~sahana-eden-jp/sahana-eden/reload_s3

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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
# -*- coding: utf-8 -*-

""" Person Registry

    @author: nursix
    @see: U{http://eden.sahanafoundation.org/wiki/BluePrintVITA}

"""

prefix = "pr"

# *****************************************************************************
# Person
#

# -----------------------------------------------------------------------------
pr_gender_opts = {
    1:T("unknown"),
    2:T("female"),
    3:T("male")
}

pr_gender = S3ReusableField("gender", "integer",
                            requires = IS_IN_SET(pr_gender_opts, zero=None),
                            default = 1,
                            label = T("Gender"),
                            represent = lambda opt: \
                                        pr_gender_opts.get(opt, UNKNOWN_OPT))


# -----------------------------------------------------------------------------
pr_age_group_opts = {
    1:T("unknown"),
    2:T("Infant (0-1)"),
    3:T("Child (2-11)"),
    4:T("Adolescent (12-20)"),
    5:T("Adult (21-50)"),
    6:T("Senior (50+)")
}

pr_age_group = S3ReusableField("age_group", "integer",
                               requires = IS_IN_SET(pr_age_group_opts,
                                                    zero=None),
                               default = 1,
                               label = T("Age Group"),
                               represent = lambda opt: \
                                           pr_age_group_opts.get(opt,
                                                                 UNKNOWN_OPT))


# -----------------------------------------------------------------------------
pr_marital_status_opts = {
    1:T("unknown"),
    2:T("single"),
    3:T("married"),
    4:T("separated"),
    5:T("divorced"),
    6:T("widowed"),
    99:T("other")
}

pr_marital_status = S3ReusableField("marital_status", "integer",
                                    requires = IS_NULL_OR(IS_IN_SET(
                                                    pr_marital_status_opts)),
                                    default = 1,
                                    label = T("Marital Status"),
                                    represent = lambda opt: opt and \
                                                pr_marital_status_opts.get(opt,
                                                    UNKNOWN_OPT))


# -----------------------------------------------------------------------------
pr_religion_opts = deployment_settings.get_L10n_religions()

pr_religion = S3ReusableField("religion",
                              requires = IS_EMPTY_OR(IS_IN_SET(pr_religion_opts)),
                              label = T("Religion"),
                              represent = lambda opt: opt and \
                                          pr_religion_opts.get(opt, UNKNOWN_OPT))


# -----------------------------------------------------------------------------
# Tags for the impact of the disaster on a person (formerly "victim status")
# NOTE: "Missing" is defined elsewhere, because this doesn't impact the person
#
pr_impact_tags = {
    1: T("injured"),
    4: T("diseased"),
    2: T("displaced"),
    5: T("separated from family"),
    3: T("suffered financial losses")
}

# -----------------------------------------------------------------------------
pr_nations = s3_list_of_nations

pr_country = S3ReusableField("country", "string", length=2,
                             requires = IS_NULL_OR(IS_IN_SET(pr_nations, sort=True)),
                             label = T("Country of Residence"),
                             represent = lambda opt: \
                                         pr_nations.get(opt, UNKNOWN_OPT))


# -----------------------------------------------------------------------------
def shn_pr_person_represent(id):

    def _represent(id):
        table = db.pr_person
        person = db(table.id == id).select(
                    table.first_name,
                    table.middle_name,
                    table.last_name,
                    limitby=(0, 1))
        if person:
            return vita.fullname(person.first())
        else:
            return None

    name = cache.ram("pr_person_%s" % id, lambda: _represent(id),
                     time_expire=10)
    return name


# -----------------------------------------------------------------------------
resourcename = "person"
tablename = "%s_%s" % (prefix, resourcename)
table = db.define_table(tablename,
                        super_link(db.pr_pentity), # pe_id
                        super_link(db.sit_trackable), # track_id
                        pe_label(),
                        Field("missing", "boolean", default=False),
                        Field("first_name", notnull=True),
                        Field("middle_name"),
                        Field("last_name"),
                        Field("preferred_name"),
                        Field("local_name"),
                        pr_gender(),
                        pr_age_group(),
                        Field("date_of_birth", "date", widget=S3DateWidget(before=110, after=0)),
                        pr_country("nationality", label = T("Nationality")),
                        pr_country("country"),
                        pr_religion(),
                        pr_marital_status(),
                        Field("occupation"),
                        Field("tags", "list:integer"),
                        comments(),
                        migrate=migrate, *s3_meta_fields())

table.first_name.label = T("First Name")
table.middle_name.label = T("Middle Name")
table.last_name.label = T("Last Name")
table.local_name.label = T("Local Name")

table.date_of_birth.label = T("Date of Birth")
table.date_of_birth.requires = IS_NULL_OR(IS_DATE_IN_RANGE(
                               maximum=request.utcnow.date(),
                               error_message="%s %%(max)s!" %
                                             T("Enter a date before")))

table.first_name.requires = IS_NOT_EMPTY(error_message = T("Please enter a First Name"))
# NB Not possible to have an IS_NAME() validator here
# http://eden.sahanafoundation.org/ticket/834

table.pe_label.comment = DIV(DIV(_class="tooltip",
    _title="%s|%s" % (T("ID Tag Number"),
                      T("Number or Label on the identification tag this person is wearing (if any)."))))
table.first_name.comment =  DIV(_class="tooltip",
    _title="%s|%s" % (T("First name"),
                      T("The first or only name of the person (mandatory).")))
table.preferred_name.comment = DIV(DIV(_class="tooltip",
    _title="%s|%s" % (T("Preferred Name"),
                      T("The name to be used when calling for or directly addressing the person (optional)."))))
table.local_name.comment = DIV(DIV(_class="tooltip",
    _title="%s|%s" % (T("Local Name"),
                      T("Name of the person in local language and script (optional)."))))
table.nationality.comment = DIV(DIV(_class="tooltip",
    _title="%s|%s" % (T("Nationality"),
                      T("Nationality of the person."))))
table.country.comment = DIV(DIV(_class="tooltip",
    _title="%s|%s" % (T("Country of Residence"),
                      T("The country the person usually lives in."))))

table.missing.represent = lambda missing: (missing and ["missing"] or [""])[0]

table.gender.label = T("Gender")
table.age_group.label = T("Age group")

