forked from bikalims/bika.lims
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path__init__.py
2297 lines (2056 loc) · 98.1 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
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# This file is part of Bika LIMS
#
# Copyright 2011-2016 by it's authors.
# Some rights reserved. See LICENSE.txt, AUTHORS.txt.
from bika.lims.exportimport.dataimport import SetupDataSetList as SDL
from bika.lims.idserver import renameAfterCreation
from bika.lims.interfaces import ISetupDataSetList
from Products.CMFPlone.utils import safe_unicode, _createObjectByType
from bika.lims.utils import tmpID, to_unicode
from bika.lims.utils import to_utf8
from bika.lims import bikaMessageFactory as _
from bika.lims.utils import t
from Products.CMFCore.utils import getToolByName
from bika.lims import logger
from bika.lims.utils.analysis import create_analysis
from zope.interface import implements
from pkg_resources import resource_filename
import datetime
import os.path
import re
import transaction
def lookup(context, portal_type, **kwargs):
at = getToolByName(context, 'archetype_tool')
catalog = at.catalog_map.get(portal_type, [None])[0] or 'portal_catalog'
catalog = getToolByName(context, catalog)
kwargs['portal_type'] = portal_type
return catalog(**kwargs)[0].getObject()
def check_for_required_columns(name, data, required):
for column in required:
if not data.get(column, None):
message = _("%s has no '%s' column." % (name, column))
raise Exception(t(message))
def Float(thing):
try:
f = float(thing)
except ValueError:
f = 0.0
return f
def read_file(path):
if os.path.isfile(path):
return open(path, "rb").read()
allowed_ext = ['pdf', 'jpg', 'jpeg', 'png', 'gif', 'ods', 'odt',
'xlsx', 'doc', 'docx', 'xls', 'csv', 'txt']
allowed_ext += [e.upper() for e in allowed_ext]
for e in allowed_ext:
out = '%s.%s' % (path, e)
if os.path.isfile(out):
return open(out, "rb").read()
raise IOError("File not found: %s. Allowed extensions: %s" % (path, ','.join(allowed_ext)))
class SetupDataSetList(SDL):
implements(ISetupDataSetList)
def __call__(self):
return SDL.__call__(self, projectname="bika.lims")
class WorksheetImporter:
"""Use this as a base, for normal tabular data sheet imports.
"""
def __init__(self, context):
self.adapter_context = context
def __call__(self, lsd, workbook, dataset_project, dataset_name):
self.lsd = lsd
self.context = lsd.context
self.workbook = workbook
self.sheetname = self.__class__.__name__.replace("_", " ")
self.worksheet = workbook.get_sheet_by_name(self.sheetname)
self.dataset_project = dataset_project
self.dataset_name = dataset_name
if self.worksheet:
logger.info("Loading {0}.{1}: {2}".format(
self.dataset_project, self.dataset_name, self.sheetname))
try:
self.Import()
except IOError:
# The importer must omit the files not found inside the server filesystem (bika/lims/setupdata/test/
# if the file is loaded from 'select existing file' or bika/lims/setupdata/uploaded if it's loaded from
# 'Load from file') and finishes the import without errors. https://jira.bikalabs.com/browse/LIMS-1624
warning = "Error while loading attached file from %s. The file will not be uploaded into the system."
logger.warning(warning, self.sheetname)
self.context.plone_utils.addPortalMessage("Error while loading some attached files. "
"The files weren't uploaded into the system.")
else:
logger.info("No records found: '{0}'".format(self.sheetname))
def get_rows(self, startrow=3, worksheet=None):
"""Returns a generator for all rows in a sheet.
Each row contains a dictionary where the key is the value of the
first row of the sheet for each column.
The data values are returned in utf-8 format.
Starts to consume data from startrow
"""
headers = []
row_nr = 0
worksheet = worksheet if worksheet else self.worksheet
for row in worksheet.rows: # .iter_rows():
row_nr += 1
if row_nr == 1:
# headers = [cell.internal_value for cell in row]
headers = [cell.value for cell in row]
continue
if row_nr % 1000 == 0:
transaction.savepoint()
if row_nr <= startrow:
continue
# row = [_c(cell.internal_value).decode('utf-8') for cell in row]
new_row = []
for cell in row:
value = cell.value
if value is None:
value = ''
if isinstance(value, unicode):
value = value.encode('utf-8')
# Strip any space, \t, \n, or \r characters from the left-hand
# side, right-hand side, or both sides of the string
if isinstance(value, str):
value = value.strip(' \t\n\r')
new_row.append(value)
row = dict(zip(headers, new_row))
# parse out addresses
for add_type in ['Physical', 'Postal', 'Billing']:
row[add_type] = {}
if add_type + "_Address" in row:
for key in ['Address', 'City', 'State', 'District', 'Zip', 'Country']:
row[add_type][key] = str(row.get("%s_%s" % (add_type, key), ''))
yield row
def get_file_data(self, filename):
if filename:
try:
path = resource_filename(
self.dataset_project,
"setupdata/%s/%s" % (self.dataset_name, filename))
file_data = open(path, "rb").read()
except:
file_data = None
else:
file_data = None
return file_data
def to_bool(self, value):
""" Converts a sheet string value to a boolean value.
Needed because of utf-8 conversions
"""
try:
value = value.lower()
except:
pass
try:
value = value.encode('utf-8')
except:
pass
try:
value = int(value)
except:
pass
if value in ('true', 1):
return True
else:
return False
def to_int(self, value, default=0):
""" Converts a value o a int. Returns default if the conversion fails.
"""
try:
return int(value)
except ValueError:
try:
return int(default)
except:
return 0
def to_float(self, value, default=0):
""" Converts a value o a float. Returns default if the conversion fails.
"""
try:
return float(value)
except ValueError:
try:
return float(default)
except:
return 0.0
def defer(self, **kwargs):
self.lsd.deferred.append(kwargs)
def Import(self):
""" Override this.
XXX Simple generic sheet importer
"""
def fill_addressfields(self, row, obj):
""" Fills the address fields for the specified object if allowed:
PhysicalAddress, PostalAddress, CountryState, BillingAddress
"""
addresses = {}
for add_type in ['Physical', 'Postal', 'Billing', 'CountryState']:
addresses[add_type] = {}
for key in ['Address', 'City', 'State', 'District', 'Zip', 'Country']:
addresses[add_type][key.lower()] = str(row.get("%s_%s" % (add_type, key), ''))
if addresses['CountryState']['country'] == '' \
and addresses['CountryState']['state'] == '':
addresses['CountryState']['country'] = addresses['Physical']['country']
addresses['CountryState']['state'] = addresses['Physical']['state']
if hasattr(obj, 'setPhysicalAddress'):
obj.setPhysicalAddress(addresses['Physical'])
if hasattr(obj, 'setPostalAddress'):
obj.setPostalAddress(addresses['Postal'])
if hasattr(obj, 'setCountryState'):
obj.setCountryState(addresses['CountryState'])
if hasattr(obj, 'setBillingAddress'):
obj.setBillingAddress(addresses['Billing'])
def fill_contactfields(self, row, obj):
""" Fills the contact fields for the specified object if allowed:
EmailAddress, Phone, Fax, BusinessPhone, BusinessFax, HomePhone,
MobilePhone
"""
fieldnames = ['EmailAddress',
'Phone',
'Fax',
'BusinessPhone',
'BusinessFax',
'HomePhone',
'MobilePhone',
]
schema = obj.Schema()
fields = dict([(field.getName(), field) for field in schema.fields()])
for fieldname in fieldnames:
try:
field = fields[fieldname]
except:
if fieldname in row:
logger.info("Address field %s not found on %s"%(fieldname,obj))
continue
value = row.get(fieldname, '')
field.set(obj, value)
def get_object(self, catalog, portal_type, title=None, **kwargs):
"""This will return an object from the catalog.
Logs a message and returns None if no object or multiple objects found.
All keyword arguments are passed verbatim to the contentFilter
"""
if not title and not kwargs:
return None
contentFilter = {"portal_type": portal_type}
if title:
contentFilter['title'] = to_unicode(title)
contentFilter.update(kwargs)
brains = catalog(contentFilter)
if len(brains) > 1:
logger.info("More than one object found for %s" % contentFilter)
return None
elif len(brains) == 0:
if portal_type == 'AnalysisService':
brains = catalog(portal_type=portal_type, getKeyword=title)
if brains:
return brains[0].getObject()
logger.info("No objects found for %s" % contentFilter)
return None
else:
return brains[0].getObject()
class Sub_Groups(WorksheetImporter):
def Import(self):
folder = self.context.bika_setup.bika_subgroups
for row in self.get_rows(3):
if 'title' in row and row['title']:
obj = _createObjectByType("SubGroup", folder, tmpID())
obj.edit(title=row['title'],
description=row['description'],
SortKey=row['SortKey'])
obj.unmarkCreationFlag()
renameAfterCreation(obj)
class Lab_Information(WorksheetImporter):
def Import(self):
laboratory = self.context.bika_setup.laboratory
values = {}
for row in self.get_rows(3):
values[row['Field']] = row['Value']
if values['AccreditationBodyLogo']:
path = resource_filename(
self.dataset_project,
"setupdata/%s/%s" % (self.dataset_name,
values['AccreditationBodyLogo']))
try:
file_data = read_file(path)
except Exception as msg:
file_data = None
logger.warning(msg[0] + " Error on sheet: " + self.sheetname)
else:
file_data = None
laboratory.edit(
Name=values['Name'],
LabURL=values['LabURL'],
Confidence=values['Confidence'],
LaboratoryAccredited=self.to_bool(values['LaboratoryAccredited']),
AccreditationBodyLong=values['AccreditationBodyLong'],
AccreditationBody=values['AccreditationBody'],
AccreditationBodyURL=values['AccreditationBodyURL'],
Accreditation=values['Accreditation'],
AccreditationReference=values['AccreditationReference'],
AccreditationBodyLogo=file_data,
TaxNumber=values['TaxNumber'],
)
self.fill_contactfields(values, laboratory)
self.fill_addressfields(values, laboratory)
class Lab_Contacts(WorksheetImporter):
def Import(self):
folder = self.context.bika_setup.bika_labcontacts
portal_groups = getToolByName(self.context, 'portal_groups')
portal_registration = getToolByName(
self.context, 'portal_registration')
rownum = 2
for row in self.get_rows(3):
rownum+=1
if not row.get('Firstname',None):
continue
# Username already exists?
username = row.get('Username','')
fullname = ('%s %s' % (row['Firstname'], row.get('Surname', ''))).strip()
if username:
username = safe_unicode(username).encode('utf-8')
bsc = getToolByName(self.context, 'bika_setup_catalog')
exists = [o.getObject() for o in bsc(portal_type="LabContact") if o.getObject().getUsername()==username]
if exists:
error = "Lab Contact: username '{0}' in row {1} already exists. This contact will be omitted.".format(username, str(rownum))
logger.error(error)
continue
# Is there a signature file defined? Try to get the file first.
signature = None
if row.get('Signature'):
signature = self.get_file_data(row['Signature'])
if not signature:
warning = "Lab Contact: Cannot load the signature file '{0}' for user '{1}'. The contact will be created, but without a signature image".format(row['Signature'], username)
logger.warning(warning)
obj = _createObjectByType("LabContact", folder, tmpID())
obj.edit(
title=fullname,
Salutation=row.get('Salutation', ''),
Firstname=row['Firstname'],
Surname=row.get('Surname', ''),
JobTitle=row.get('JobTitle', ''),
Username=row.get('Username', ''),
Signature=signature
)
obj.unmarkCreationFlag()
renameAfterCreation(obj)
self.fill_contactfields(row, obj)
self.fill_addressfields(row, obj)
if row['Department_title']:
self.defer(src_obj=obj,
src_field='Department',
dest_catalog='bika_setup_catalog',
dest_query={'portal_type': 'Department',
'title': row['Department_title']}
)
# Create Plone user
if not row['Username']:
warn = "Lab Contact: No username defined for user '{0}' in row {1}. Contact created, but without access credentials.".format(fullname, str(rownum))
logger.warning(warn)
if not row.get('EmailAddress', ''):
warn = "Lab Contact: No Email defined for user '{0}' in row {1}. Contact created, but without access credentials.".format(fullname, str(rownum))
logger.warning(warn)
if(row['Username'] and row.get('EmailAddress','')):
username = safe_unicode(row['Username']).encode('utf-8')
passw = row['Password']
if not passw:
warn = "Lab Contact: No password defined for user '{0}' in row {1}. Password established automatically to '{3}'".format(username, str(rownum), username)
logger.warning(warn)
passw = username
try:
member = portal_registration.addMember(
username,
passw,
properties={
'username': username,
'email': row['EmailAddress'],
'fullname': fullname}
)
except Exception as msg:
logger.error("Client Contact: Error adding user (%s): %s" % (msg, username))
continue
groups = row.get('Groups', '')
if not groups:
warn = "Lab Contact: No groups defined for user '{0}' in row {1}. Group established automatically to 'Analysts'".format(username, str(rownum))
logger.warning(warn)
groups = 'Analysts'
group_ids = [g.strip() for g in groups.split(',')]
# Add user to all specified groups
for group_id in group_ids:
group = portal_groups.getGroupById(group_id)
if group:
group.addMember(username)
roles = row.get('Roles', '')
if roles:
role_ids = [r.strip() for r in roles.split(',')]
# Add user to all specified roles
for role_id in role_ids:
member._addRole(role_id)
# If user is in LabManagers, add Owner local role on clients
# folder
if 'LabManager' in group_ids:
self.context.clients.manage_setLocalRoles(
username, ['Owner', ])
# Now we have the lab contacts registered, try to assign the managers
# to each department if required
sheet = self.workbook.get_sheet_by_name("Lab Departments")
bsc = getToolByName(self.context, 'bika_setup_catalog')
for row in self.get_rows(3, sheet):
if row['title'] and row['LabContact_Username']:
dept = self.get_object(bsc, "Department", row.get('title'))
if dept and not dept.getManager():
username = safe_unicode(row['LabContact_Username']).encode('utf-8')
exists = [o.getObject() for o in bsc(portal_type="LabContact") if o.getObject().getUsername()==username]
if exists:
dept.setManager(exists[0].UID())
class Lab_Departments(WorksheetImporter):
def Import(self):
folder = self.context.bika_setup.bika_departments
bsc = getToolByName(self.context, 'bika_setup_catalog')
lab_contacts = [o.getObject() for o in bsc(portal_type="LabContact")]
for row in self.get_rows(3):
if row['title']:
obj = _createObjectByType("Department", folder, tmpID())
obj.edit(title=row['title'],
description=row.get('description', ''))
manager = None
for contact in lab_contacts:
if contact.getUsername() == row['LabContact_Username']:
manager = contact
break
if manager:
obj.setManager(manager.UID())
else:
message = "Department: lookup of '%s' in LabContacts/Username failed." % row[
'LabContact_Username']
logger.info(message)
obj.unmarkCreationFlag()
renameAfterCreation(obj)
class Lab_Products(WorksheetImporter):
def Import(self):
context = self.context
# Refer to the default folder
folder = self.context.bika_setup.bika_labproducts
# Iterate through the rows
for row in self.get_rows(3):
# Create the SRTemplate object
obj = _createObjectByType('LabProduct', folder, tmpID())
# Apply the row values
obj.edit(
title=row.get('title', 'Unknown'),
description=row.get('description', ''),
Volume=row.get('volume', 0),
Unit=str(row.get('unit', 0)),
Price=str(row.get('price', 0)),
)
# Rename the new object
renameAfterCreation(obj)
class Clients(WorksheetImporter):
def Import(self):
folder = self.context.clients
for row in self.get_rows(3):
obj = _createObjectByType("Client", folder, tmpID())
if not row['Name']:
message = "Client %s has no Name"
raise Exception(message)
if not row['ClientID']:
message = "Client %s has no Client ID"
raise Exception(message)
obj.edit(Name=row['Name'],
ClientID=row['ClientID'],
MemberDiscountApplies=row[
'MemberDiscountApplies'] and True or False,
BulkDiscount=row['BulkDiscount'] and True or False,
TaxNumber=row.get('TaxNumber', ''),
AccountNumber=row.get('AccountNumber', '')
)
self.fill_contactfields(row, obj)
self.fill_addressfields(row, obj)
obj.unmarkCreationFlag()
renameAfterCreation(obj)
class Client_Contacts(WorksheetImporter):
def Import(self):
portal_groups = getToolByName(self.context, 'portal_groups')
pc = getToolByName(self.context, 'portal_catalog')
for row in self.get_rows(3):
client = pc(portal_type="Client",
getName=row['Client_title'])
if len(client) == 0:
client_contact = "%(Firstname)s %(Surname)s" % row
error = "Client invalid: '%s'. The Client Contact %s will not be uploaded."
logger.error(error, row['Client_title'], client_contact)
continue
client = client[0].getObject()
contact = _createObjectByType("Contact", client, tmpID())
fullname = "%(Firstname)s %(Surname)s" % row
pub_pref = [x.strip() for x in
row.get('PublicationPreference', '').split(",")]
contact.edit(
Salutation=row.get('Salutation', ''),
Firstname=row.get('Firstname', ''),
Surname=row.get('Surname', ''),
Username=row['Username'],
JobTitle=row.get('JobTitle', ''),
Department=row.get('Department', ''),
PublicationPreference=pub_pref,
AttachmentsPermitted=row[
'AttachmentsPermitted'] and True or False,
)
self.fill_contactfields(row, contact)
self.fill_addressfields(row, contact)
contact.unmarkCreationFlag()
renameAfterCreation(contact)
# CC Contacts
if row['CCContacts']:
names = [x.strip() for x in row['CCContacts'].split(",")]
for _fullname in names:
self.defer(src_obj=contact,
src_field='CCContact',
dest_catalog='portal_catalog',
dest_query={'portal_type': 'Contact',
'getFullname': _fullname}
)
## Create Plone user
username = safe_unicode(row['Username']).encode('utf-8')
password = safe_unicode(row['Password']).encode('utf-8')
if(username):
try:
member = self.context.portal_registration.addMember(
username,
password,
properties={
'username': username,
'email': row['EmailAddress'],
'fullname': fullname}
)
except Exception as msg:
logger.info("Error adding user (%s): %s" % (msg, username))
contact.aq_parent.manage_setLocalRoles(row['Username'], ['Owner', ])
# add user to Clients group
group = portal_groups.getGroupById('Clients')
group.addMember(username)
class Container_Types(WorksheetImporter):
def Import(self):
folder = self.context.bika_setup.bika_containertypes
for row in self.get_rows(3):
if not row['title']:
continue
obj = _createObjectByType("ContainerType", folder, tmpID())
obj.edit(title=row['title'],
description=row.get('description', ''))
obj.unmarkCreationFlag()
renameAfterCreation(obj)
class Preservations(WorksheetImporter):
def Import(self):
folder = self.context.bika_setup.bika_preservations
for row in self.get_rows(3):
if not row['title']:
continue
obj = _createObjectByType("Preservation", folder, tmpID())
RP = {
'days': int(row['RetentionPeriod_days'] and row['RetentionPeriod_days'] or 0),
'hours': int(row['RetentionPeriod_hours'] and row['RetentionPeriod_hours'] or 0),
'minutes': int(row['RetentionPeriod_minutes'] and row['RetentionPeriod_minutes'] or 0),
}
obj.edit(title=row['title'],
description=row.get('description', ''),
RetentionPeriod=RP)
obj.unmarkCreationFlag()
renameAfterCreation(obj)
class Containers(WorksheetImporter):
def Import(self):
folder = self.context.bika_setup.bika_containers
bsc = getToolByName(self.context, 'bika_setup_catalog')
for row in self.get_rows(3):
if not row['title']:
continue
obj = _createObjectByType("Container", folder, tmpID())
obj.edit(
title=row['title'],
description=row.get('description', ''),
Capacity=row.get('Capacity', 0),
PrePreserved=self.to_bool(row['PrePreserved'])
)
if row['ContainerType_title']:
ct = self.get_object(bsc, 'ContainerType', row.get('ContainerType_title',''))
if ct:
obj.setContainerType(ct)
if row['Preservation_title']:
pres = self.get_object(bsc, 'Preservation',row.get('Preservation_title',''))
if pres:
obj.setPreservation(pres)
obj.unmarkCreationFlag()
renameAfterCreation(obj)
class Suppliers(WorksheetImporter):
def Import(self):
folder = self.context.bika_setup.bika_suppliers
for row in self.get_rows(3):
obj = _createObjectByType("Supplier", folder, tmpID())
if row['Name']:
obj.edit(
Name=row.get('Name', ''),
TaxNumber=row.get('TaxNumber', ''),
AccountType=row.get('AccountType', {}),
AccountName=row.get('AccountName', {}),
AccountNumber=row.get('AccountNumber', ''),
BankName=row.get('BankName', ''),
BankBranch=row.get('BankBranch', ''),
SWIFTcode=row.get('SWIFTcode', ''),
IBN=row.get('IBN', ''),
NIB=row.get('NIB', ''),
Website=row.get('Website', ''),
)
self.fill_contactfields(row, obj)
self.fill_addressfields(row, obj)
obj.unmarkCreationFlag()
renameAfterCreation(obj)
class Supplier_Contacts(WorksheetImporter):
def Import(self):
bsc = getToolByName(self.context, 'bika_setup_catalog')
for row in self.get_rows(3):
if not row['Supplier_Name']:
continue
if not row['Firstname']:
continue
folder = bsc(portal_type="Supplier",
Title=row['Supplier_Name'])
if not folder:
continue
folder = folder[0].getObject()
obj = _createObjectByType("SupplierContact", folder, tmpID())
obj.edit(
Firstname=row['Firstname'],
Surname=row.get('Surname', ''),
Username=row.get('Username')
)
self.fill_contactfields(row, obj)
self.fill_addressfields(row, obj)
obj.unmarkCreationFlag()
renameAfterCreation(obj)
class Manufacturers(WorksheetImporter):
def Import(self):
folder = self.context.bika_setup.bika_manufacturers
for row in self.get_rows(3):
obj = _createObjectByType("Manufacturer", folder, tmpID())
if row['title']:
obj.edit(
title=row['title'],
description=row.get('description', '')
)
self.fill_addressfields(row, obj)
obj.unmarkCreationFlag()
renameAfterCreation(obj)
class Instrument_Types(WorksheetImporter):
def Import(self):
folder = self.context.bika_setup.bika_instrumenttypes
for row in self.get_rows(3):
obj = _createObjectByType("InstrumentType", folder, tmpID())
obj.edit(
title=row['title'],
description=row.get('description', ''))
obj.unmarkCreationFlag()
renameAfterCreation(obj)
class Instruments(WorksheetImporter):
def Import(self):
folder = self.context.bika_setup.bika_instruments
bsc = getToolByName(self.context, 'bika_setup_catalog')
pc = getToolByName(self.context, 'portal_catalog')
for row in self.get_rows(3):
if ('Type' not in row
or 'Supplier' not in row
or 'Brand' not in row):
logger.info("Unable to import '%s'. Missing supplier, manufacturer or type" % row.get('title',''))
continue
obj = _createObjectByType("Instrument", folder, tmpID())
obj.edit(
title=row.get('title', ''),
AssetNumber=row.get('assetnumber', ''),
description=row.get('description', ''),
Type=row.get('Type', ''),
Brand=row.get('Brand', ''),
Model=row.get('Model', ''),
SerialNo=row.get('SerialNo', ''),
DataInterface=row.get('DataInterface', ''),
Location=row.get('Location', ''),
InstallationDate=row.get('Instalationdate', ''),
UserManualID=row.get('UserManualID', ''),
)
instrumenttype = self.get_object(bsc, 'InstrumentType', title=row.get('Type'))
manufacturer = self.get_object(bsc, 'Manufacturer', title=row.get('Brand'))
supplier = self.get_object(bsc, 'Supplier', getName=row.get('Supplier', ''))
method = self.get_object(pc, 'Method', title=row.get('Method'))
obj.setInstrumentType(instrumenttype)
obj.setManufacturer(manufacturer)
obj.setSupplier(supplier)
obj.setMethod([method])
# Attaching the instrument's photo
if row.get('Photo', None):
path = resource_filename(
self.dataset_project,
"setupdata/%s/%s" % (self.dataset_name,
row['Photo'])
)
try:
file_data = read_file(path)
obj.setPhoto(file_data)
except Exception as msg:
file_data = None
logger.warning(msg[0] + " Error on sheet: " + self.sheetname)
# Attaching the Installation Certificate if exists
if row.get('InstalationCertificate', None):
path = resource_filename(
self.dataset_project,
"setupdata/%s/%s" % (self.dataset_name,
row['InstalationCertificate'])
)
try:
file_data = read_file(path)
obj.setInstallationCertificate(file_data)
except Exception as msg:
logger.warning(msg[0] + " Error on sheet: " + self.sheetname)
# Attaching the Instrument's manual if exists
if row.get('UserManualFile', None):
row_dict = {'DocumentID': row.get('UserManualID', 'manual'),
'DocumentVersion': '',
'DocumentLocation': '',
'DocumentType': 'Manual',
'File': row.get('UserManualFile', None)
}
addDocument(self, row_dict, obj)
obj.unmarkCreationFlag()
renameAfterCreation(obj)
class Instrument_Validations(WorksheetImporter):
def Import(self):
bsc = getToolByName(self.context, 'bika_setup_catalog')
for row in self.get_rows(3):
if not row.get('instrument', None) or not row.get('title', None):
continue
folder = self.get_object(bsc, 'Instrument', row.get('instrument'))
if folder:
obj = _createObjectByType("InstrumentValidation", folder, tmpID())
obj.edit(
title=row['title'],
DownFrom=row.get('downfrom', ''),
DownTo=row.get('downto', ''),
Validator=row.get('validator', ''),
Considerations=row.get('considerations', ''),
WorkPerformed=row.get('workperformed', ''),
Remarks=row.get('remarks', ''),
DateIssued=row.get('DateIssued', ''),
ReportID=row.get('ReportID', '')
)
# Getting lab contacts
bsc = getToolByName(self.context, 'bika_setup_catalog')
lab_contacts = [o.getObject() for o in bsc(portal_type="LabContact", inactive_state='active')]
for contact in lab_contacts:
if contact.getFullname() == row.get('Worker', ''):
obj.setWorker(contact.UID())
obj.unmarkCreationFlag()
renameAfterCreation(obj)
class Instrument_Calibrations(WorksheetImporter):
def Import(self):
bsc = getToolByName(self.context, 'bika_setup_catalog')
for row in self.get_rows(3):
if not row.get('instrument', None) or not row.get('title', None):
continue
folder = self.get_object(bsc, 'Instrument', row.get('instrument'))
if folder:
obj = _createObjectByType("InstrumentCalibration", folder, tmpID())
obj.edit(
title=row['title'],
DownFrom=row.get('downfrom', ''),
DownTo=row.get('downto', ''),
Calibrator=row.get('calibrator', ''),
Considerations=row.get('considerations', ''),
WorkPerformed=row.get('workperformed', ''),
Remarks=row.get('remarks', ''),
DateIssued=row.get('DateIssued', ''),
ReportID=row.get('ReportID', '')
)
# Gettinginstrument lab contacts
bsc = getToolByName(self.context, 'bika_setup_catalog')
lab_contacts = [o.getObject() for o in bsc(portal_type="LabContact", nactive_state='active')]
for contact in lab_contacts:
if contact.getFullname() == row.get('Worker', ''):
obj.setWorker(contact.UID())
obj.unmarkCreationFlag()
renameAfterCreation(obj)
class Instrument_Certifications(WorksheetImporter):
def Import(self):
bsc = getToolByName(self.context, 'bika_setup_catalog')
for row in self.get_rows(3):
if not row['instrument'] or not row['title']:
continue
folder = self.get_object(bsc, 'Instrument', row.get('instrument',''))
if folder:
obj = _createObjectByType("InstrumentCertification", folder, tmpID())
today = datetime.date.today()
certificate_expire_date = today.strftime('%d/%m') + '/' + str(today.year+1) \
if row.get('validto', '') == '' else row.get('validto')
certificate_start_date = today.strftime('%d/%m/%Y') \
if row.get('validfrom', '') == '' else row.get('validfrom')
obj.edit(
title=row['title'],
AssetNumber=row.get('assetnumber', ''),
Date=row.get('date', ''),
ValidFrom=certificate_start_date,
ValidTo=certificate_expire_date,
Agency=row.get('agency', ''),
Remarks=row.get('remarks', ''),
)
# Attaching the Report Certificate if exists
if row.get('report', None):
path = resource_filename(
self.dataset_project,
"setupdata/%s/%s" % (self.dataset_name,
row['report'])
)
try:
file_data = read_file(path)
obj.setDocument(file_data)
except Exception as msg:
file_data = None
logger.warning(msg[0] + " Error on sheet: " + self.sheetname)
# Getting lab contacts
bsc = getToolByName(self.context, 'bika_setup_catalog')
lab_contacts = [o.getObject() for o in bsc(portal_type="LabContact", nactive_state='active')]
for contact in lab_contacts:
if contact.getFullname() == row.get('preparedby', ''):
obj.setPreparator(contact.UID())
if contact.getFullname() == row.get('approvedby', ''):
obj.setValidator(contact.UID())
obj.unmarkCreationFlag()
renameAfterCreation(obj)
class Instrument_Documents(WorksheetImporter):
def Import(self):
bsc = getToolByName(self.context, 'bika_setup_catalog')
for row in self.get_rows(3):
if not row.get('instrument', ''):
continue
folder = self.get_object(bsc, 'Instrument', row.get('instrument', ''))
addDocument(self, row, folder)
def addDocument(self, row_dict, folder):
"""
This function adds a multifile object to the instrument folder
:param row_dict: the dictionary which contains the document information
:param folder: the instrument object
"""
if folder:
# This content type need a file
if row_dict.get('File', None):
path = resource_filename(
self.dataset_project,
"setupdata/%s/%s" % (self.dataset_name,
row_dict['File'])
)
try:
file_data = read_file(path)
except Exception as msg:
file_data = None
logger.warning(msg[0] + " Error on sheet: " + self.sheetname)
# Obtain all created instrument documents content type
catalog = getToolByName(self.context, 'bika_setup_catalog')
documents_brains = catalog.searchResults({'portal_type': 'Multifile'})
# If a the new document has the same DocumentID as a created document, this object won't be created.
idAlreadyInUse = False
for item in documents_brains:
if item.getObject().getDocumentID() == row_dict.get('DocumentID', ''):
warning = "The ID '%s' used for this document is already in use on instrument '%s', consequently " \
"the file hasn't been upload." % (row_dict.get('DocumentID', ''), row_dict.get('instrument', ''))
self.context.plone_utils.addPortalMessage(warning)
idAlreadyInUse = True
if not idAlreadyInUse:
obj = _createObjectByType("Multifile", folder, tmpID())
obj.edit(
DocumentID=row_dict.get('DocumentID', ''),
DocumentVersion=row_dict.get('DocumentVersion', ''),
DocumentLocation=row_dict.get('DocumentLocation', ''),
DocumentType=row_dict.get('DocumentType', ''),
File=file_data
)
obj.unmarkCreationFlag()
renameAfterCreation(obj)
class Instrument_Maintenance_Tasks(WorksheetImporter):
def Import(self):
bsc = getToolByName(self.context, 'bika_setup_catalog')
for row in self.get_rows(3):
if not row['instrument'] or not row['title'] or not row['type']:
continue
folder = self.get_object(bsc, 'Instrument',row.get('instrument'))
if folder:
obj = _createObjectByType("InstrumentMaintenanceTask", folder, tmpID())
try:
cost = "%.2f" % (row.get('cost', 0))
except: