forked from dodobas/waterboard
-
Notifications
You must be signed in to change notification settings - Fork 2
/
temp_deleted_20180316.txt
1302 lines (931 loc) · 31.4 KB
/
temp_deleted_20180316.txt
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
{
externalLayers: {
bingLayer: {
label: 'Bing Layer',
key: 'AuhiCJHlGzhg93IqUH_oCpl_-ZUrIE6SPftlyGYUvr9Amx5nzA-WqGcPquyFZl4L',
}
},
withUrl: {
mapbox: {
label: 'MapBox',
mapOpts: {
url: 'https://api.mapbox.com/v4/mapbox.streets/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoicmFrc2hhayIsImEiOiJ5cHhqeHlRIn0.Vi87VjI1cKbl1lhOn95Lpw',
options: {
attribution: '© <a href="https://www.mapbox.com/feedback/">Mapbox</a> © <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
}
}
},
googleSatLayer: {
label: 'Google Satellite',
mapOpts: {
url: 'http://{s}.google.com/vt/lyrs=s&x={x}&y={y}&z={z}',
options: {
maxZoom: 20,
subdomains: ['mt0', 'mt1', 'mt2', 'mt3']
}
}
}
}
}
/* $('body').off('click', this.options.submitBtnSelector);
$('body').on('click', this.options.submitBtnSelector, function (e) {
e.preventDefault();
var formData = parseAttributesForm(self.formDomObj);
if (self.options.updateCb && self.options.updateCb instanceof Function) {
self.options.updateCb(formData, self)
}
});*/
/**
* Create leaflet Markers from marker definitions - markersData
*
* @param markersData - marker definitions {lat:, lng: , draggable: .... other}
* @param leafletMap - leaflet map instance
* @param layerGroup - if specified markers will be added to this layer group L.layerGroup([])
* @param addToMap boolean - if true will add marker layer to leaflet map
* @param clearLayer boolean - if true will clear provided layer
* @returns {layerGroup} featureMarkers
*/
function _createMarkersOnLayer(options) {
var markersData = options.markersData;
var addToMap = options.addToMap;
var clearLayer = options.clearLayer;
var iconIdentifierKey = options.iconIdentifierKey;
_handleLayers(clearLayer, addToMap);
var i = 0, marker;
var dataCnt = markersData.length;
for (i; i < dataCnt; i += 1) {
marker = createDashBoardMarker({
marker: markersData[i],
iconIdentifierKey: iconIdentifierKey
});
marker.addTo(featureMarkers);
}
return featureMarkers;
}
.wb-actions-row {
width: 100%;
display: block;
position: relative;
padding: 0.1em 0 0.3em;
}
.wb-actions-row .wb-actions {
padding: 0 5px;
}
.wb-actions-row .geo-search-wrap {
position: relative;
display: block;
float: right;
width: 100%;
min-width: 150px;
max-width: 350px;
}
<div class="navbar navbar-fixed-top">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
data-target="#wb-navbar-collapse" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/" title="Waterboard"></a>
</div>
<div class="collapse navbar-collapse" id="wb-navbar-collapse">
<ul class="nav navbar-nav">
<li class="active">
<a href="/table-report">Back <span class="sr-only">(current)</span></a>
</li>
{# <li><a href="#">Link</a></li>#}
</ul>
<ul class="nav navbar-nav navbar-right">
{% if not user.is_authenticated %}
<li id="login_id">
<a href="/login">
Login
</a>
</li>
{% else %}
<li>
<a href="/logout">
Logout
</a>
</li>
{% endif %}
</ul>
</div>
</div>
</div>
</nav>
/**
* Get chart filter keys (filter field names) from chart config
* @param chartConf
* @returns {*}
*/
DashboardController.getFilterableChartKeys = function (chartConf) {
return Object.keys(chartConf).reduce(function (acc, val, i) {
if (chartConf[val].isFilter === true) {
acc[acc.length] = chartConf[val].name;
}
return acc;
}, []);
};
/**
* Get chart keys for specified chart type
* @param chartConf
* @param chartType
* @returns {*}
*/
DashboardController.getChartKeysByChartType = function (chartConf, chartType) {
return Object.keys(chartConf).reduce(function (acc, val, i) {
if (chartConf[val].chartType === chartType) {
acc[acc.length] = val;
}
return acc;
}, []);
};
function SimpleStorage(storage) {
this.storage = storage || {};
}
// TODO unneded - remoev prolly
SimpleStorage.prototype = {
setItem: function (key, val) {
this.storage[key] = val;
return this.storage[key];
},
getItem: function (key) {
if (key !== undefined && key !== null) {
return _.get(this.storage, key);
}
return this.storage;
},
getItems: function (keys) {
var key, i = 0, items = {};
var keysCnt = (keys || []).length;
if (keysCnt > 1) {
for (i; i < keysCnt; i += i) {
key = keys[i];
if (key !== undefined && key !== null) {
items[key] = _.get(this.storage, key);
}
}
return items;
}
return this.storage;
},
removeItem: function (key) {
delete this.storage[key];
},
setStorage: function (storage) {
this.storage = storage || {};
}
};
WB.Storage = new SimpleStorage(globalVars);
/** TODO REMOVE
* After resize / debounce
* @param func
* @param wait
* @param endCheck
* @returns {Function}
*/
function _debounce(func, wait, endCheck) {
var timeout;
return function () {
const that = this;
const args = arguments;
const later = function () {
timeout = null;
if (!endCheck) {
func.apply(that, args);
}
};
const callNow = endCheck && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) {
func.apply(that, args);
}
};
}
/** TODO remove
* taken from: https://github.com/cosmosio/nested-property
* Get the property of an object nested in one or more objects
* given an object such as a.b.c.d = 5, getNestedProperty(a, "b.c.d") will return 5.
* @param {Object} object the object to get the property from
* @param {String} property the path to the property as a string
* @returns the object or the the property value if found
*/
function _getNestedProperty(object, property) {
if (object && typeof object == "object") {
if (typeof property == "string" && property !== "") {
var split = property.split(".");
return split.reduce(function (obj, prop) {
return obj && obj[prop];
}, object);
} else if (typeof property == "number") {
return object[property];
} else {
return object;
}
} else {
return object;
}
}
WB.utils.ax({
method: 'POST',
url: '/data/',
data: opts.data,
successCb: opts.successCb || function (data) {
WB.controller.updateDashboards(data);
},
errorCb: opts.errorCb || function (request, error) {
WB.notif.options({
message: 'Could not Fetch Dashboard data.',
type: 'danger'
}).show();
}
});
{# <script src="https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv.min.js" integrity="sha256-3Jy/GbSLrg0o9y5Z5n1uw0qxZECH7C6OQpVBgNFYa0g=" crossorigin="anonymous"></script>#}
var dynamicColumns = reportTableDataAttributes.map(function (attribute) {
return {
data: attribute.key,
title: '<div>' + attribute.label + '</div>',
searchable: attribute.searchable,
orderable: attribute.orderable
};
});
var TABLE_REPORT_COLUMNS = [{
data: '_last_update',
title: 'Last Update',
searchable: false,
render: timestampColumnRenderer,
orderable: true
}, {
data: '_webuser',
title: 'User',
searchable: false,
orderable: true
}].concat(dynamicColumns);
var options = {
dataTable: {
"dom": 'l<"wb-export-toolbar">frtip',
scrollX: true,
fixedHeader: true,
columns: TABLE_REPORT_COLUMNS,
order: [[0, 'desc']],
lengthMenu: TABLE_ROWS_PER_PAGE,
rowClickCb: tableRowClickHandlerFn,
serverSide: true,
// this is only throttling and not debouncing, for debouncing we need to fully control search input events
searchDelay: 400,
ajax: {
url: '/table-data',
type: 'POST'
}
}
};
// TODO combine all init functions
/* var WB = (function (module) {
if (!module.controller) {
module.controller = {};
}
// init module and set options
WB.notif = WB.SimpleNotification()
.options({
message: null,
type: 'success',
fadeOut: {
delay: Math.floor(Math.random() * 500) + 2500,
enabled: true
}
});
})(WB || {});*/
WB.notif = WB.SimpleNotification()
.options({
message: null,
type: 'success',
fadeOut: {
delay: Math.floor(Math.random() * 500) + 2500,
enabled: true
}
});
WB.notif();
WB.FeatureForm = new SimpleForm({
formId: 'feature-create-form',
parentId: 'formWrap',
isEnabled: true,
isBtnVisible: true,
submitBtnSelector: '#create_button',
onSubmit: function (formData, formInstance) {
WB.loadingModal.show();
formInstance.formDomObj.submit();
},
accordionConf: {
selector: '#data-accordion',
opts: {
heightStyle: "content",
header: "div > h3"
}
}
});
// Leaflet Map
var coords = WB.FeatureForm.getFormFieldValues(['_latitude', '_longitude']);
var markerGeometry = {lon: 38.3, lat: 14.3};
if (coords._longitude && coords._latitude) {
markerGeometry = {
lon: coords._longitude,
lat: coords._latitude
};
} else {
WB.FeatureForm.setFormFieldValues({
_longitude: markerGeometry.lon,
_latitude: markerGeometry.lat
});
}
// setup
WB.mapInstance = wbMap()
.layerConf(TILELAYER_DEFINITIONS)
.leafletConf({
zoom: 12,
editable: true
}, 'MapBox')
.markerRenderer(createFeatureByUUidMarker)
.initMapSearch({
parentId: 'geo-search-wrap'
})
.markerData([{
geometry: markerGeometry,
data: {},
draggable: true,
zoomToMarker: true
}]);
// init
WB.mapInstance('featureMapWrap');
// add markers
WB.mapInstance.renderMarkers({});
create or replace function core_utils.prepare_filtered_dashboard_data(i_webuser_id integer, i_min_x double precision, i_min_y double precision, i_max_x double precision, i_max_y double precision, i_filters json default '{}'::json)
returns void
LANGUAGE plpgsql
AS $BODY$
declare
l_query text;
l_filter_query text;
l_filter text;
l_is_staff boolean;
l_geofence geometry;
l_woreda_predicate text;
l_geofence_predicate text;
begin
-- TODO handle ranges
-- {"tabiya":"Egub","fencing_exists":"No","funded_by":"FoodSecurity","water_committe_exist":"Unknown","static_water_level":4,"amount_of_deposited":4,"yield":5,"should_not_appeat":null}
l_filter_query:= format($WHERE_FILTER$
SELECT
string_agg('and (' || same_filter_values || ')', ' ')
from
(
SELECT distinct
filter_key,
string_agg(
filter_key || '=' || quote_literal(filter_value) , ' or '
) over (partition by filter_key) as same_filter_values
FROM (
SELECT
"key" as filter_key,
json_array_elements_text("value"::json) as filter_value
FROM
json_each_text(
'%s'::JSON
)
) a
where a.filter_value is not null
group by
filter_key,
filter_value
) k
$WHERE_FILTER$, i_filters);
execute l_filter_query into l_filter;
-- point_geometry && ST_SetSRID(ST_MakeBox2D(ST_Point(-180, -90), ST_Point(180, 90)), 4326)
-- check if user has is_staff
l_query := format('select is_staff OR is_readonly, geofence FROM webusers_webuser where id = %L', i_webuser_id);
EXECUTE l_query INTO l_is_staff, l_geofence;
IF l_is_staff = FALSE
THEN
l_woreda_predicate := format(' AND woreda IN (SELECT unnest(values) FROM webusers_grant WHERE webuser_id = %L)',
i_webuser_id);
ELSE
l_woreda_predicate := NULL;
END IF;
-- geofence predicate
IF l_geofence IS NOT NULL THEN
l_geofence_predicate := format(' AND st_within(point_geometry, %L)', l_geofence);
ELSE
l_geofence_predicate := NULL;
END IF;
-- create temporary table so the core_utils.get_core_dashboard_data is called only once
-- filtering / aggregation / statistics should be taken from tmp_dashboard_chart_data
l_query := format($TEMP_TABLE_QUERY$create temporary table if not exists tmp_dashboard_chart_data on commit drop
as
select *
from (
select *,
CASE
WHEN static_water_level::FLOAT >= 100
THEN 5
WHEN static_water_level::FLOAT >= 50 AND static_water_level::FLOAT < 100
THEN 4
WHEN static_water_level::FLOAT >= 20 AND static_water_level::FLOAT < 50
THEN 3
WHEN static_water_level::FLOAT > 10 AND static_water_level::FLOAT < 20
THEN 2
ELSE 1
END AS static_water_level_group_id,
CASE
WHEN amount_of_deposited::FLOAT >= 5000
THEN 5
WHEN amount_of_deposited::FLOAT >= 3000 AND amount_of_deposited::FLOAT < 5000
THEN 4
WHEN amount_of_deposited::FLOAT >= 500 AND amount_of_deposited::FLOAT < 3000
THEN 3
WHEN amount_of_deposited::FLOAT > 1 AND amount_of_deposited::FLOAT < 500
THEN 2
ELSE 1
END AS amount_of_deposited_group_id,
CASE
WHEN yield::FLOAT >= 6
THEN 5
WHEN yield::FLOAT >= 3 AND yield::FLOAT < 6
THEN 4
WHEN yield::FLOAT >= 1 AND yield::FLOAT < 3
THEN 3
WHEN yield::FLOAT > 0 AND yield::FLOAT < 1
THEN 2
ELSE 1
END AS yield_group_id
FROM
features.active_data
) core_data
WHERE
point_geometry && ST_SetSRID(ST_MakeBox2D(ST_Point(%s, %s), ST_Point(%s, %s)), 4326)
%s %s %s
$TEMP_TABLE_QUERY$, i_min_x, i_min_y, i_max_x, i_max_y, l_filter, l_woreda_predicate, l_geofence_predicate);
execute l_query;
END;
$BODY$;
-- *
-- core_utils.create_feature
-- *
CREATE or replace FUNCTION core_utils.create_feature(i_feature_changeset integer, i_feature_point_geometry geometry, i_feature_attributes text)
RETURNS text
LANGUAGE plpgsql
AS $$
DECLARE
v_new_attributes JSONB;
v_key TEXT;
v_attr_id INTEGER;
v_result_type TEXT;
v_allowed_values TEXT [];
v_feature_uuid uuid;
v_int_value INTEGER;
v_decimal_value DECIMAL(9, 2);
v_text_value text;
BEGIN
-- insert a new feature
INSERT INTO features.feature (feature_uuid, changeset_id, point_geometry, is_active)
VALUES (
uuid_generate_v4(), i_feature_changeset, i_feature_point_geometry,
TRUE
) RETURNING feature_uuid INTO v_feature_uuid;
-- v_new_attributes := jsonb_strip_nulls(i_feature_attributes::jsonb);
v_new_attributes := i_feature_attributes::jsonb;
-- cast(i_feature_attributes AS JSONB);
-- collect type definitions
CREATE TEMPORARY TABLE tmp_attribute_types ON COMMIT DROP AS
SELECT
aa.id,
aa.key AS key,
aa.result_type,
array_agg(ao.value) AS allowed_values
FROM attributes_attribute aa
JOIN attributes_attributegroup ag ON aa.attribute_group_id = ag.id
LEFT JOIN attributes_attributeoption ao ON ao.attribute_id = aa.id
GROUP BY aa.id, aa.key, aa.result_type;
FOR v_key IN SELECT * FROM jsonb_object_keys(v_new_attributes) LOOP
-- check attributes
SELECT
id,
result_type,
allowed_values
INTO
v_attr_id,
v_result_type,
v_allowed_values
FROM tmp_attribute_types
WHERE key = v_key;
IF NOT FOUND
THEN
RAISE NOTICE 'Attribute="%" is not defined, skipping', v_key;
CONTINUE;
END IF;
-- check attribute type
IF v_result_type = 'Integer'
THEN
v_int_value := v_new_attributes ->> v_key;
-- only insert new data if the value has changed
-- insert new data
INSERT INTO features.feature_attribute_value (feature_uuid, changeset_id, attribute_id, val_int)
VALUES (
v_feature_uuid, i_feature_changeset, v_attr_id, v_int_value
);
ELSEIF v_result_type = 'Decimal'
THEN
v_decimal_value := v_new_attributes ->> v_key;
-- only insert new data if the value has changed
-- insert new data
INSERT INTO features.feature_attribute_value (feature_uuid, changeset_id, attribute_id, val_real)
VALUES (
v_feature_uuid, i_feature_changeset, v_attr_id, v_decimal_value
);
ELSEIF v_result_type = 'Text'
THEN
-- for whatever reason text values must be extracted as text (oprerator ->>)
v_text_value := v_new_attributes ->> v_key;
-- only insert new data if the value has changed
-- insert new data
INSERT INTO features.feature_attribute_value (feature_uuid, changeset_id, attribute_id, val_text)
VALUES (
v_feature_uuid, i_feature_changeset, v_attr_id, nullif(v_text_value::text, '')
);
ELSEIF v_result_type = 'DropDown'
THEN
v_int_value := v_new_attributes ->> v_key;
-- only insert new data if the value has changed
IF NOT (v_allowed_values @> ARRAY [v_int_value :: TEXT])
THEN
RAISE 'Attribute "%" value "%" is not allowed: %', v_key, v_int_value, v_allowed_values;
END IF;
-- insert new data
INSERT INTO features.feature_attribute_value (feature_uuid, changeset_id, attribute_id, val_int)
VALUES (
v_feature_uuid, i_feature_changeset, v_attr_id, v_int_value
);
END IF;
END LOOP;
-- we need to refresh the materialized view
-- execute core_utils.refresh_active_data();
RETURN v_feature_uuid::text;
END;
$$;
-- *
-- * create materialized view active_data and refresh
-- *
CREATE OR REPLACE FUNCTION core_utils.refresh_active_data()
RETURNS void
LANGUAGE plpgsql
AS $$
DECLARE
v_query TEXT;
l_args TEXT;
l_field_def TEXT;
BEGIN
v_query := $attributes$
select
string_agg(quote_literal(key), ',' ORDER BY key) as args,
string_agg(key || ' text', ', ' ORDER BY key) as field_def
from (
SELECT key
FROM
attributes_attribute
ORDER BY
key
)d;
$attributes$;
EXECUTE v_query
INTO l_args, l_field_def;
v_query := format($q$
CREATE MATERIALIZED VIEW IF NOT EXISTS features.active_data AS (
select * from core_utils.get_core_dashboard_data(
%s
) as (
point_geometry geometry, email varchar, ts timestamp with time zone, feature_uuid uuid,
%s
)
);$q$, l_args, l_field_def);
EXECUTE v_query;
-- unique index is required for concurrent updates
CREATE UNIQUE INDEX IF NOT EXISTS features_active_data_feature_uuid ON features.active_data (feature_uuid);
REFRESH MATERIALIZED VIEW CONCURRENTLY features.active_data;
END;
$$;
-- *
-- core_utils.get_feature_by_changeset_uuid
-- *
CREATE OR REPLACE FUNCTION
core_utils.get_feature_by_changeset_uuid(i_uuid UUID, i_changeset_id int)
RETURNS TEXT AS
$BODY$
SELECT coalesce(jsonb_agg(d.row) :: TEXT, '[]') AS data
FROM (
SELECT jsonb_build_object(
'_feature_uuid', ft.feature_uuid :: TEXT,
'_created_date', chg.ts_created,
'_data_captor', wu.email,
'_geometry', ARRAY [ST_Y(ft.point_geometry), ST_X(ft.point_geometry)]
) || coalesce(attributes.row, '{}' :: JSONB) AS row
FROM
features.feature ft
LEFT JOIN LATERAL (
SELECT
fav.feature_uuid,
jsonb_object_agg(
dg.key || '/' || da.key,
row_to_json(fav) -> CASE
WHEN da.result_type = 'Integer'
THEN 'val_int'
WHEN da.result_type = 'Decimal'
THEN 'val_real'
WHEN da.result_type = 'Text'
THEN 'val_text'
WHEN da.result_type = 'DropDown'
THEN 'val_int'
WHEN da.result_type = 'MultipleChoice'
THEN 'val_text'
ELSE NULL
END
) AS row
FROM
features.feature_attribute_value fav
JOIN public.attributes_attribute da ON da.id = fav.attribute_id
JOIN public.attributes_attributegroup dg ON dg.id = da.attribute_group_id
WHERE
fav.feature_uuid = ft.feature_uuid
and fav.changeset_id = i_changeset_id
GROUP BY fav.feature_uuid
) attributes ON TRUE
JOIN
features.changeset chg ON ft.changeset_id = chg.id
JOIN
webusers_webuser wu ON chg.webuser_id = wu.id
WHERE
ft.feature_uuid = $1
AND
ft.changeset_id = i_changeset_id
GROUP BY ft.feature_uuid, chg.ts_created, wu.email, ft.point_geometry,
attributes.row
ORDER BY ft.feature_uuid) d;
$BODY$
LANGUAGE SQL;
-- *
-- core_utils.get_event_by_uuid
-- *
CREATE OR REPLACE FUNCTION core_utils.get_event_by_uuid(i_uuid UUID)
RETURNS TEXT AS
$BODY$
SELECT coalesce(jsonb_agg(d.row) :: TEXT, '[]') AS data
FROM (
SELECT jsonb_build_object(
'_feature_uuid', ft.feature_uuid :: TEXT,
'_created_date', chg.ts_created,
'_data_captor', wu.email,
'_geometry', ARRAY [ST_X(ft.point_geometry), ST_Y(ft.point_geometry)]
) || coalesce(attributes.row, '{}' :: JSONB) AS row
FROM
features.feature ft
LEFT JOIN LATERAL (
SELECT
fav.feature_uuid,
jsonb_object_agg(
dg.key || '/' || da.key,
row_to_json(fav) -> CASE
WHEN da.result_type = 'Integer'
THEN 'val_int'
WHEN da.result_type = 'Decimal'
THEN 'val_real'
WHEN da.result_type = 'Text'
THEN 'val_text'
WHEN da.result_type = 'DropDown'
THEN 'val_int'
WHEN da.result_type = 'MultipleChoice'