table.tags.label = T("Personal impact of disaster")
table.tags.comment = DIV(DIV(_class="tooltip",
    _title=T("Personal impact of disaster") + "|" + T("How is this person affected by the disaster? (Select all that apply)")))
table.tags.requires = IS_EMPTY_OR(IS_IN_SET(pr_impact_tags, zero=None, multiple=True))
table.tags.represent = lambda opt: opt and \
                       ", ".join([str(pr_impact_tags.get(o, UNKNOWN_OPT)) for o in opt]) or ""

# -----------------------------------------------------------------------------
ADD_PERSON = T("Add Person")
LIST_PERSONS = T("List Persons")
s3.crud_strings[tablename] = Storage(
    title_create = T("Add a Person"),
    title_display = T("Person Details"),
    title_list = LIST_PERSONS,
    title_update = T("Edit Person Details"),
    title_search = T("Search Persons"),
    subtitle_create = ADD_PERSON,
    subtitle_list = T("Persons"),
    label_list_button = LIST_PERSONS,
    label_create_button = ADD_PERSON,
    label_delete_button = T("Delete Person"),
    msg_record_created = T("Person added"),
    msg_record_modified = T("Person details updated"),
    msg_record_deleted = T("Person deleted"),
    msg_list_empty = T("No Persons currently registered"))


# -----------------------------------------------------------------------------
shn_person_comment = lambda title, comment: \
    DIV(A(ADD_PERSON,
        _class="colorbox",
        _href=URL(r=request, c="pr", f="person", args="create", vars=dict(format="popup")),
        _target="top",
        _title=ADD_PERSON),
    DIV(DIV(_class="tooltip",
        _title="%s|%s" % (title, comment))))

shn_person_id_comment = shn_person_comment(
    T("Person"),
    T("Select the person associated with this scenario."))

person_id = S3ReusableField("person_id", db.pr_person,
                            sortby = ["first_name", "middle_name", "last_name"],
                            requires = IS_NULL_OR(IS_ONE_OF(db, "pr_person.id",
                                                            shn_pr_person_represent,
                                                            orderby="pr_person.first_name",
                                                            sort=True,
                                                            error_message="Person must be specified!")),
                            represent = lambda id: (id and \
                                        [shn_pr_person_represent(id)] or [NONE])[0],
                            label = T("Person"),
                            comment = shn_person_id_comment,
                            ondelete = "RESTRICT",
                            widget = S3PersonAutocompleteWidget(request)
                            )

# -----------------------------------------------------------------------------
def pr_person_onvalidation(form):

    try:
        age = int(form.vars.get("age_group", None))
    except (ValueError, TypeError):
        age = None
    dob = form.vars.get("date_of_birth", None)

    if age and age != 1 and dob:
        now = request.utcnow
        dy = int((now.date() - dob).days / 365.25)
        if dy < 0:
            ag = 1
        elif dy < 2:
            ag = 2
        elif dy < 12:
            ag = 3
        elif dy < 21:
            ag = 4
        elif dy < 51:
            ag = 5
        else:
            ag = 6

        if age != ag:
            form.errors.age_group = T("Age group does not match actual age.")
            return False

    return True

# -----------------------------------------------------------------------------
s3xrc.model.configure(table,
                      main="first_name",
                      extra="last_name",
                      super_entity=(db.pr_pentity, db.sit_trackable),
                      onvalidation=lambda form: pr_person_onvalidation(form),
                      list_fields = [
                        "id",
                        "first_name",
                        "middle_name",
                        "last_name",
                        "gender",
                        "age_group"
                      ])


# *****************************************************************************
# Group (group)
#

# -----------------------------------------------------------------------------
pr_group_type_opts = {
    1:T("Family"),
    2:T("Tourist Group"),
    3:T("Relief Team"),     # Don't change this number without changing vol/group()
    4:T("other")
}

pr_group_type = S3ReusableField("group_type", "integer",
                                requires = IS_IN_SET(pr_group_type_opts, zero=None),
                                default = 4,
                                label = T("Group Type"),
                                represent = lambda opt: \
                                            pr_group_type_opts.get(opt, UNKNOWN_OPT))

# -----------------------------------------------------------------------------
resourcename = "group"
tablename = "%s_%s" % (prefix, resourcename)
table = db.define_table(tablename,
                        super_link(db.pr_pentity), # pe_id
                        pr_group_type(),
                        Field("system", "boolean", default=False),
                        Field("name"),
                        Field("description"),
                        comments(),
                        migrate=migrate, *s3_meta_fields())

table.system.readable = False
table.system.writable = False
table.group_type.label = T("Group type")
table.name.label = T("Group name")
table.name.requires = IS_NOT_EMPTY()

table.description.label = T("Group description")
table.description.comment = DIV(DIV(_class="tooltip",
    _title="%s|%s" % (T("Group description"),
                      T("A brief description of the group (optional)"))))

# -----------------------------------------------------------------------------
ADD_GROUP = T("Add Group")
LIST_GROUPS = T("List Groups")
s3.crud_strings[tablename] = Storage(
    title_create = ADD_GROUP,
    title_display = T("Group Details"),
    title_list = LIST_GROUPS,
    title_update = T("Edit Group"),
    title_search = T("Search Groups"),
    subtitle_create = T("Add New Group"),
    subtitle_list = T("Groups"),
    label_list_button = LIST_GROUPS,
    label_create_button = ADD_GROUP,
    label_delete_button = T("Delete Group"),
    msg_record_created = T("Group added"),
    msg_record_modified = T("Group updated"),
    msg_record_deleted = T("Group deleted"),
    msg_list_empty = T("No Groups currently registered"))


# -----------------------------------------------------------------------------
group_id = S3ReusableField("group_id", db.pr_group,
                           sortby="name",
                           requires = IS_NULL_OR(IS_ONE_OF(db, "pr_group.id",
                                                           "%(id)s: %(name)s",
                                                           filterby="system",
                                                           filter_opts=(False,))),
                           represent = lambda id: (id and \
                                       [db(db.pr_group.id == id).select(db.pr_group.name, limitby=(0, 1)).first().name] or [NONE])[0],
                           comment = \
                                DIV(A(s3.crud_strings.pr_group.label_create_button,
                                    _class="colorbox",
                                    _href=URL(r=request, c="pr", f="group", args="create", vars=dict(format="popup")),
                                    _target="top",
                                    _title=s3.crud_strings.pr_group.label_create_button),
                                DIV(DIV(_class="tooltip",
                                    _title="%s|%s" % (T("Create Group Entry"),
                                                      T("Create a group entry in the registry."))))),
                           ondelete = "RESTRICT")

