-
Notifications
You must be signed in to change notification settings - Fork 559
/
s3widgets.py
10131 lines (8655 loc) · 356 KB
/
s3widgets.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
# -*- coding: utf-8 -*-
""" Custom UI Widgets
@requires: U{B{I{gluon}} <http://web2py.com>}
@copyright: 2009-2021 (c) Sahana Software Foundation
@license: MIT
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
Note:
Widgets are processed upon form submission (before form validation)
in addition to when generating new forms (so are often processed twice)
"""
__all__ = ("S3ACLWidget",
"S3AddObjectWidget",
"S3AddPersonWidget",
"S3AgeWidget",
"S3AutocompleteWidget",
"S3BooleanWidget",
"S3CascadeSelectWidget",
"S3ColorPickerWidget",
"S3CalendarWidget",
"S3DateWidget",
"S3DateTimeWidget",
"S3HoursWidget",
"S3EmbeddedComponentWidget",
"S3GroupedOptionsWidget",
#"S3RadioOptionsWidget",
"S3HiddenWidget",
"S3HierarchyWidget",
"S3HumanResourceAutocompleteWidget",
"S3ImageCropWidget",
"S3KeyValueWidget",
# Only used inside this module
#"S3LatLonWidget",
"S3LocationAutocompleteWidget",
"S3LocationDropdownWidget",
"S3LocationLatLonWidget",
"S3PasswordWidget",
"S3PhoneWidget",
"S3QRInput",
"S3Selector",
"S3LocationSelector",
"S3MultiSelectWidget",
"S3OrganisationAutocompleteWidget",
"S3OrganisationHierarchyWidget",
"S3PersonAutocompleteWidget",
"S3PentityAutocompleteWidget",
"S3PriorityListWidget",
"S3SelectWidget",
"S3SiteAutocompleteWidget",
"S3SliderWidget",
"S3StringWidget",
"S3TimeIntervalWidget",
#"S3UploadWidget",
"S3WeeklyHoursWidget",
"S3FixedOptionsWidget",
"S3QuestionEditorWidget",
"CheckboxesWidgetS3",
"s3_comments_widget",
"s3_richtext_widget",
"search_ac",
"S3XMLContents",
"S3TagCheckboxWidget",
"ICON",
)
import datetime
import json
import os
import re
from uuid import uuid4
try:
from dateutil.relativedelta import relativedelta
except ImportError:
import sys
sys.stderr.write("ERROR: dateutil module needed for Date handling\n")
raise
from gluon import *
# Here are dependencies listed for reference:
#from gluon import current
#from gluon.html import *
#from gluon.http import HTTP
#from gluon.validators import *
from gluon.html import BUTTON
from gluon.languages import lazyT
from gluon.sqlhtml import *
from gluon.storage import Storage
from .s3datetime import S3Calendar, S3DateTime
from .s3utils import *
from .s3validators import *
DEFAULT = lambda:None
repr_select = lambda l: len(l.name) > 48 and "%s..." % l.name[:44] or l.name
# Compact JSON encoding
SEPARATORS = (",", ":")
# =============================================================================
class S3ACLWidget(CheckboxesWidget):
"""
Widget class for ACLs
TODO:
Add option dependency logic (JS)
Configurable vertical/horizontal alignment
"""
@staticmethod
def widget(field, value, **attributes):
requires = field.requires
if not isinstance(requires, (list, tuple)):
requires = [requires]
if requires:
if hasattr(requires[0], "options"):
options = requires[0].options()
values = []
for k in options:
if isinstance(k, (list, tuple)):
k = k[0]
try:
flag = int(k)
if flag == 0:
if value == 0:
values.append(k)
break
else:
continue
elif value and value & flag == flag:
values.append(k)
except ValueError:
pass
value = values
#return CheckboxesWidget.widget(field, value, **attributes)
attr = OptionsWidget._attributes(field, {}, **attributes)
options = [(k, v) for k, v in options if k != ""]
opts = []
cols = attributes.get("cols", 1)
totals = len(options)
mods = totals % cols
rows = totals / cols
if mods:
rows += 1
for r_index in range(rows):
tds = []
for k, v in options[r_index*cols:(r_index+1)*cols]:
tds.append(TD(INPUT(_type = "checkbox",
_name = attr.get("_name", field.name),
requires = attr.get("requires", None),
hideerror = True,
_value = k,
value = (k in value)
),
v
))
opts.append(TR(tds))
if opts:
opts[-1][0][0]["hideerror"] = False
return TABLE(*opts, **attr)
# was values = re.compile("[\w\-:]+").findall(str(value))
#values = not isinstance(value,(list,tuple)) and [value] or value
#requires = field.requires
#if not isinstance(requires, (list, tuple)):
#requires = [requires]
#if requires:
#if hasattr(requires[0], "options"):
#options = requires[0].options()
#else:
#raise SyntaxError, "widget cannot determine options of %s" \
#% field
# =============================================================================
class S3AddObjectWidget(FormWidget):
"""
This widget displays an inline form loaded via AJAX on demand.
Status:
Currently Unused
In the browser:
A load request must made to this widget to enable it.
The load request must include:
- a URL for the form
after a successful submission, the response callback is handed the
response.
"""
def __init__(self,
form_url,
table_name,
dummy_field_selector,
on_show,
on_hide
):
self.form_url = form_url
self.table_name = table_name
self.dummy_field_selector = dummy_field_selector
self.on_show = on_show
self.on_hide = on_hide
def __call__(self, field, value, **attributes):
T = current.T
s3 = current.response.s3
if s3.debug:
script_name = "/%s/static/scripts/jquery.ba-resize.js"
else:
script_name = "/%s/static/scripts/jquery.ba-resize.min.js"
if script_name not in s3.scripts:
s3.scripts.append(script_name)
return TAG[""](
# @ToDo: Move to Static
SCRIPT('''
$(function () {
var form_field = $('#%(form_field_name)s')
var throbber = $('<div id="%(form_field_name)s_ajax_throbber" class="throbber"/>')
throbber.hide()
throbber.insertAfter(form_field)
function request_add_form() {
throbber.show()
var dummy_field = $('%(dummy_field_selector)s')
// create an element for the form
var form_iframe = document.createElement('iframe')
var $form_iframe = $(form_iframe)
$form_iframe.attr('id', '%(form_field_name)s_form_iframe')
$form_iframe.attr('frameborder', '0')
$form_iframe.attr('scrolling', 'no')
$form_iframe.attr('src', '%(form_url)s')
var initial_iframe_style = {
width: add_object_link.width(),
height: add_object_link.height()
}
$form_iframe.css(initial_iframe_style)
function close_iframe() {
$form_iframe.unload()
form_iframe.contentWindow.close()
//iframe_controls.remove()
$form_iframe.animate(
initial_iframe_style,
{
complete: function () {
$form_iframe.remove()
add_object_link.show()
%(on_hide)s
dummy_field.show()
}
}
)
}
function reload_iframe() {
form_iframe.contentWindow.location.reload(true)
}
function resize_iframe_to_fit_content() {
var form_iframe_content = $form_iframe.contents().find('body');
// do first animation smoothly
$form_iframe.animate(
{
height: form_iframe_content.outerHeight(true),
width: 500
},
{
duration: jQuery.resize.delay,
complete: function () {
// iframe's own animations should be instant, as they
// have their own smoothing (e.g. expanding error labels)
function resize_iframe_to_fit_content_immediately() {
$form_iframe.css({
height: form_iframe_content.outerHeight(true),
width:500
})
}
// if the iframe content resizes, resize the iframe
// this depends on Ben Alman's resize plugin
form_iframe_content.bind(
'resize',
resize_iframe_to_fit_content_immediately
)
// when unloading, unbind the resizer (remove poller)
$form_iframe.bind(
'unload',
function () {
form_iframe_content.unbind(
'resize',
resize_iframe_to_fit_content_immediately
)
//iframe_controls.hide()
}
)
// there may have been content changes during animation
// so resize to make sure they are shown.
form_iframe_content.resize()
//iframe_controls.show()
%(on_show)s
}
}
)
}
function iframe_loaded() {
dummy_field.hide()
resize_iframe_to_fit_content()
form_iframe.contentWindow.close_iframe = close_iframe
throbber.hide()
}
$form_iframe.bind('load', iframe_loaded)
function set_object_id() {
// the server must give the iframe the object
// id of the created object for the field
// the iframe must also close itself.
var created_object_representation = form_iframe.contentWindow.created_object_representation
if (created_object_representation) {
dummy_field.val(created_object_representation)
}
var created_object_id = form_iframe.contentWindow.created_object_id
if (created_object_id) {
form_field.val(created_object_id)
close_iframe()
}
}
$form_iframe.bind('load', set_object_id)
add_object_link.hide()
/*
var iframe_controls = $('<span class="iframe_controls" style="float:right; text-align:right;"></span>')
iframe_controls.hide()
var close_button = $('<a>%(Close)s </a>')
close_button.click(close_iframe)
var reload_button = $('<a>%(Reload)s </a>')
reload_button.click(reload_iframe)
iframe_controls.append(close_button)
iframe_controls.append(reload_button)
iframe_controls.insertBefore(add_object_link)
*/
$form_iframe.insertAfter(add_object_link)
}
var add_object_link = $('<a>%(Add)s</a>')
add_object_link.click(request_add_form)
add_object_link.insertAfter(form_field)
})''' % {"field_name": field.name,
"form_field_name": "_".join((self.table_name, field.name)),
"form_url": self.form_url,
"dummy_field_selector": self.dummy_field_selector(self.table_name, field.name),
"on_show": self.on_show,
"on_hide": self.on_hide,
"Add": T("Add..."),
"Reload": T("Reload"),
"Close": T("Close"),
}
)
)
# =============================================================================
class S3AddPersonWidget(FormWidget):
"""
Widget for person_id or human_resource_id fields that
allows to either select an existing person/hrm (autocomplete), or to
create a new person/hrm record inline
Features:
- embedded fields configurable in deployment settings
- can use single name field (with on-submit name splitting),
alternatively separate fields for first/middle/last names
- can check for possible duplicates during data entry
- fully encapsulated, works with regular validators (IS_ONE_OF)
=> Uses client-side script s3.ui.addperson.js (injected)
"""
def __init__(self,
controller = None,
separate_name_fields = None,
father_name = None,
grandfather_name = None,
year_of_birth = None,
first_name_only = None,
pe_label = False,
):
"""
Args:
controller: controller for autocomplete
separate_name_fields: use separate name fields, overrides
deployment setting
father_name: expose father name field, overrides
deployment setting
grandfather_name: expose grandfather name field, overrides
deployment setting
year_of_birth: use just year-of-birth field instead of full
date-of-birth, overrides deployment setting
first_name_only: treat single name field entirely as
first name (=do not split into name parts),
overrides auto-detection, otherwise default
for right-to-left written languages
pe_label: expose ID label field
"""
self.controller = controller
self.separate_name_fields = separate_name_fields
self.father_name = father_name
self.grandfather_name = grandfather_name
self.year_of_birth = year_of_birth
self.first_name_only = first_name_only
self.pe_label = pe_label
self.hrm = False
self.fields = {}
self.labels = {}
self.required = {}
# -------------------------------------------------------------------------
def __call__(self, field, value, **attributes):
"""
Widget builder
Args:
field: the Field
value: the current or default value
attributes: additional HTML attributes for the widget
"""
T = current.T
s3db = current.s3db
# Attributes for the main input
default = {"_type": "text",
"value": (value is not None and str(value)) or "",
}
attr = StringWidget._attributes(field, default, **attributes)
# Translations
i18n = {"none_of_the_above": T("None of the above"),
"loading": T("loading")
}
# Determine reference type
reference_type = str(field.type)[10:]
if reference_type == "pr_person":
hrm = False
fn = "person"
elif reference_type == "hrm_human_resource":
self.hrm = hrm = True
fn = "human_resource"
else:
raise TypeError("S3AddPersonWidget: unsupported field type %s" % field.type)
settings = current.deployment_settings
# Field label overrides
# (all other labels are looked up from the corresponding Field)
labels = {"full_name": T(settings.get_pr_label_fullname()),
"email": T("Email"),
"mobile_phone": settings.get_ui_label_mobile_phone(),
"home_phone": T("Home Phone"),
}
# Tag labels (...and tags, in order as configured)
tags = []
for label, tag in settings.get_pr_request_tags():
if tag not in labels:
labels[tag] = label
tags.append(tag)
self.labels = labels
# Fields which, if enabled, are required
# (all other fields are assumed to not be required)
required = {"full_name": True,
"first_name": True,
"middle_name": settings.get_L10n_mandatory_middlename(),
"last_name": settings.get_L10n_mandatory_lastname(),
"date_of_birth": settings.get_pr_dob_required(),
"gender": settings.get_pr_gender_required(),
"email": settings.get_hrm_email_required() if hrm else False,
}
# Determine controller for autocomplete
controller = self.controller
if not controller:
controller = current.request.controller
if controller not in ("pr", "dvr", "hrm", "vol"):
controller = "hrm" if hrm else "pr"
# Fields to extract and fields in form
ptable = s3db.pr_person
dtable = s3db.pr_person_details
fields = {}
details = False
trigger = None
formfields = []
fappend = formfields.append
values = {}
if hrm:
# Organisation ID
htable = s3db.hrm_human_resource
f = htable.organisation_id
if f.default:
values["organisation_id"] = s3_str(f.default)
fields["organisation_id"] = f
fappend("organisation_id")
required["organisation_id"] = settings.get_hrm_org_required()
self.required = required
# ID Label
pe_label = self.pe_label
if pe_label:
fields["pe_label"] = ptable.pe_label
fappend("pe_label")
# Name fields (always extract all)
fields["first_name"] = ptable.first_name
fields["last_name"] = ptable.last_name
fields["middle_name"] = ptable.middle_name
separate_name_fields = self.separate_name_fields
if separate_name_fields is None:
separate_name_fields = settings.get_pr_separate_name_fields()
if separate_name_fields:
# Detect order of name fields
name_format = settings.get_pr_name_format()
keys = StringTemplateParser.keys(name_format)
if keys and keys[0] == "last_name":
# Last name first
trigger = "last_name"
fappend("last_name")
fappend("first_name")
else:
# First name first
trigger = "first_name"
fappend("first_name")
fappend("last_name")
if separate_name_fields == 3:
if keys and keys[-1] == "middle_name":
fappend("middle_name")
else:
formfields.insert(-1, "middle_name")
else:
# Single combined name field
fields["full_name"] = True
fappend("full_name")
# Additional name fields
father_name = self.father_name
if father_name is None:
# Not specified => apply deployment setting
father_name = settings.get_pr_request_father_name()
if father_name:
f = dtable.father_name
i18n["father_name_label"] = f.label
fields["father_name"] = f
details = True
fappend("father_name")
grandfather_name = self.grandfather_name
if grandfather_name is None:
# Not specified => apply deployment setting
grandfather_name = settings.get_pr_request_grandfather_name()
if grandfather_name:
f = dtable.grandfather_name
i18n["grandfather_name_label"] = f.label
fields["grandfather_name"] = f
details = True
fappend("grandfather_name")
# Date of Birth / Year of birth
year_of_birth = self.year_of_birth
if year_of_birth is None:
# Use Global deployment_setting
year_of_birth = settings.get_pr_request_year_of_birth()
if year_of_birth:
fields["year_of_birth"] = dtable.year_of_birth
details = True
fappend("year_of_birth")
elif settings.get_pr_request_dob():
fields["date_of_birth"] = ptable.date_of_birth
fappend("date_of_birth")
# Gender
if settings.get_pr_request_gender():
f = ptable.gender
if f.default:
values["gender"] = s3_str(f.default)
fields["gender"] = f
fappend("gender")
# Occupation
if controller == "vol":
fields["occupation"] = dtable.occupation
details = True
fappend("occupation")
# Contact Details
if settings.get_pr_request_email():
fields["email"] = True
fappend("email")
if settings.get_pr_request_mobile_phone():
fields["mobile_phone"] = True
fappend("mobile_phone")
if settings.get_pr_request_home_phone():
fields["home_phone"] = True
fappend("home_phone")
# Tags
for tag in tags:
if tag not in fields:
fields[tag] = True
fappend(tag)
elif current.response.s3.debug:
# This error would be very hard to diagnose because it only
# messes up the data without ever hitting an exception, so
# we raise one right here before it can do any harm:
raise RuntimeError("AddPersonWidget person field <-> tag name collision")
self.fields = fields
editable_fields = settings.get_pr_editable_fields()
editable_fields = [fname for fname in editable_fields if fname in fields]
self.editable_fields = editable_fields
# Extract existing values
if value:
record_id = None
if isinstance(value, str) and not value.isdigit():
data, error = self.parse(value)
if not error:
if all(k in data for k in formfields):
values = data
else:
record_id = data.get("id")
else:
record_id = value
if record_id:
values = self.extract(record_id, fields, details=details, tags=tags, hrm=hrm)
# Generate the embedded rows
widget_id = str(field).replace(".", "_")
formrows = self.embedded_form(field.label, widget_id, formfields, values)
# Widget Options (pass only non-default options)
widget_options = {}
# Duplicate checking?
lookup_duplicates = settings.get_pr_lookup_duplicates()
if lookup_duplicates:
# Add translations for duplicates-review
i18n.update({"Yes": T("Yes"),
"No": T("No"),
"dupes_found": T("_NUM_ duplicates found"),
})
widget_options["lookupDuplicates"] = True
if settings.get_ui_icons() != "font-awesome":
# Non-default icon theme => pass icon classes
widget_options["downIcon"] = ICON("down").attributes.get("_class")
widget_options["yesIcon"] = ICON("deployed").attributes.get("_class")
widget_options["noIcon"] = ICON("remove").attributes.get("_class")
# Use separate name fields?
if separate_name_fields:
widget_options["separateNameFields"] = True
if trigger:
widget_options["trigger"] = trigger
# Editable Fields
if editable_fields:
widget_options["editableFields"] = editable_fields
# Tags
if tags:
widget_options["tags"] = tags
# Non default AC controller/function?
if controller != "pr":
widget_options["c"] = controller
if fn != "person":
widget_options["f"] = fn
# Non-default AC trigger parameters?
delay = settings.get_ui_autocomplete_delay()
if delay != 800:
widget_options["delay"] = delay
chars = settings.get_ui_autocomplete_min_chars()
if chars != 2:
widget_options["chars"] = chars
# Inject the scripts
self.inject_script(widget_id, widget_options, i18n)
# Create and return the main input
attr["_class"] = "hide"
# Prepend internal validation
requires = field.requires
if requires:
requires = (self.validate, requires)
else:
requires = self.validate
attr["requires"] = requires
return TAG[""](DIV(INPUT(**attr), _class = "hide"), formrows)
# -------------------------------------------------------------------------
def extract(self, record_id, fields, details=False, tags=None, hrm=False):
"""
Extract the data for a record ID
Args:
record_id: the record ID
fields: the fields to extract, dict {propName: Field}
details: includes person details
tags: list of Tags
hrm: record ID is a hrm_human_resource ID rather
than person ID
Returns:
dict of {propName: value}
"""
db = current.db
s3db = current.s3db
ptable = s3db.pr_person
dtable = s3db.pr_person_details
qfields = [f for f in fields.values() if type(f) is not bool]
qfields.append(ptable.pe_id)
if hrm:
if tags:
qfields.append(ptable.id)
htable = s3db.hrm_human_resource
query = (htable.id == record_id)
join = ptable.on(ptable.id == htable.person_id)
else:
query = (ptable.id == record_id)
join = None
if details:
left = dtable.on(dtable.person_id == ptable.id)
else:
left = None
row = db(query).select(join = join,
left = left,
limitby = (0, 1),
*qfields).first()
if not row:
# Raise?
return {}
person = row.pr_person if join or left else row
values = {k: person[k] for k in person}
if fields.get("full_name"):
values["full_name"] = s3_fullname(person)
if details:
details = row.pr_person_details
for k in details:
values[k] = details[k]
if hrm:
human_resource = row.hrm_human_resource
for k in human_resource:
values[k] = human_resource[k]
person_id = person.id
else:
person_id = record_id
# Add tags
if tags:
for k, v in self.get_tag_data(person_id, tags).items():
if k not in values:
values[k] = v
values.update(self.get_contact_data(person.pe_id))
return values
# -------------------------------------------------------------------------
def get_contact_data(self, pe_id):
"""
Extract the contact data for a pe_id; extracts only the first
value per contact method
Args:
pe_id: the pe_id
Returns:
dict {fieldname: value}, where field names
correspond to the contact method (field map)
"""
# Map contact method <=> form field name
names = {"EMAIL": "email",
"HOME_PHONE": "home_phone",
"SMS": "mobile_phone",
}
# Determine relevant contact methods
fields = self.fields
methods = set(m for m in names if fields.get(names[m]))
# Initialize values with relevant fields
values = dict.fromkeys((names[m] for m in methods), "")
if methods:
# Retrieve the contact data
ctable = current.s3db.pr_contact
query = (ctable.pe_id == pe_id) & \
(ctable.deleted == False) & \
(ctable.contact_method.belongs(methods))
rows = current.db(query).select(ctable.contact_method,
ctable.value,
orderby = ctable.priority,
)
# Extract the values
for row in rows:
method = row.contact_method
if method in methods:
values[names[method]] = row.value
methods.discard(method)
if not methods:
break
return values
# -------------------------------------------------------------------------
@staticmethod
def get_tag_data(person_id, tags):
"""
Extract the tag data for a person_id
Args:
person_id: the person_id
tags: list of tags
Returns:
dict {fieldname: value}, where field names
correspond to the tag name (field map)
"""
ttable = current.s3db.pr_person_tag
query = (ttable.person_id == person_id) & \
(ttable.tag.belongs(tags)) & \
(ttable.deleted == False)
rows = current.db(query).select(ttable.tag,
ttable.value,
)
return {row.tag: row.value for row in rows}
# -------------------------------------------------------------------------
def embedded_form(self, label, widget_id, formfields, values):
"""
Construct the embedded form
Args:
label: the label for the embedded form
(= field label for the person_id)
widget_id: the widget ID
(=element ID of the person_id field)
formfields: list of field names indicating which
fields to render and in which order
values: dict with values to populate the embedded form
Returns:
DIV containing the embedded form rows
"""
T = current.T
s3 = current.response.s3
settings = current.deployment_settings
# Test the formstyle
formstyle = s3.crud.formstyle
tuple_rows = isinstance(formstyle("", "", "", ""), tuple)
rows = DIV()
# Section Title + Actions
title_id = "%s_title" % widget_id
label = LABEL(label, _for=title_id)
if len(self.editable_fields):
edit_btn = A(ICON("edit"),
_class = "edit-action",
_title = T("Edit Entry"),
)
else:
edit_btn = ""
widget = DIV(edit_btn,
A(ICON("eraser"),
_class = "clear-action",
_title = T("Clear Entry"),
),
A(ICON("undo"),
_class = "undo-action",
_title = T("Revert Entry"),
),
_class = "add_person_edit_bar hide",
_id = "%s_edit_bar" % widget_id,
)
if tuple_rows:
row = TR(TD(DIV(label, widget, _class="box_top_inner"),
_class = "box_top_td",
_colspan = 2,
),
_id = "%s__row" % title_id,
)
else:
row = formstyle("%s__row" % title_id, label, widget, "")
row.add_class("box_top hide")
rows.append(row)
# Input rows
fields_get = self.fields.get
get_label = self.get_label
get_widget = self.get_widget
for fname in formfields:
field = fields_get(fname)
if not field:
continue # Field is disabled
field_id = "%s_%s" % (widget_id, fname)
label = get_label(fname)
required = self.required.get(fname, False)
if required:
label = DIV("%s:" % label, SPAN(" *", _class="req"))
else:
label = "%s:" % label
label = LABEL(label, _for=field_id)
widget = get_widget(fname, field)
value = values.get(fname, "")
if widget:
widget = widget(field,