-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest-data-tracker.js
More file actions
1357 lines (1183 loc) · 45 KB
/
test-data-tracker.js
File metadata and controls
1357 lines (1183 loc) · 45 KB
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
/********************************************/
/******** COACD Single Sign On Login ********/
/********************************************/
function customizeLoginButton(viewId) {
// Hide Knack default SSO button, login form, login title, and any other children
$("#" + viewId)
.children()
.hide();
var url = Knack.url_base + Knack.scene_hash + "auth/COACD";
// Create a div for Login buttons
var $coacdButton = $("<div/>", {
id: "coacd-button-login",
});
$coacdButton.appendTo("#" + viewId);
// Append Big SSO Login button and non-SSO Login button
bigButton(
"coacd-big-button",
"coacd-button-login",
url,
"sign-in",
"Sign-In"
);
$coacdButton.append(
"<a class='small-button' href='javascript:void(0)'>" +
"<div class='small-button-container'><span><i class='fa fa-lock'></i></span><span> Non-COA Sign-In</span></div></a>"
);
// On non-SSO button click, hide SSO and non-SSO buttons and show Knack Login form
var $nonCoacdButton = $(".small-button");
$nonCoacdButton.click(function () {
$("#" + viewId)
.children()
.show();
$(".small-button-container,.big-button-container").hide();
$(".kn-sso-container").hide();
});
}
// Call customizeLoginButton on any view render to customize any login page that renders in app
$(document).on("knack-view-render.any", function (event, page) {
// Find SSO button and existing custom button
var $ssoButton = $(".kn-sso-container");
var $coacdLoginDiv = $("#coacd-button-login");
// If SSO button exists on page and there isn't already a custom button
if ($ssoButton.length && !$coacdLoginDiv.length) {
var $ssoView = $ssoButton.closest("[id^=view_]");
var viewId = $ssoView.get(0).id;
customizeLoginButton(viewId);
}
});
/********************************************/
/*************** Big Buttons ****************/
/********************************************/
//Create Big Button nested in a block
function bigButton(
id,
view_id,
url,
fa_icon,
button_label,
is_disabled = false,
callback = null
) {
var disabledClass = is_disabled ? " big-button-disabled'" : "'";
$(
"<a id='" +
id +
"' class='big-button-container" +
disabledClass +
" href='" +
url +
"'><span><i class='fa fa-" +
fa_icon +
"'></i></span><span> " +
button_label +
"</span></a>"
).appendTo("#" + view_id);
if (callback) callback();
}
/********************************************/
/************** Small Buttons ***************/
/********************************************/
//Create Small Button nested in a block
function smallButton(
id,
view_id,
url,
fa_icon,
button_label,
is_disabled = false,
callback = null
) {
var disabledClass = is_disabled ? " small-button-disabled'" : "'";
$(
"<a id='" +
id +
"' class='back-button" +
disabledClass +
" href='" +
url +
"'><span><i class='fa fa-" +
fa_icon +
"'></i></span><span> " +
button_label +
"</span></a>"
).appendTo("#" + view_id);
if (callback) callback();
}
$(document).on("knack-page-render.any", function (event, page) {
// Hide the entire "Repeat" checkbox and label
$("label:contains('Repeat')").hide();
// Rename confusing google maps link
$('a[title="view in google maps"]').text("View on Google Maps");
});
$(document).on("knack-view-render.view_958", function (event, page) {
// hide crumb trail at select locations
setTimeout(function () {
$(".kn-crumbtrail").remove();
//do something special
}, 1000);
});
/**
* Set the URL of the embedded AGOL map on the MMC issue/service request details page
*/
$(document).on("knack-scene-render.scene_428", function () {
var iframe_url = $(".kn-detail.field_1403 a").attr("href");
$(".view_1852").hide();
$("#csr_view").attr("src", iframe_url);
});
$(document).on("knack-view-render.view_1407", function (event, page) {
// default city/state for VZA enforcement
$("#city").val("Austin");
$("#state").val("TX");
});
function changeFieldColor(field, color_map) {
var child_field = $(field).find(".kn-value");
var value = child_field.text();
if (color_map[value]) {
$(child_field).css({
"background-color": color_map[value].background_color,
color: color_map[value].color,
});
}
}
var colorMapOne = {
"NEED TO BE ISSUED": { background_color: "#e41a1c", color: "#fff" },
"ON HOLD": { background_color: "#aeaeae", color: "#fff" },
ISSUED: { background_color: "#377eb8", color: "#fff" },
"NEEDS GIS": { background_color: "#984ea3", color: "#fff" },
"FINAL REVIEW": { background_color: "#4daf4a", color: "#fff" },
};
$(document).on("knack-view-render.view_2107", function (event, page) {
// replace attachment filename with attachment type
// find each attachment cell
$("td.field_2405").each(function () {
// find each attachment link within the cell
$(this)
.find("a")
.each(function (index) {
var attachmentType = "";
// search the neighboring field (attachmenty type) and retrieve the corresponding type
$(this)
.closest("tr")
.children("td.field_2403")
.find("span")
.children("span")
.each(function (index2) {
if (index == index2) {
attachmentType = $(this).text();
}
});
// update link contents
$(this).html(attachmentType);
});
});
});
$(document).on("knack-view-render.view_2108", function (event, page) {
// replace attachment filename with attachment type
// find each attachment cell
$("td.field_2405").each(function () {
// find each attachment link within the cell
$(this)
.find("a")
.each(function (index) {
var attachmentType = "";
// search the neighboring field (attachmenty type) and retrieve the corresponding type
$(this)
.closest("tr")
.children("td.field_2403")
.find("span")
.children("span")
.each(function (index2) {
if (index == index2) {
attachmentType = $(this).text();
}
});
// update link contents
$(this).html(attachmentType);
});
});
});
// replace 'Quantity' label with UOM of measure by parsing the select value contents
// was unable to use the chosen.js native events because of however Knack has implemented them
// so listening for click which is a bit wonky
function setUOM(element) {
// expects a connection selector field with a pipe-delmited name/unit of measure
var item = $(element).find("span").text();
if (item.split("|")[1]) {
var unitOfMeasure = item.split("|")[1].trim();
$("#kn-input-field_2214").find(".kn-input-label").text(unitOfMeasure);
}
}
$(document).on("knack-scene-render.scene_716", function (event, page) {
// handle a click
$("#view_1929_field_2220_chzn").click(function () {
setUOM(this);
});
// and for good measure update UOM on field focus
$("#field_2214").focus(function () {
var element = $("#view_1929_field_2220_chzn")["0"];
setUOM(element);
});
});
//////////////////////////////////////////////////
// Remove non-digits from street segment inputs///
//////////////////////////////////////////////////
/**
* Restricts an input field to digits by removing all non-digit characters.
* This function is designed to be used as a jQuery event handler.
*
* @function restrictToDigits
* @this {jQuery} The jQuery object representing the input element
* @returns {void}
*
* @example
* // Attach to a specific input field
* $("#phone-number").keyup(restrictToDigits);
*
* @example
* // Use with event delegation
* $(document).on("keyup", ".digits-only", restrictToDigits);
*
* @example
* // Attach to multiple events
* $("#zip-code").on("keyup input paste", restrictToDigits);
*/
function restrictToDigits() {
var currentValue = $(this).val();
// Remove all non-digit characters
var digitsOnly = currentValue.replace(/\D/g, "");
// Only update if the value changed to avoid cursor jumping
if (currentValue !== digitsOnly) {
$(this).val(digitsOnly);
}
}
$(document).on("knack-view-render.view_1199", function () {
// New location form - add primary street segment
$("#field_119").keyup(restrictToDigits);
});
$(document).on("knack-view-render.view_1200", function () {
// New location form - cross street segment
$("#field_119").keyup(restrictToDigits);
});
$(document).on("knack-view-render.view_1207", function () {
// Edit location form - primary street segment
$("#field_119").keyup(restrictToDigits);
});
$(document).on("knack-view-render.view_1206", function () {
// Edit location form - cross street segment
$("#field_119").keyup(restrictToDigits);
});
////////////////////////////////////////
// End non-digit character removal /////
////////////////////////////////////////
$(document).on("knack-view-render.view_2357", function (event, page) {
// now with minor changes, used for traffic count attachments field
// this one affects the table that those with editing priviledges see
// replace attachment filename with attachment type
// find each attachment cell
$("td.field_3176").each(function () {
// find each attachment link within the cell
$(this)
.find("a")
.each(function (index) {
var attachmentType = "";
// search the neighboring field (attachmenty type) and retrieve the corresponding type
$(this)
.closest("tr")
.children("td.field_3174")
.find("span")
.children("span")
.each(function (index2) {
if (index == index2) {
attachmentType = $(this).text();
}
});
// update link contents
// and add a line break to make it consistent with the box next to it (BH)
$(this).html(attachmentType + "<br>");
});
});
});
$(document).on("knack-view-render.view_2486", function (event, page) {
// now with minor changes, used for traffic count attachments field
// this one affects the table that those without editing priviledges see
// replace attachment filename with attachment type
// find each attachment cell
$("td.field_3176").each(function () {
// find each attachment link within the cell
$(this)
.find("a")
.each(function (index) {
var attachmentType = "";
// search the neighboring field (attachmenty type) and retrieve the corresponding type
$(this)
.closest("tr")
.children("td.field_3174")
.find("span")
.children("span")
.each(function (index2) {
if (index == index2) {
attachmentType = $(this).text();
}
});
// update link contents
// and add a line break to make it consistent with the box next to it (BH)
$(this).html(attachmentType + "<br>");
});
});
});
$(document).on("knack-view-render.view_2491", function (event, page) {
// Another copy of the find and replace attachment types script, this one for the manage requests
// page
$("td.field_3176").each(function () {
// find each attachment link within the cell
$(this)
.find("a")
.each(function (index) {
var attachmentType = "";
// search the neighboring field (attachmenty type) and retrieve the corresponding type
$(this)
.closest("tr")
.children("td.field_3174")
.find("span")
.children("span")
.each(function (index2) {
if (index == index2) {
attachmentType = $(this).text();
}
});
// update link contents
// and add a line break to make it consistent with the box next to it (BH)
$(this).html(attachmentType + "<br>");
});
});
});
$(document).on("knack-view-render.view_2465", function (event, page) {
// Another copy of the find and replace attachment types script. This one is used
// on the Request Status page under Traffic Counts.
$("td.field_3176").each(function () {
// find each attachment link within the cell
$(this)
.find("a")
.each(function (index) {
var attachmentType = "";
// search the neighboring field (attachmenty type) and retrieve the corresponding type
$(this)
.closest("tr")
.children("td.field_3174")
.find("span")
.children("span")
.each(function (index2) {
if (index == index2) {
attachmentType = $(this).text();
}
});
// update link contents
// and add a line break to make it consistent with the box next to it (BH)
$(this).html(attachmentType + "<br>");
});
});
});
//////////////////////////////////////////////////////////////
// set random password when adding an account. //
// the user will not use this pw. they login with ADFS //
//////////////////////////////////////////////////////////////
function generatePassword() {
const lower = "abcdefghijklmnopqrstuvwxyz";
const upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const numbers = "0123456789";
// Known allowable special characters. There may be more but `(` and `)` are not
const special = "!@#$%&*^";
// Ensure at least one of each type
const array = new Uint8Array(20);
crypto.getRandomValues(array);
let password = "";
password += lower[array[0] % lower.length];
password += upper[array[1] % upper.length];
password += numbers[array[2] % numbers.length];
password += special[array[3] % special.length];
// Fill remaining 16 characters from all sets
const allChars = lower + upper + numbers + special;
for (let i = 4; i < 20; i++) {
password += allChars[array[i] % allChars.length];
}
// Shuffle the password to avoid predictable positions
return password
.split("")
.sort(() => crypto.getRandomValues(new Uint8Array(1))[0] - 128)
.join("");
}
$(document).on("knack-view-render.view_1294", function (event, scene) {
// set a random password when creating a new account. the user will not
// use this pw. they login with ADFS
var pw = generatePassword();
$('input[name$="password"]').val(pw);
$('input[name$="password_confirmation"]').val(pw);
});
///// end set password //////
/////////////////////////////////////////////////////////////
//// Change field color of inventory request statuses ///////
/////////////////////////////////////////////////////////////
function changeFieldColor(fieldClass, color_map) {
var child_field = $(fieldClass).find(".kn-value");
var value = child_field.text();
if (color_map[value]) {
$(child_field).css({
"background-color": color_map[value].background_color,
color: color_map[value].color,
});
}
}
function insertIcon(fieldClass, icon_map) {
var child_field = $(fieldClass).find(".kn-value");
var value = child_field.text();
var elem = $(fieldClass).find(".kn-value").find("span")[0];
$(elem).before(
"<span> <i class='fa fa-" + icon_map[value].icon + "'></i> </span>"
);
}
var colorMapOne = {
"Needs to be issued": {
background_color: "#377eb8",
color: "#fff",
icon: "exclamation-circle",
},
"Review needed": {
background_color: "#f5901f",
color: "#fff",
icon: "exclamation-triangle",
},
"Needs AIMS entry": {
background_color: "#ff9b9c",
color: "#fff",
icon: "exclamation-triangle",
},
Completed: {
background_color: "",
color: "#adadad",
icon: "check-circle",
},
Cancelled: {
background_color: "#adadad",
color: "#000",
icon: "times-circle-o",
},
};
$(document).on("knack-scene-render.scene_1085", function () {
// inventory request details
changeFieldColor(".field_3556", colorMapOne);
insertIcon(".field_3556", colorMapOne);
});
////////////////////////////////////////////////////////////
////////// End field color setting ////////////////////
///////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
//// Begin Set Weighted Unit Cost ///////////////////////////
/////////////////////////////////////////////////////////////
$(document).on("knack-scene-render.scene_1171", function (event, page) {
function appendErrorMessage(msg) {
var errorDiv = $(
'<div id="' +
page.key +
'-fail" class="kn-message is-error"><span class="kn-message-body"><p><strong>' +
msg +
"</strong></p></span></div>"
);
errorDiv.insertBefore($(".kn-submit")[0]);
}
function dollarsToNum(val) {
// Attempts to parse a float from a dollar string. Returns a float or NaN.
if (typeof val === "number") {
// if val is a number, return it
return val;
} else if (!typeof val === "string") {
// not a number or string, set it to NaN and let validation catch it
return NaN;
}
// we use Number here (and elsewhere) instead of parseFloat, because we don't want to tolerate any
// unexpected text in the value we're parsing. e.g. parseFloat("23abcd12") would return `23`
return Number(val.replace("$", "").replaceAll(",", "").trim());
}
function getWeightedUnitCost(state) {
var weightedUnitCost =
(state.quantity.current * state.cost.current +
state.quantity.restock * state.cost.restock) /
(state.quantity.current + state.quantity.restock);
return Number(weightedUnitCost.toFixed(4));
}
function handleWeightedUnitCostChange(state) {
var isValid = state.isValid();
if (!isValid && !state.errorIsShowing) {
// show error banner
appendErrorMessage(
"Unable to submit. Please verify that all fields are populated correctly."
);
// hide submit button
$(".kn-button").hide();
state.errorIsShowing = true;
} else if (isValid) {
// remove error banner
$("#" + page.key + "-fail").remove();
// show submit button
$(".kn-button").show();
state.errorIsShowing = false;
} else {
// leave existing error banner up
return;
}
}
function areInputsValid() {
// ensure that the user-input values are valid. the restock unit cost, quantity
// and, as a safegaurd, the calculated weighted unit cost, must be non-zero numbers
var valsToTest = [
this.cost.updated,
this.quantity.restock,
this.cost.restock,
];
return valsToTest.every((val) => {
if (isNaN(val) || typeof val !== "number" || val === 0) {
return false;
} else {
return true;
}
});
return results;
}
var detailsView = "view_2865";
var fields = {
cost: {
current: "field_245",
previous: "field_3786",
restock: "field_3783",
updated: "field_245",
},
quantity: {
current: "field_3579",
previous: "field_3906",
restock: "field_3785",
},
};
var state = {
quantity: {
restock: null,
current: null,
},
cost: {
restock: null,
current: null,
updated: null,
},
isValid: areInputsValid,
errorIsShowing: false,
};
// clear out pre-existing values from these form fields. these fields are used to "translate"
// values to the related unit_cost_history records that are created by form rule on submission,
// there may be values in these fields from previous restocking
$("#" + fields.cost.restock).val("");
$("#" + fields.quantity.restock).val("");
$("#" + fields.cost.updated).val("");
// prevent editing of new unit cost field. this will be set programmatically
$("#" + fields.cost.updated).prop("disabled", true);
state.quantity.current = parseInt(
$(
$("#" + detailsView)
.find("div.kn-detail." + fields.quantity.current)
.find(".kn-detail-body span")[0]
)
.text()
.replaceAll(",", "")
.trim()
);
// handle situation where stock levels are negative (this should not but prob will happen)
state.quantity.current =
state.quantity.current > 0 ? state.quantity.current : 0;
state.cost.current = dollarsToNum(
$(
$("#" + detailsView)
.find("div.kn-detail." + fields.cost.current)
.find(".kn-detail-body span")[0]
).text()
);
/*
set the value of the preivous unit cost and quanity. these fields are hidden to the
user and we pass these values via submit rule that inserts them into a log record
*/
$("#" + fields.cost.previous)
.val(state.cost.current)
.prop("disabled", true);
$("#" + fields.quantity.previous)
.val(state.quantity.current)
.prop("disabled", true);
// we call handleWeightedUnitCostChange to initialize the error state and hide submit button
// until all fields are populated
handleWeightedUnitCostChange(state);
$("#" + fields.cost.restock).on("input", function () {
state.cost.restock = dollarsToNum($(this).val());
state.cost.updated = getWeightedUnitCost(state);
$("#" + fields.cost.updated).val(state.cost.updated);
handleWeightedUnitCostChange(state);
});
$("#" + fields.quantity.restock).on("input", function () {
state.quantity.restock = Number($(this).val());
state.cost.updated = getWeightedUnitCost(state);
$("#" + fields.cost.updated).val(state.cost.updated);
handleWeightedUnitCostChange(state);
});
});
///////////////////////////////////////////////////////////
//// End Set Weighted Unit Cost ///////////////////////////
///////////////////////////////////////////////////////////
// Add "Refresh" button to inventory requests table
$(document).on("knack-view-render.view_2698", function (event, page) {
var button = $(
"<span style='width: 2em'></span><button id='refresh-view_2698' style='border-radius: .35em !important' class='kn-button is-primary'><i class='fa fa-refresh'></i><span style='width: .5em'></span>Refresh</button>"
);
button.insertAfter(
$("#view_2698").find("form.table-keyword-search").find("a")[0]
);
$("#refresh-view_2698").click(function (e) {
e.preventdefault();
Knack.views["view_2698"].model.fetch();
});
});
//////////////////////////////////////////////////////
// Disable editing of task order on work orders ////
//////////////////////////////////////////////////////
/*
This logic ensures that a work order's task order cannot be edited if
any inventory transactions have been financially processed. This is
dependent on a view being added to the work order edit view which
displays the `SUM_JV_TRANSACTIONS_COMPLETED` field. This field
indicates if any financial transactions have been processed.
If financial txns have been processed, then the editable select field
will be replaced with a static span of text.
*/
function getDetailsFieldValue(fieldKey) {
var spans = $("div." + fieldKey).find(".kn-detail-body span");
if (!spans || spans.length === 0) {
return null;
}
var span = spans[0];
if (!span) {
return null;
}
return $(span).text();
}
function removeParentDetails(fieldKey) {
var details = $("." + fieldKey).closest(".kn-details");
if (details) {
details.remove();
}
}
function getConnectionFieldValue(fieldKey) {
return $($("#connection-picker-chosen-" + fieldKey)[0]).find("span")[0]
.textContent;
}
function conditionallyDisableTaskOrderEditing() {
var JV_STATUS_FIELD_KEY = "field_3871";
var TK_FIELD_KEY = "field_2634";
var taskOrderValue = null;
var jvStatus = getDetailsFieldValue(JV_STATUS_FIELD_KEY);
// always hide this details view, users don't need to see it
removeParentDetails(JV_STATUS_FIELD_KEY);
if (jvStatus && jvStatus > 0) {
// hide the the task order connection field
// attempt to get the current value of the task order connection field
// we're dealing with a race condition with the Chosen lib, which
// knack uses for async select inputs.
//
// side note: i did try to interface directly with jquery-chosen, which has
// a mechanism for disabling inputs, but i could not get it to work. i think
// it's a context issue
// https://stackoverflow.com/questions/17153417/disable-jquery-chosen-dropdown
var MAX_ATTEMPTS = 3;
var attempts = 0;
var loop = setInterval(function () {
// the connection field will have a value of "Select" until rendering is complete
// it may *actually* have a value of select (i.e., it's blank)
// or we may be waiting for the field to render
attempts++;
taskOrderValue = getConnectionFieldValue(TK_FIELD_KEY);
if (taskOrderValue != "Select") {
// append TK field value as text
$("#kn-input-" + TK_FIELD_KEY).append(
"<span>" + taskOrderValue + "</span>"
);
// hide TK connection input
// it's important that we hide—-not remove--this field, because removing
// could have weird side effects when the form is submitted
$("#kn-input-" + TK_FIELD_KEY)
.find(".control")
.addClass("hiddenFormField");
clearInterval(loop);
} else if (attempts === MAX_ATTEMPTS) {
// append TK field value as text
$("#kn-input-" + TK_FIELD_KEY).append("<span>(none)</span>");
// hide TK connection input
$("#kn-input-" + TK_FIELD_KEY)
.find(".control")
.addClass("hiddenFormField");
clearInterval(loop);
}
}, 1000);
}
}
$(document).on("knack-scene-render.scene_1130", function (event, scene) {
conditionallyDisableTaskOrderEditing();
});
$(document).on("knack-scene-render.scene_1048", function (event, scene) {
conditionallyDisableTaskOrderEditing();
});
$(document).on("knack-scene-render.scene_297", function (event, scene) {
conditionallyDisableTaskOrderEditing();
});
$(document).on("knack-scene-render.scene_634", function (event, scene) {
conditionallyDisableTaskOrderEditing();
});
////////////////////////////////////////////
////// End Disable Task Order Editing //////
////////////////////////////////////////////
////////////////////////////////////////////
/// Begin Technician Time Log Validation ///
////////////////////////////////////////////
function appendErrorMessage(viewKey, formDiv, msg) {
// remove existing error msg if present
var errorDiv = $(
'<div id="' +
viewKey +
'-fail" class="kn-message is-error"><span class="kn-message-body"><p><strong>' +
msg +
"</strong></p></span></div>"
);
errorDiv.insertBefore(formDiv);
setTimeout(function () {
$("#" + viewKey + "-fail").remove();
}, 6000);
}
function highlightErrorField(inputId) {
$(inputId).addClass("input-error");
$(inputId + "-time").addClass("input-error");
setTimeout(function () {
$(inputId).removeClass("input-error");
$(inputId + "-time").removeClass("input-error");
}, 6000);
}
function getDatetime(inputId) {
// Date-time field has two inputs, one for date, and one for time
var dt = $("#" + inputId).val();
if (!dt) return undefined;
var [hoursStr, minutesStr] = $("#" + inputId + "-time")
.val()
.split(":");
if (!(hoursStr && minutesStr)) {
// we'll do like knack does and handle an absent or un-parseable time as 0:00
hoursStr = "0";
minutesStr = "0";
}
var hours = parseInt(hoursStr);
var amPm = minutesStr.slice(-2).toLowerCase();
// extract 'am' or 'pm' if present
if (amPm !== "am" && amPm !== "pm") {
amPm = null;
} else {
// remove am/pm string from string so that we can parse it as an int
minutesStr = minutesStr.replace(amPm, "");
}
minutes = parseInt(minutesStr) || 0;
if (isNaN(hours) || isNaN(minutes)) {
return undefined;
}
// adjust hours for am/pm
if (amPm == "pm" && hours < 12) {
hours = hours + 12;
} else if (amPm == "am" && hours == 12) {
hours = 0;
}
return new Date(dt + " " + hours + ":" + minutes);
}
function formatErrorMessage(startField, endField) {
return `<u>${startField.name}</u> must be earlier than <u>${endField.name}</u><br/>`;
}
$(document).on("knack-view-render.view_1252", function (event, page) {
var viewKey = page.key;
// each date field must be ordred chronologically, earliest to latest
var dateFields = [
{ key: "field_2020", name: "Issue Recevied" }, // issue received
{ key: "field_1437", name: "Arrive at Worksite" }, // arrive on-site
{ key: "field_1438", name: "Leave Work Site" }, // leave site
{ key: "field_1425", name: "Return to Shop" }, // return to shop
];
$(`#${viewKey} .kn-button`).on("click", function () {
var passesValidation = true;
var formDiv = $(this).closest("div")[0];
var errorMsgs = "";
for (var i = 1; i < 4; i++) {
var startField = dateFields[i - 1];
var endField = dateFields[i];
var startDateTime = getDatetime(`${viewKey}-${startField.key}`);
var endDateTime = getDatetime(`${viewKey}-${endField.key}`);
if (startDateTime === undefined || endDateTime === undefined) {
// this only happens when a date or time field is blank
// in which case we do not validate start/end. Knack validations
// will step in if these fields are required
continue;
}
if (startDateTime > endDateTime) {
passesValidation = false;
// highlight errored fields with red border
highlightErrorField(`#${viewKey}-${startField.key}`);
highlightErrorField(`#${viewKey}-${endField.key}`);
errorMsgs = `${errorMsgs}${formatErrorMessage(startField, endField)}`;
}
}
if (!passesValidation) {
// show red error banner
appendErrorMessage(viewKey, formDiv, errorMsgs);
}
return passesValidation;
});
});
////////////////////////////////////////////
/// End Technician Time Log Validation ///
////////////////////////////////////////////
//// Update link text to cabinet details page from signal detals
$(document).on("knack-view-render.view_1261", function (event, page) {
// find cabinet ID field div
var el = $(".field_1789");
// find child <a>
var a = $(el).find("a");
// update text
$(a).addClass("kn-link kn-link-1 kn-link-page kn-button");
$(a).html(
"<span class='icon is-small'><i class='fa fa-list'></i></span><span>Cabinet details</span>"
);
});
///////////////////////////////////////////////////////////////
///// Prevent user from re-assigning their own assignment /////
// https://github.com/cityofaustin/atd-data-tech/issues/9053 //
///////////////////////////////////////////////////////////////
var technicianField = "field_1754";
var disableChosenSelect = function ($workingField, $workingFieldParent) {
var $workingFieldClone = $workingField.clone();
// Remove the working Chosen select
$workingField.remove();
// Append a non-working copy of the Chosen select to the field parent div
// Clone/append breaks the context of the Chosen library on the field, hacky but it works
$workingFieldParent.append($workingFieldClone);
// Find the a tag that gives us the hover highlighting and pointer change
var $aTag = $workingFieldClone.find("a.chzn-single");
// Override hover in/out CSS so select doesn't look interactive
$aTag.css("background-color", "#e5e5e5");
$aTag.hover(
function () {
$(this).css("border-color", "#dbdbdb");
$(this).css("cursor", "default");
},
function () {
$(this).css("border-color", "#dbdbdb");
$(this).css("cursor", "default");
}