# -----------------------------------------------------------------------------
s3xrc.model.configure(table,
                      #deletable=False,
                      super_entity=db.pr_pentity,
                      main="name",
                      extra="description")

# -----------------------------------------------------------------------------
# Search method
#pr_person_search = s3base.S3PersonSearch(
    #label=T("Name and/or ID"),
    #comment=T("To search for a person, enter any of the first, middle or last names and/or an ID number of a person, separated by spaces. You may use % as wildcard. Press 'Search' without input to list all persons."),
    #fields=["pe_label",
            #"first_name",
            #"middle_name",
            #"last_name",
            #"identity.value"])

pr_person_search = s3base.S3PersonSearch(
            name="person_search_simple",
            label=T("Name and/or ID"),
            comment=T("To search for a person, enter any of the first, middle or last names and/or an ID number of a person, separated by spaces. You may use % as wildcard. Press 'Search' without input to list all persons."),
            field=["pe_label",
                   "first_name",
                   "middle_name",
                   "last_name",
                   "identity.value"])

# Set as default search method
s3xrc.model.configure(db.pr_person, search_method=pr_person_search)

# *****************************************************************************
# Group membership
#
resourcename = "group_membership"
tablename = "%s_%s" % (prefix, resourcename)
table = db.define_table(tablename,
                        group_id(),
                        person_id(),
                        Field("group_head", "boolean", default=False),
                        Field("description"),
                        comments(),
                        migrate=migrate, *s3_meta_fields())


table.group_head.represent = lambda group_head: (group_head and [T("yes")] or [""])[0]

table.group_id.label = T("Group")
table.person_id.label = T("Person")


# -----------------------------------------------------------------------------
s3xrc.model.add_component(prefix, resourcename,
                          multiple=True,
                          joinby=dict(pr_group="group_id",
                                      pr_person="person_id"))

s3xrc.model.configure(table,
    list_fields=[
        "id",
        "group_id",
        "person_id",
        "group_head",
        "description"
    ])


# -----------------------------------------------------------------------------
if request.function in ("person", "group_membership"):
    s3.crud_strings[tablename] = Storage(
        title_create = T("Add Membership"),
        title_display = T("Membership Details"),
        title_list = T("Memberships"),
        title_update = T("Edit Membership"),
        title_search = T("Search Membership"),
        subtitle_create = T("Add New Membership"),
        subtitle_list = T("Current Memberships"),
        label_list_button = T("List All Memberships"),
        label_create_button = T("Add Membership"),
        label_delete_button = T("Delete Membership"),
        msg_record_created = T("Membership added"),
        msg_record_modified = T("Membership updated"),
        msg_record_deleted = T("Membership deleted"),
        msg_list_empty = T("No Memberships currently registered"))

elif request.function == "group":
    s3.crud_strings[tablename] = Storage(
        title_create = T("Add Member"),
        title_display = T("Membership Details"),
        title_list = T("Group Members"),
        title_update = T("Edit Membership"),
        title_search = T("Search Member"),
        subtitle_create = T("Add New Member"),
        subtitle_list = T("Current Group Members"),
        label_list_button = T("List Members"),
        label_create_button = T("Add Group Member"),
        label_delete_button = T("Delete Membership"),
        msg_record_created = T("Group Member added"),
        msg_record_modified = T("Membership updated"),
        msg_record_deleted = T("Membership deleted"),
        msg_list_empty = T("No Members currently registered"))


# -----------------------------------------------------------------------------
#
def shn_pr_rheader(jr, tabs=[]):

    """ Person Registry page headers """

    if jr.representation == "html":

        rheader_tabs = shn_rheader_tabs(jr, tabs)

        if jr.name == "person":

            _next = jr.here()
            _same = jr.same()

            person = jr.record

            if person:
                rheader = DIV(TABLE(

                    TR(TH("%s: " % T("Name")),
                       vita.fullname(person),
                       TH("%s: " % T("ID Tag Number")),
                       "%(pe_label)s" % person),

                    TR(TH("%s: " % T("Date of Birth")),
                       "%s" % (person.date_of_birth or T("unknown")),
                       TH("%s: " % T("Gender")),
                       "%s" % pr_gender_opts.get(person.gender, T("unknown"))),

                    TR(TH("%s: " % T("Nationality")),
                       "%s" % pr_nations.get(person.nationality, T("unknown")),
                       TH("%s: " % T("Age Group")),
                       "%s" % pr_age_group_opts.get(person.age_group, T("unknown"))),

                    #))
                    ), rheader_tabs)

                return rheader

        elif jr.name == "group":

            _next = jr.here()
            _same = jr.same()

            group = jr.record

            if group:
                rheader = DIV(TABLE(

                    TR(TH("%s: " % T("Name")),
                       group.name,
                       TH(""),
                       ""),
                    TR(TH("%s: " % T("Description")),
                       group.description,
                       TH(""),
                       "")

                    ), rheader_tabs)

                return rheader

    return None

# *****************************************************************************
# Address (address)
#
pr_address_type_opts = {
    1:T("Home Address"),
    2:T("Office Address"),
    3:T("Holiday Address"),
    99:T("other")
}


# -----------------------------------------------------------------------------
resourcename = "address"
tablename = "%s_%s" % (prefix, resourcename)
table = db.define_table(tablename,
                        super_link(db.pr_pentity), # pe_id
                        Field("type",
                              "integer",
                              requires = IS_IN_SET(pr_address_type_opts, zero=None),
                              default = 99,
                              label = T("Address Type"),
                              represent = lambda opt: \
                                          pr_address_type_opts.get(opt, UNKNOWN_OPT)),
                        Field("co_name", label=T("c/o Name")),
                        location_id(),
                        Field("address", "text", label=T("Address"), writable=False), # Populated from location_id
                        Field("L4", label=deployment_settings.get_gis_locations_hierarchy("L4"), writable=False), # Populated from location_id
                        Field("L3", label=deployment_settings.get_gis_locations_hierarchy("L3"), writable=False), # Populated from location_id
                        Field("L2", label=deployment_settings.get_gis_locations_hierarchy("L2"), writable=False), # Populated from location_id
                        Field("L1", label=deployment_settings.get_gis_locations_hierarchy("L1"), writable=False), # Populated from location_id
                        Field("L0", label=deployment_settings.get_gis_locations_hierarchy("L0"), writable=False), # Populated from location_id
                        Field("postcode", label=T("Postcode"), writable=False), # Populated from location_id
                        comments(),
                        migrate=migrate, *s3_meta_fields())



table.uuid.requires = IS_NOT_ONE_OF(db, "%s.uuid" % tablename)

table.pe_id.requires = IS_ONE_OF(db, "pr_pentity.pe_id", shn_pentity_represent,
                                 orderby="instance_type",
                                 filterby="instance_type",
                                 filter_opts=("pr_person", "pr_group"))

ADD_ADDRESS = T("Add Address")
LIST_ADDRESS = T("List of addresses")
s3.crud_strings[tablename] = Storage(
    title_create = ADD_ADDRESS,
    title_display = T("Address Details"),
    title_list = LIST_ADDRESS,
    title_update = T("Edit Address"),
    title_search = T("Search Addresses"),
    subtitle_create = T("Add New Address"),
    subtitle_list = T("Addresses"),
    label_list_button = LIST_ADDRESS,
    label_create_button = ADD_ADDRESS,
    msg_record_created = T("Address added"),
    msg_record_modified = T("Address updated"),
    msg_record_deleted = T("Address deleted"),
    msg_list_empty = T("No Addresses currently registered"))

def address_onvalidation(form):
    """
        Write the Postcode & Street Address fields from the Location
        - also used by org_office

        @ToDo: Allow the reverse operation.
        If these fields are populated then create an appropriate location
    """

    if "location_id" in form.vars:
        locations = db.gis_location
        # Read Postcode & Street Address
        location = db(locations.id == form.vars.location_id).select(locations.addr_street,
                                                                    locations.addr_postcode,
                                                                    locations.name,
                                                                    locations.level,
                                                                    locations.parent,
                                                                    locations.path,
                                                                    limitby=(0, 1)).first()
        if location:
            form.vars.address = location.addr_street
            form.vars.postcode = location.addr_postcode
            if location.level == "L0":
                form.vars.L0 = location.name
            elif location.level == "L1":
                form.vars.L1 = location.name
                if location.parent:
                    country = db(locations.id == location.parent).select(locations.name, limitby=(0, 1)).first()
                    if country:
                        form.vars.L0 = country.name
            else:
                # Get ids of ancestors at each level.
                gis.get_parent_per_level(form.vars,
                                         form.vars.location_id,
                                         feature=location,
                                         names=True)

# Addresses as component of person entities
s3xrc.model.add_component(prefix, resourcename,
                          multiple=True,
                          joinby=super_key(db.pr_pentity))

s3xrc.model.configure(table,
                      onvalidation=lambda form: address_onvalidation(form),
                      list_fields = [
                        "id",
                        "type",
                        "address",
                        "postcode",
                        #"co_name",
                        #"L4",
                        "L3",
                        "L2",
                        "L1",
                        "L0"
                    ])

# *****************************************************************************
# Contact (pe_contact)
#
pr_contact_method_opts = {
    1:T("Email"),
    2:T("Mobile Phone"),
    3:"XMPP",
    4:T("Twitter"),
    5:T("Telephone"),
    6:T("Fax"),
    7:T("Facebook"),
    99:T("other")
}


# -----------------------------------------------------------------------------
resourcename = "pe_contact"
tablename = "%s_%s" % (prefix, resourcename)
table = db.define_table(tablename,
                        super_link(db.pr_pentity), # pe_id
                        Field("contact_method",
                              "integer",
                              requires = IS_IN_SET(pr_contact_method_opts, zero=None),
                              default = 99,
                              label = T("Contact Method"),
                              represent = lambda opt: \
                                          pr_contact_method_opts.get(opt, UNKNOWN_OPT)),
                        Field("value", notnull=True),
                        Field("priority"),
                        Field("contact_person"),
                        comments(),
                        #Field("name"),
                        migrate=migrate, *s3_meta_fields())


table.uuid.requires = IS_NOT_ONE_OF(db, "%s.uuid" % tablename)
table.pe_id.requires = IS_ONE_OF(db, "pr_pentity.pe_id",
                                 shn_pentity_represent,
                                 orderby="instance_type",
                                 filterby="instance_type",
                                 filter_opts=("pr_person", "pr_group"))

table.value.requires = IS_NOT_EMPTY()
table.priority.requires = IS_IN_SET(range(1, 10), zero=None)


pe_contact_id = S3ReusableField("pe_contact_id", db.pr_pe_contact,
                                requires = IS_NULL_OR(IS_ONE_OF(db, "pr_pe_contact.id")),
                                ondelete = "RESTRICT")


# Contact information as component of person entities
s3xrc.model.add_component(prefix, resourcename,
                          multiple=True,
                          joinby=super_key(db.pr_pentity))

def shn_pe_contact_onvalidation(form):

    """ Contact form validation """

    table = db.pr_pe_contact

    if form.vars.contact_method == '1':
        email, error = IS_EMAIL()(form.vars.value)
        if error:
            form.errors.value = T("Enter a valid email")

    return False

s3xrc.model.configure(table,
                      onvalidation=shn_pe_contact_onvalidation,
                      list_fields=[
                        #"id",
                        #"pe_id",
                        "contact_method",
                        "value",
                        "priority",
                        #"contact_person",
                        #"name",
                      ])

s3.crud_strings[tablename] = Storage(
    title_create = T("Add Contact Information"),
    title_display = T("Contact Details"),
    title_list = T("Contact Information"),
    title_update = T("Edit Contact Information"),
    title_search = T("Search Contact Information"),
    subtitle_create = T("Add Contact Information"),
    subtitle_list = T("Contact Information"),
    label_list_button = T("List Records"),
    label_create_button = T("Add Record"),
    label_delete_button = T("Delete Record"),
    msg_record_created = T("Contact information added"),
    msg_record_modified = T("Contact information updated"),
    msg_record_deleted = T("Contact information deleted"),
    msg_list_empty = T("No contact information available"))


# *****************************************************************************
# Image (image)
#
pr_image_type_opts = {
    1:T("Photograph"),
    2:T("Sketch"),
    3:T("Fingerprint"),
    4:T("X-Ray"),
    5:T("Document Scan"),
    99:T("other")
}


# -----------------------------------------------------------------------------
resourcename = "image"
tablename = "%s_%s" % (prefix, resourcename)
table = db.define_table(tablename,
                        super_link(db.pr_pentity), # pe_id
                        Field("type", "integer",
                              requires = IS_IN_SET(pr_image_type_opts, zero=None),
                              default = 1,
                              label = T("Image Type"),
                              represent = lambda opt: pr_image_type_opts.get(opt, UNKNOWN_OPT)),
                        Field("title"),
                        Field("image", "upload", autodelete=True),
                        Field("url"),
                        Field("description"),
                        comments(),
                        migrate=migrate, *s3_meta_fields())


table.uuid.requires = IS_NOT_ONE_OF(db, "%s.uuid" % tablename)

table.title.requires = IS_NOT_EMPTY()
table.title.comment = DIV(_class="tooltip",
    _title=T("Title") + "|" + T("Specify a descriptive title for the image."))

table.url.label = T("URL")
table.url.represent = lambda url: url and DIV(A(IMG(_src=url, _height=60), _href=url)) or T("None")
table.url.comment =  DIV(_class="tooltip",
    _title=T("URL") + "|" + T("The URL of the image file. If you don't upload an image file, then you must specify its location here."))
table.image.comment =  DIV(_class="tooltip",
    _title=T("Image") + "|" + T("Upload an image file here. If you don't upload an image file, then you must specify its location in the URL field."))
table.image.represent = lambda image: image and \
        DIV(A(IMG(_src=URL(r=request, c="default", f="download", args=image),_height=60, _alt=T("View Image")),
              _href=URL(r=request, c="default", f="download", args=image))) or \
        T("No Image")
table.description.comment =  DIV(_class="tooltip",
    _title=T("Description") + "|" + T("Give a brief description of the image, e.g. what can be seen where on the picture (optional)."))


# -----------------------------------------------------------------------------
def shn_pr_image_onvalidation(form):

    """ Image form validation """

    table = db.pr_image
    image = form.vars.image

    if not hasattr(image, "file"):
        id = request.post_vars.id
        if id:
            record = db(table.id == id).select(table.image, limitby=(0, 1)).first()
            if record:
                image = record.image

    url = form.vars.url
    if not hasattr(image, "file") and not image and not url:
        form.errors.image = \
        form.errors.url = T("Either file upload or image URL required.")

    return False


# -----------------------------------------------------------------------------
# Images as component of person entities
s3xrc.model.add_component(prefix, resourcename,
                          multiple=True,
                          joinby=super_key(db.pr_pentity))

s3xrc.model.configure(table,
    onvalidation=shn_pr_image_onvalidation,
    mark_required = ["url", "image"],
    list_fields=[
        "id",
        "title",
        "type",
        "image",
        "url",
        "description"
    ])


LIST_IMAGES = T("List Images")
s3.crud_strings[tablename] = Storage(
    title_create = T("Image"),
    title_display = T("Image Details"),
    title_list = LIST_IMAGES,
    title_update = T("Edit Image Details"),
    title_search = T("Search Images"),
    subtitle_create = T("Add New Image"),
    subtitle_list = T("Images"),
    label_list_button = LIST_IMAGES,
    label_create_button = T("Add Image"),
    label_delete_button = T("Delete Image"),
    msg_record_created = T("Image added"),
    msg_record_modified = T("Image updated"),
    msg_record_deleted = T("Image deleted"),
    msg_list_empty = T("No Images currently registered"))


# *****************************************************************************
# Presence Log (presence)
#
pr_presence_condition_opts = vita.presence_conditions

# -----------------------------------------------------------------------------
resourcename = "presence"
tablename = "%s_%s" % (prefix, resourcename)
table = db.define_table(tablename,
                        super_link(db.pr_pentity), # pe_id
                        super_link(db.sit_situation), # sit_id
                        person_id("observer",
                                  label=T("Observer"),
                                  default = s3_logged_in_person(),
                                  comment=shn_person_comment(T("Observer"),
                                                             T("Person who has actually seen the person/group."))),
                        Field("shelter_id", "integer"),
                        location_id(widget = S3LocationAutocompleteWidget(request, deployment_settings),
                                    comment = DIV(A(ADD_LOCATION, _class="colorbox", _target="top", _title=ADD_LOCATION,
                                                  _href=URL(r=request, c="gis", f="location", args="create", vars=dict(format="popup"))),
                                              DIV(_class="tooltip",
                                                  _title=T("Current Location") + "|" + T("The Current Location of the Person/Group, which can be general (for Reporting) or precise (for displaying on a Map). Enter a few characters to search from available locations.")))),
                        Field("location_details",
                              comment = DIV(_class="tooltip",
                                            _title=T("Location Details") + "|" + T("Specific Area (e.g. Building/Room) within the Location that this Person/Group is seen."))
                             ),
                        Field("datetime", "datetime"),
                        Field("presence_condition", "integer",
                              requires = IS_IN_SET(pr_presence_condition_opts,
                                                   zero=None),
                              default = vita.DEFAULT_PRESENCE,
                              label = T("Presence Condition"),
                              represent = lambda opt: \
                                          pr_presence_condition_opts.get(opt, UNKNOWN_OPT)),
                        Field("proc_desc"),
                        location_id("orig_id", label=T("Origin"), widget = S3LocationAutocompleteWidget(request, deployment_settings),
                                    comment = DIV(A(ADD_LOCATION, _class="colorbox", _target="top", _title=ADD_LOCATION,
                                                  _href=URL(r=request, c="gis", f="location", args="create", vars=dict(format="popup"))),
                                              DIV(_class="tooltip",
                                                  _title=T("Origin") + "|" + T("The Location the Person has come from, which can be general (for Reporting) or precise (for displaying on a Map). Enter a few characters to search from available locations.")))),
                        location_id("dest_id", label=T("Destination"), widget = S3LocationAutocompleteWidget(request, deployment_settings),
                                    comment = DIV(A(ADD_LOCATION, _class="colorbox", _target="top", _title=ADD_LOCATION,
                                                  _href=URL(r=request, c="gis", f="location", args="create", vars=dict(format="popup"))),
                                              DIV(_class="tooltip",
                                                  _title=T("Destination") + "|" + T("The Location the Person is going to, which can be general (for Reporting) or precise (for displaying on a Map). Enter a few characters to search from available locations.")))),
                        Field("comment"),
                        Field("closed", "boolean", default=False),
                        migrate=migrate, *s3_meta_fields())



table.uuid.requires = IS_NOT_ONE_OF(db, "%s.uuid" % tablename)

table.datetime.requires = IS_UTC_DATETIME(utc_offset=shn_user_utc_offset(), allow_future=False)
table.datetime.represent = lambda value: shn_as_local_time(value)
table.datetime.label = T("Date/Time")
table.datetime.default = request.utcnow

table.closed.readable = False
table.closed.writable = False
#table.closed.represent = lambda opt: opt and "closed" or ""

table.proc_desc.label = T("Procedure")
table.proc_desc.comment = DIV(DIV(_class="tooltip",
        _title=T("Procedure") + "|" + T('Describe the procedure which this record relates to (e.g. "medical examination")')))

table.shelter_id.readable = False
table.shelter_id.writable = False


# -----------------------------------------------------------------------------
def s3_pr_presence_onvalidation(form):

    """ Presence record validation """

    table = db.pr_presence

    location = form.vars.location_id
    shelter = form.vars.shelter_id

    if shelter and "cr_shelter" in db:
        set = db(db.cr_shelter.id == shelter)
        row = set.select(db.cr_shelter.location_id, limitby=(0, 1)).first()
        if row:
            location = form.vars.location_id = row.location_id
        else:
            shelter = None

    if location or shelter:
        return

    condition = form.vars.presence_condition
    if condition:
        try:
            condition = int(condition)
        except ValueError:
            condition = None
    else:
        condition = table.presence_condition.default
        form.vars.condition = condition

    if condition:
        if condition in vita.PERSISTANT_PRESENCE or \
           condition in vita.ABSENCE:
            if not form.vars.id:
                if table.location_id.default or \
                   table.shelter_id.default:
                    return
            else:
                record = db(table.id == form.vars.id).select(table.location_id,
                                                             table.shelter_id,
                                                             limitby=(0, 1)).first()
                if record and \
                   record.location_id or record.shelter_id:
                    return
        else:
            return
    else:
        return

    form.errors.location_id = \
    form.errors.shelter_id = T("Either a shelter or a location must be specified")
    return


# -----------------------------------------------------------------------------
# Presence as component of person entities
s3xrc.model.add_component(prefix, resourcename,
                          multiple=True,
                          joinby=super_key(db.pr_pentity))

def s3_pr_presence_onaccept(form):
    vita.presence_accept(form)

def s3_pr_presence_ondelete(row):
    vita.presence_accept(row)

s3xrc.model.configure(table,
    super_entity = db.sit_situation,
    onvalidation = lambda form: s3_pr_presence_onvalidation(form),
    onaccept = lambda form: s3_pr_presence_onaccept(form),
    delete_onaccept = lambda row: s3_pr_presence_ondelete(row),
    list_fields = [
        "id",
        "datetime",
        "location_id",
        "shelter_id",
        "presence_condition",
        "orig_id",
        "dest_id"
    ],
    main="time", extra="location_details")


ADD_LOG_ENTRY = T("Add Log Entry")
s3.crud_strings[tablename] = Storage(
    title_create = ADD_LOG_ENTRY,
    title_display = T("Log Entry Details"),
    title_list = T("Presence Log"),
    title_update = T("Edit Log Entry"),
    title_search = T("Search Log Entry"),
    subtitle_create = T("Add New Log Entry"),
    subtitle_list = T("Current Log Entries"),
    label_list_button = T("List Log Entries"),
    label_create_button = ADD_LOG_ENTRY,
    msg_record_created = T("Log entry added"),
    msg_record_modified = T("Log entry updated"),
    msg_record_deleted = T("Log entry deleted"),
    msg_list_empty = T("No Presence Log Entries currently registered"))


# *****************************************************************************
# Note (future replacement for pr_presence and pf_missing_report)
#
#pr_note_types = {
    #1:T("Location"),
    #2:T("Status"),
    #3:T("Note")
#}

#pr_note_status = {
    #1:T("reported"),
    #2:T("confirmed"),
    #3:T("invalid")
#}

#pr_procedure_types = {
    #1:T("Check-in"),
    #2:T("Check-out")
#}

#resourcename = "note"
#tablename = "%s_%s" % (prefix, resourcename)
#table = db.define_table(tablename,
                        #super_link(db.pr_pentity), # pe_id
                        #person_id("reporter"),

                        ## Note type and status
                        #Field("note_type", "integer",
                              #requires = IS_IN_SET(pr_note_types, zero=None),
                              #default = 3,
                              #label = T("Note Type"),
                              #represent = lambda opt: \
                                          #pr_note_types.get(opt, UNKNOWN_OPT)),
                        #Field("note_status", "integer",
                              #requires = IS_IN_SET(pr_note_status, zero=None),
                              #default = 1,
                              #label = T("Note Status"),
                              #represent = lambda opt: \
                                          #pr_note_status.get(opt, UNKNOWN_OPT)),

                        ## Time stamp
                        #Field("timestmp", "datetime"),

                        ## Last known location
                        #location_id(),
                        #shelter_id(),
                        #hospital_id(),

                        ## Note text (optional)
                        #Field("note_text", "text"),

                        ## Person status
                        #Field("missing", "boolean", default=False),
                        #Field("injured", "boolean", default=False),
                        #Field("deceased", "boolean", default=False),

                        ## Procedure: None, Check-in or Check-out
                        #Field("procedure", "integer",
                              #requires = IS_EMPTY_OR(IS_IN_SET(pr_procedure_types)),
                              #default = None,
                              #label = T("Procedure"),
                              #represent = lambda opt: \
                                          #pr_procedure_types.get(opt, UNKNOWN_OPT)),

                        #Field("closed", "boolean", default=False),
                        #migrate=migrate, *s3_meta_fields())


## CRUD strings
#ADD_NOTE = T("Add Note")
#s3.crud_strings[tablename] = Storage(
    #title_create = ADD_NOTE,
    #title_display = T("Note Details"),
    #title_list = T("Notes"),
    #title_update = T("Edit Note"),
    #title_search = T("Search Notes"),
    #subtitle_create = T("Add New Note"),
    #subtitle_list = T("Current Notes"),
    #label_list_button = T("List Notes"),
    #label_create_button = ADD_NOTE,
    #msg_record_created = T("Note added"),
    #msg_record_modified = T("Note updated"),
    #msg_record_deleted = T("Note deleted"),
    #msg_list_empty = T("No notes available"))


## Notes as component of person entities
#s3xrc.model.add_component(prefix, resourcename,
                          #multiple=True,
                          #joinby=super_key(db.pr_pentity))


# *****************************************************************************
# Subscription (pe_subscription)
#
resourcename = "pe_subscription"
tablename = "%s_%s" % (prefix, resourcename)
table = db.define_table(tablename,
                        super_link(db.pr_pentity), # pe_id
                        Field("resource"),
                        Field("record"), # type="s3uuid"
                        comments(),
                        migrate=migrate, *s3_meta_fields())



table.uuid.requires = IS_NOT_ONE_OF(db, "%s.uuid" % tablename)
table.pe_id.requires = IS_ONE_OF(db, "pr_pentity.pe_id",
                                    shn_pentity_represent,
                                    filterby="instance_type",
                                    orderby="instance_type",
                                    filter_opts=("pr_person", "pr_group"))

# Moved to zzz_last.py to ensure all tables caught!
#table.resource.requires = IS_IN_SET(db.tables)

# Subscriptions as component of person entities
s3xrc.model.add_component(prefix, resourcename,
                          multiple=True,
                          joinby=super_key(db.pr_pentity))

s3xrc.model.configure(table,
    list_fields=[
        "id",
        "resource",
        "record"
    ])

s3.crud_strings[tablename] = Storage(
    title_create = T("Add Subscription"),
    title_display = T("Subscription Details"),
    title_list = T("Subscriptions"),
    title_update = T("Edit Subscription"),
    title_search = T("Search Subscriptions"),
    subtitle_create = T("Add Subscription"),
    subtitle_list = T("Subscriptions"),
    label_list_button = T("List Subscriptions"),
    label_create_button = T("Add Subscription"),
    label_delete_button = T("Delete Subscription"),
    msg_record_created = T("Subscription added"),
    msg_record_modified = T("Subscription updated"),
    msg_record_deleted = T("Subscription deleted"),
    msg_list_empty = T("No Subscription available"))


# *****************************************************************************
# Identity
#
pr_id_type_opts = {
    1:T("Passport"),
    2:T("National ID Card"),
    3:T("Driving License"),
    99:T("other")
}


# -----------------------------------------------------------------------------
resourcename = "identity"
tablename = "%s_%s" % (prefix, resourcename)
table = db.define_table(tablename,
                        person_id(),
                        Field("type", "integer",
                              requires = IS_IN_SET(pr_id_type_opts, zero=None),
                              default = 1,
                              label = T("ID type"),
                              represent = lambda opt: \
                                          pr_id_type_opts.get(opt, UNKNOWN_OPT)),
                        Field("value"),
                        Field("description"),
                        Field("country_code", length=4),
                        Field("ia_name"), # Name of issuing authority
                        #Field("ia_subdivision"), # Name of issuing authority subdivision
                        #Field("ia_code"), # Code of issuing authority (if any)
                        comments(),
                        migrate=migrate, *s3_meta_fields())


table.uuid.requires = IS_NOT_ONE_OF(db, "%s.uuid" % tablename)
table.person_id.label = T("Person")
table.value.requires = [IS_NOT_EMPTY(), IS_NOT_ONE_OF(db, "%s.value" % tablename)]
table.ia_name.label = T("Issuing Authority")

# Identity as component of persons
s3xrc.model.add_component(prefix, resourcename,
                          multiple=True,
                          joinby=dict(pr_person="person_id"))

s3xrc.model.configure(table,
    list_fields=[
        "id",
        "type",
        "type",
        "value",
        "country_code",
        "ia_name"
    ])

ADD_IDENTITY = T("Add Identity")
s3.crud_strings[tablename] = Storage(
    title_create = ADD_IDENTITY,
    title_display = T("Identity Details"),
    title_list = T("Known Identities"),
    title_update = T("Edit Identity"),
    title_search = T("Search Identity"),
    subtitle_create = T("Add New Identity"),
    subtitle_list = T("Current Identities"),
    label_list_button = T("List Identities"),
    label_create_button = ADD_IDENTITY,
    msg_record_created = T("Identity added"),
    msg_record_modified = T("Identity updated"),
    msg_record_deleted = T("Identity deleted"),
    msg_list_empty = T("No Identities currently registered"))


# *****************************************************************************
# PR Extension: physical description
#
if deployment_settings.has_module("dvi") or \
   deployment_settings.has_module("mpr"):

    pr_race_opts = {
        1: T("caucasoid"),
        2: T("mongoloid"),
        3: T("negroid"),
        99: T("other")
    }

    pr_complexion_opts = {
        1: T("light"),
        2: T("medium"),
        3: T("dark"),
        99: T("other")
    }

    pr_height_opts = {
        1: T("short"),
        2: T("average"),
        3: T("tall")
    }

    pr_weight_opts = {
        1: T("slim"),
        2: T("average"),
        3: T("fat")
    }

    pr_blood_type_opts = {
        1: "A",
        2: "B",
        3: "0",
        4: "AB"
    }

    pr_eye_color_opts = {
        1: T("blue"),
        2: T("grey"),
        3: T("green"),
        4: T("brown"),
        5: T("black"),
        99: T("other")
    }

    pr_hair_color_opts = {
        1: T("blond"),
        2: T("brown"),
        3: T("black"),
        4: T("red"),
        5: T("grey"),
        6: T("white"),
        99: T("see comment")
    }

    pr_hair_style_opts = {
        1: T("straight"),
        2: T("wavy"),
        3: T("curly"),
        99: T("see comment")
    }

    pr_hair_length_opts = {
        1: T("short<6cm"),
        2: T("medium<12cm"),
        3: T("long>12cm"),
        4: T("shaved"),
        99: T("see comment")
    }

    pr_hair_baldness_opts = {
        1: T("forehead"),
        2: T("sides"),
        3: T("tonsure"),
        4: T("total"),
        99: T("see comment")
    }

    pr_facial_hair_type_opts = {
        1: T("none"),
        2: T("Moustache"),
        3: T("Goatee"),
        4: T("Whiskers"),
        5: T("Full beard"),
        99: T("see comment")
    }

    pr_facial_hair_length_opts = {
        1: T("short"),
        2: T("medium"),
        3: T("long"),
        4: T("shaved")
    }


# -----------------------------------------------------------------------------
    resourcename = "physical_description"
    tablename = "%s_%s" % (prefix, resourcename)
    table = db.define_table(tablename,
                            super_link(db.pr_pentity), # pe_id

                            # Race and complexion
                            Field("race", "integer",
                                  requires = IS_EMPTY_OR(IS_IN_SET(pr_race_opts)),
                                  label = T("Race"),
                                  represent = lambda opt: \
                                              pr_race_opts.get(opt, UNKNOWN_OPT)),
                            Field("complexion", "integer",
                                  requires = IS_EMPTY_OR(IS_IN_SET(pr_complexion_opts)),
                                  label = T("Complexion"),
                                  represent = lambda opt: \
                                              pr_complexion_opts.get(opt, UNKNOWN_OPT)),
                            Field("ethnicity"),

                            # Height and weight
                            Field("height", "integer",
                                  requires = IS_EMPTY_OR(IS_IN_SET(pr_height_opts)),
                                  label = T("Height"),
                                  represent = lambda opt: \
                                              pr_height_opts.get(opt, UNKNOWN_OPT)),
                            Field("height_cm", "integer",
                                  requires = IS_NULL_OR(IS_INT_IN_RANGE(0, 300)),
                                  label = T("Height (cm)")),
                            Field("weight", "integer",
                                  requires = IS_EMPTY_OR(IS_IN_SET(pr_weight_opts)),
                                  label = T("Weight"),
                                  represent = lambda opt: \
                                              pr_weight_opts.get(opt, UNKNOWN_OPT)),
                            Field("weight_kg", "integer",
                                  requires = IS_NULL_OR(IS_INT_IN_RANGE(0, 500)),
                                  label = T("Weight (kg)")),

                            # Blood type, eye color
                            Field("blood_type", "integer",
                                  requires = IS_EMPTY_OR(IS_IN_SET(pr_blood_type_opts)),
                                  label = T("Blood Type (AB0)"),
                                  represent = lambda opt: \
                                              pr_blood_type_opts.get(opt, UNKNOWN_OPT)),
                            Field("eye_color", "integer",
                                  requires = IS_EMPTY_OR(IS_IN_SET(pr_eye_color_opts)),
                                  label = T("Eye Color"),
                                  represent = lambda opt: \
                                              pr_eye_color_opts.get(opt, UNKNOWN_OPT)),

                            # Hair of the head
                            Field("hair_color", "integer",
                                  requires = IS_EMPTY_OR(IS_IN_SET(pr_hair_color_opts)),
                                  label = T("Hair Color"),
                                  represent = lambda opt: \
                                              pr_hair_color_opts.get(opt, UNKNOWN_OPT)),
                            Field("hair_style", "integer",
                                  requires = IS_EMPTY_OR(IS_IN_SET(pr_hair_style_opts)),
                                  label = T("Hair Style"),
                                  represent = lambda opt: \
                                              pr_hair_style_opts.get(opt, UNKNOWN_OPT)),
                            Field("hair_length", "integer",
                                  requires = IS_EMPTY_OR(IS_IN_SET(pr_hair_length_opts)),
                                  label = T("Hair Length"),
                                  represent = lambda opt: \
                                              pr_hair_length_opts.get(opt, UNKNOWN_OPT)),
                            Field("hair_baldness", "integer",
                                  requires = IS_EMPTY_OR(IS_IN_SET(pr_hair_baldness_opts)),
                                  label = T("Baldness"),
                                  represent = lambda opt: \
                                              pr_hair_baldness_opts.get(opt, UNKNOWN_OPT)),
                            Field("hair_comment"),

                            # Facial hair
                            Field("facial_hair_type", "integer",
                                  requires = IS_EMPTY_OR(IS_IN_SET(pr_facial_hair_type_opts)),
                                  label = T("Facial hair, type"),
                                  represent = lambda opt: \
                                              pr_facial_hair_type_opts.get(opt, UNKNOWN_OPT)),
                            Field("facial_hair_color", "integer",
                                  requires = IS_EMPTY_OR(IS_IN_SET(pr_hair_color_opts)),
                                  label = T("Facial hair, color"),
                                  represent = lambda opt: \
                                              pr_hair_color_opts.get(opt, UNKNOWN_OPT)),
                            Field("facial_hair_length", "integer",
                                  requires = IS_EMPTY_OR(IS_IN_SET(pr_facial_hair_length_opts)),
                                  label = T("Facial hear, length"),
                                  represent = lambda opt: \
                                              pr_facial_hair_length_opts.get(opt, UNKNOWN_OPT)),
                            Field("facial_hair_comment"),

                            # Body hair and skin marks
                            Field("body_hair"),
                            Field("skin_marks", "text"),

                            # Medical Details: scars, amputations, implants
                            Field("medical_conditions", "text"),

                            # Other details
                            Field("other_details", "text"),

                            comments(),
                            migrate=migrate, *s3_meta_fields())


    table.height_cm.comment = DIV(DIV(_class="tooltip",
        _title=T("Height") + "|" + T("The body height (crown to heel) in cm.")))
    table.weight_kg.comment = DIV(DIV(_class="tooltip",
        _title=T("Weight") + "|" + T("The weight in kg.")))

    table.pe_id.readable = False
    table.pe_id.writable = False

    # Physical description as component of person entity
    s3xrc.model.add_component(prefix, resourcename,
                              multiple=False,
                              joinby=super_key(db.pr_pentity))

# End
# *****************************************************************************