-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathUnit1.pas
More file actions
1363 lines (1166 loc) · 40.3 KB
/
Unit1.pas
File metadata and controls
1363 lines (1166 loc) · 40.3 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
unit Unit1;
interface
uses
System.SysUtils,
System.Classes,
System.Math,
System.DateUtils,
JSDelphiSystem,
JS,
Web,
WEBLib.Graphics,
WEBLib.Controls,
WEBLib.Forms,
WEBLib.Dialogs,
WEBLib.WebCtrls,
WEBLib.WebTools,
WEBLib.StdCtrls,
XData.Web.Client,
XData.Web.Connection,
Vcl.StdCtrls,
Vcl.Controls, WEBLib.ExtCtrls;
type
TForm1 = class(TWebForm)
divMain: TWebHTMLDiv;
divFooter: TWebHTMLDiv;
divHeader: TWebHTMLDiv;
btnPrevious: TWebButton;
btnNext: TWebButton;
divTitle: TWebHTMLDiv;
divSubTitleHolder: TWebHTMLDiv;
btnAbout: TWebButton;
btnMessage: TWebButton;
divMiddle: TWebHTMLDiv;
divAbout: TWebHTMLDiv;
divFeedback: TWebHTMLDiv;
divFeedbackHeader: TWebHTMLDiv;
divFeedbackTitle: TWebHTMLDiv;
btnFeedbackAbout: TWebButton;
btnFeedbackFeedback: TWebButton;
divBottomFeedback: TWebHTMLDiv;
btnSubmitFeedback: TWebButton;
btnCancelFeedback: TWebButton;
divAboutHeader: TWebHTMLDiv;
divAboutTitle: TWebHTMLDiv;
btnAboutAbout: TWebButton;
btnAboutMessage: TWebButton;
divAboutFooter: TWebHTMLDiv;
btnAboutOK: TWebButton;
divAboutContent: TWebHTMLDiv;
ServerConn: TXDataWebConnection;
ClientConn: TXDataWebClient;
tmrRetry: TWebTimer;
divFeedbackHolder: TWebHTMLDiv;
divFeedbackForm: TWebHTMLDiv;
memoFeedback: TWebMemo;
tmrCountdown: TWebTimer;
labelAboutVersion: TWebLabel;
labelAboutRelease: TWebLabel;
divSubtitle: TWebHTMLDiv;
divSubtitleProgress: TWebHTMLDiv;
divBefore: TWebHTMLDiv;
divAfter: TWebHTMLDiv;
procedure WebFormResize(Sender: TObject);
procedure btnMessageClick(Sender: TObject);
[async] procedure btnSubmitFeedbackClick(Sender: TObject);
procedure btnCancelFeedbackClick(Sender: TObject);
procedure btnAboutClick(Sender: TObject);
procedure btnAboutOKClick(Sender: TObject);
[async] procedure WebFormCreate(Sender: TObject);
procedure LogActivity(Activity: String);
[async] procedure GetSurveyData;
procedure tmrRetryTimer(Sender: TObject);
procedure tmrCountdownTimer(Sender: TObject);
procedure btnPreviousClick(Sender: TObject);
procedure btnNextClick(Sender: TObject);
procedure DisplayQuestion;
procedure HandleInput;
function GetNextQuestion(CurrentIndex: Integer; Options: String): Integer;
function GetPreviousQuestion(CurrentIndex: Integer; Options: String): Integer;
function GetRandomQuestion(CurrentIndex: Integer; Options: String): Integer;
procedure UpdateProgress(Progress: Integer);
[async] procedure SaveResponses(QuestionID: String; QuestionName: String; ThisResponse: String);
private
{ Private declarations }
public
{ Public declarations }
AppVer: String;
AppRel: String;
AppRelH: String;
ActivityLog: TStringList;
CountdownTimer: String;
MainState : String;
SurveyState: String;
ServerName: String;
ClientID: String;
SurveyID: String;
SurveyName: String;
SurveyGroup: String;
SurveyLink: String;
SurveyQuestionCount: Integer;
SurveyData: TJSObject;
SurveyQuestions: TJSArray;
SurveyResponses: TJSObject;
SurveyStart: String;
SurveyFinish: String;
CurrentResponse: String;
LastTransmission: String;
CurrentQuestion: TJSObject;
CurrentQuestionID: String;
CurrentQuestionName: String;
CurrentQuestionType: Integer;
CurrentQuestionIndex: Integer;
NextQuestionIndex: Integer;
PreviousQuestionIndex: Integer;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.btnAboutClick(Sender: TObject);
begin
// Click About: Show About, Hide Main and Feedback
LogActivity('About Button Clicked');
divMain.ElementHandle.classList.add('HideTransition');
divMain.ElementHandle.classList.remove('ShowTransition');
divFeedback.ElementHandle.classList.add('HideTransition');
divFeedback.ElementHandle.classList.remove('ShowTransition');
divAbout.ElementHandle.classList.add('ShowTransition');
divAbout.ElementHandle.classList.remove('HideTransition');
end;
procedure TForm1.btnAboutOKClick(Sender: TObject);
begin
// Click About OK: Show Main, Hide About
LogActivity('About/OK Button Clicked');
divAbout.ElementHandle.classList.add('HideTransition');
divAbout.ElementHandle.classList.remove('ShowTransition');
divMain.ElementHandle.classList.add('ShowTransition');
divMain.ElementHandle.classList.remove('HideTransition');
// Show Activity Log in Console
// console.log(ActivityLog.Text);
end;
procedure TForm1.btnCancelFeedbackClick(Sender: TObject);
begin
// Click Feedback Cancel: Show Main, Hide Feedback
LogActivity('Feedback/Cancel Button Clicked');
divFeedback.ElementHandle.classList.add('HideTransition');
divFeedback.ElementHandle.classList.remove('ShowTransition');
divMain.ElementHandle.classList.add('ShowTransition');
divMain.ElementHandle.classList.remove('HideTransition');
// Reset Feedback text
MemoFeedback.Lines.Text := '';
end;
procedure TForm1.btnMessageClick(Sender: TObject);
begin
// Click Feedback: Show Feedback, Hide Main, About
LogActivity('Feedback Button Clicked');
divMain.ElementHandle.classList.add('HideTransition');
divMain.ElementHandle.classList.remove('ShowTransition');
divAbout.ElementHandle.classList.add('HideTransition');
divAbout.ElementHandle.classList.remove('ShowTransition');
divFeedback.ElementHandle.classList.add('ShowTransition');
divFeedback.ElementHandle.classList.remove('HideTransition');
end;
procedure TForm1.btnNextClick(Sender: TObject);
begin
// Next
// Our very first question!
if CurrentQuestionID = '' then
begin
// Let's calm things down a bit
btnNext.Caption := '<i class="fa-solid fa-circle-right fa-2x" style="font-size:42px; margin-top:-4px; margin-left:-8px;"></i>';
// Basics of a question
CurrentQuestionIndex := 0;
CurrentQuestion := TJSObject(SurveyQuestions[CurrentQuestionIndex]);
CurrentQuestionID := String(CurrentQuestion['question_id']);
CurrentQuestionName := String(CurrentQuestion['question_name']);
DisplayQuestion;
// Elements may have different triggers. We want to catch them all
// We'll deal with multiple firing for the same event later
asm
divMiddle.addEventListener('change', pas.Unit1.Form1.HandleInput);
divMiddle.addEventListener('input', pas.Unit1.Form1.HandleInput);
end;
end
else
begin
// First thing we'll want to do now is save the response to the question that
// was just answered, if any response was generated.
if CurrentResponse <> '' then
begin
SaveResponses(CurrentQuestionID, CurrentQuestionName, CurrentResponse);
end;
// We've already got a question and we've got to figure out where to go next.
// Presumably the question response has been satisfied or we'd not have gotten
// here due to the button being disabled
CurrentQuestionIndex := NextQuestionIndex;
CurrentQuestion := TJSObject(SurveyQuestions[CurrentQuestionIndex]);
CurrentQuestionID := String(CurrentQuestion['question_id']);
CurrentQuestionName := String(CurrentQuestion['question_name']);
DisplayQuestion;
end;
end;
procedure TForm1.btnPreviousClick(Sender: TObject);
begin
// TODO: Load up values from a previous response - might be non-trivial
CurrentQuestionIndex := PreviousQuestionIndex;
if CurrentQuestionIndex = -1 then
begin
asm
window.location.reload(true);
window.location.href=window.location.href;
end;
end
else
begin
CurrentQuestion := TJSObject(SurveyQuestions[CurrentQuestionIndex]);
CurrentQuestionID := String(CurrentQuestion['question_id']);
CurrentQuestionName := String(CurrentQuestion['question_name']);
DisplayQuestion;
end;
end;
procedure TForm1.btnSubmitFeedbackClick(Sender: TObject);
var
Response: TXDataClientResponse;
ClientConn: TXDataWebClient;
Blob: JSValue;
Data: JSValue;
Elapsed: TDateTime;
FeedbackID: String;
begin
Elapsed := Now;
FeedbackID := TGUID.NewGUID.ToString;
LogActivity('[ Feedback Submission Started ]');
btnSubmitFeedback.Caption := '<div style="font-size:16px;" class="ms-1 me-2">'+
'<i class="fa-solid '+
'fa-paper-plane '+
'fa-xl me-2 fa-beat-fade" '+
'style="--fa-beat-fade-opacity: 0.7; '+
'--fa-beat-fade-scale: 1.2; '+
'--fa-animation-duration: 2s;'+
'"></i> Send</div>';
try
if (ServerConn.Connected) then
begin
try
ClientConn := TXDataWebClient.Create(nil);
ClientConn.Connection := ServerConn;
Response := await(ClientConn.RawInvokeAsync('ISurveyClientService.Feedback',[
SurveyID,
ClientID,
'SC/'+Appver,
AppRel,
FeedbackID,
MemoFeedback.Lines.Text,
MainState+'/'+SurveyState+'/'+CurrentQuestionName,
ActivityLog.Text
]));
Blob := Response.Result;
Data := Blob;
asm
Data = await Blob.text();
end;
Form1.LogActivity(String(Data));
except on E: Exception do
begin
Form1.LogActivity('Feedback Error: ['+E.ClassName+'] '+E.Message);
console.log('Feedback Error: ['+E.ClassName+'] '+E.Message);
end;
end;
end;
finally
btnSubmitFeedback.Caption := '<div style="font-size:16px;" class="ms-1 me-2"><i class="fa-solid fa-paper-plane fa-xl me-2"></i>Send</div>';
end;
LogActivity('[ Feedback Submission Completed ] '+IntToStr(MillisecondsBetween(Now, Elapsed))+'ms');
// Click Feedback Submit: Show Main, Hide Feedback
LogActivity('Feedback/Submit Button Clicked');
divFeedback.ElementHandle.classList.add('HideTransition');
divFeedback.ElementHandle.classList.remove('ShowTransition');
divMain.ElementHandle.classList.add('ShowTransition');
divMain.ElementHandle.classList.remove('HideTransition');
// Reset Feedback text
MemoFeedback.Lines.Text := '';
end;
procedure TForm1.DisplayQuestion;
var
QTitle: String;
QFooter: String;
Question: String;
QType: Integer;
QOptions: String;
PrevButton: Boolean;
NextButton: Boolean;
QuestionReady: Boolean;
begin
// display whatever question we've got selected
PrevButton := False;
NextButton := False;
QuestionReady := False;
CurrentResponse := '';
// Here we're dealing with the different question types
// Loop is because some question types are redirects to other
// questions so we keep looping until we land on the final
// question that is to be displayed
while not(QuestionReady) do
begin
QTitle := SurveyName;
if String(CurrentQuestion['question_title']) <> ''
then QTitle := String(CurrentQuestion['question_title']);
QFooter := 'Question '+IntToStr(CurrentQuestionIndex + 1)+' of '+IntToStr(SurveyQuestionCount);
if String(CurrentQuestion['question_footer']) <> ''
then QFooter := String(CurrentQuestion['question_footer']);
Question := '';
if String(CurrentQuestion['question']) <> ''
then Question := String(CurrentQuestion['question']);
QType := 2;
if String(CurrentQuestion['question_type']) <> ''
then QType := Integer(CurrentQuestion['question_type']);
CurrentQuestionType := QType;
QOptions := '';
if String(CurrentQuestion['question_options']) <> ''
then QOptions := String(CurrentQuestion['question_options']);
// 0 => Undefined
// Don't do anything, just skip right past it
if (QType = 0) then
begin
NextQuestionIndex := CurrentQuestionIndex + 1;
btnNextClick(nil);
exit;
end
// 1 => Opening
else if (QType = 1) then
begin
QuestionReady := True;
PrevButton := True;
NextButton := True;
PreviousQuestionIndex := -1;
NextQuestionIndex := GetNextQuestion(CurrentQuestionIndex, QOptions);
asm
this.SurveyStart = luxon.DateTime.now().toISO();
end;
CurrentResponse := SurveyStart;
end
// 2 => Info
else if (QType = 2) then
begin
QuestionReady := True;
PrevButton := True;
NextButton := True;
PreviousQuestionIndex := GetPreviousQuestion(CurrentQuestionIndex, QOptions);
NextQuestionIndex := GetNextQuestion(CurrentQuestionIndex, QOptions);
end
// 3 => Closing
else if (QType = 3) then
begin
QuestionReady := True;
PrevButton := False;
NextButton := False;
CurrentQuestionIndex := SurveyQuestionCount;
asm
this.SurveyFinish = luxon.DateTime.now().toISO();
end;
CurrentResponse := SurveyFinish;
SaveResponses(CurrentQuestionID, CurrentQuestionName, CurrentResponse);
// Grand Finale Fireworks?
if (Pos('FIREWORKS', Uppercase(QOptions)) > 0) then
begin
divBefore.Visible := True;
divAfter.Visible := True;
Form1.ElementClassName := 'overflow-hidden Custom_Fireworks';
end;
end
// 4 => Disabled
else if (QType = 4) then
begin
NextQuestionIndex := CurrentQuestionIndex + 1;
btnNextClick(nil);
exit;
end
// 5 => Redirect
else if (QType = 5) then
begin
NextQuestionIndex := GetNextQuestion(CurrentQuestionIndex, QOptions);
btnNextClick(nil);
exit;
end
// 6 => Random
else if (QType = 6) then
begin
NextQuestionIndex := getRandomQuestion(CurrentQuestionIndex, QOptions);
btnNextClick(nil);
exit;
end
// 7 => Text Multi
else if (QType = 7) then
begin
QuestionReady := True;
PrevButton := True;
NextButton := True;
PreviousQuestionIndex := getPreviousQuestion(CurrentQuestionIndex, QOptions);
NextQuestionIndex := getNextQuestion(CurrentQuestionIndex, QOptions);
end
// 8 => Text Single
else if (QType = 8) then
begin
QuestionReady := True;
PrevButton := True;
NextButton := True;
PreviousQuestionIndex := getPreviousQuestion(CurrentQuestionIndex, QOptions);
NextQuestionIndex := getNextQuestion(CurrentQuestionIndex, QOptions);
end
// 9 => Pick One
else if (QType = 9) then
begin
QuestionReady := True;
PrevButton := True;
NextButton := False;
PreviousQuestionIndex := getPreviousQuestion(CurrentQuestionIndex, QOptions);
NextQuestionIndex := getNextQuestion(CurrentQuestionIndex, QOptions);
end
// 11 => Pick Many
else if (QType = 11) then
begin
QuestionReady := True;
PrevButton := True;
NextButton := True;
PreviousQuestionIndex := getPreviousQuestion(CurrentQuestionIndex, QOptions);
NextQuestionIndex := getNextQuestion(CurrentQuestionIndex, QOptions);
end
// Unexpected? Pretend it is info and hope we can move past it
else
begin
QuestionReady := True;
NextButton := True;
PreviousQuestionIndex := GetPreviousQuestion(CurrentQuestionIndex, QOptions);
NextQuestionIndex := GetNextQuestion(CurrentQuestionIndex, QOptions);
end;
end;
// If it isn't going to change anything then don't enable the buttons
// This can happen when completing a section where no return is permitted
if PreviousQuestionIndex = CurrentQuestionIndex
then PrevButton := False;
if NextQuestionIndex = CurrentQuestionIndex
then NextButton := False;
// Display Question
divTitle.HTML.Text := QTitle;
divMiddle.HTML.Text := Question;
divSubTitle.HTML.Text := QFooter;
// Activate Previous/Next buttons if necessary
btnPrevious.Enabled := PrevButton;
btnNext.Enabled := NextButton;
// Progress Bar
UpdateProgress(CurrentQuestionIndex + 1);
// At this point, the question is displayed and we're done.
// Nothing happens until either a prev/next button is clicked
// And whether those are even enabled may depend on having an
// input event fired. For example, a "Pick One" question will
// enable "next" once a selection has been made.
end;
function TForm1.GetNextQuestion(CurrentIndex: Integer; Options: String): Integer;
var
uOptions: String;
NextQ: String;
i: Integer;
begin
// Check options for anything that might indicate a redirect, otherwise
// it is just the next question in the array.
Result := CurrentIndex + 1;
uOptions := uppercase(Options);
if Pos('NEXT:', uOptions) > 0 then
begin
NextQ := Copy(uOptions, Pos('NEXT:', uOptions)+6, maxint);
if Pos(',', NextQ) > 0
then NextQ := Copy(NextQ, 1, Pos(',',NextQ) - 1);
if Pos('PREV:', NextQ) > 0
then NextQ := Copy(NextQ, 1, Pos('PREV:',NextQ) - 1);
NextQ := Trim(NextQ);
i := 0;
while i < SurveyQuestions.Length do
begin
if TJSObject(SurveyQuestions[i])['question_name'] <> nil then
begin
if Uppercase(String(TJSObject(SurveyQuestions[i])['question_name'])) = NextQ
then Result := i
end;
i := i + 1;
end;
end;
end;
function TForm1.GetPreviousQuestion(CurrentIndex: Integer; Options: String): Integer;
var
uOptions: String;
NextQ: String;
i: Integer;
begin
// Check options for anything that might indicate a redirect, otherwise
// it is just the next question in the array.
Result := CurrentIndex -1;
uOptions := uppercase(Options);
if Pos('PREV:', uOptions) > 0 then
begin
NextQ := Copy(uOptions, Pos('PREV:', uOptions)+6, maxint);
if Pos(',', NextQ) > 0
then NextQ := Copy(NextQ, 1, Pos(',',NextQ) - 1);
if Pos('NEXT:', NextQ) > 0
then NextQ := Copy(NextQ, 1, Pos('NEXT:',NextQ) - 1);
NextQ := Trim(NextQ);
i := 0;
while i < SurveyQuestions.Length do
begin
if TJSObject(SurveyQuestions[i])['question_name'] <> nil then
begin
if Uppercase(String(TJSObject(SurveyQuestions[i])['question_name'])) = NextQ
then Result := i
end;
i := i + 1;
end;
end;
end;
function TForm1.GetRandomQuestion(CurrentIndex: Integer; Options: String): Integer;
var
uOptions: String;
NextQ: String;
Choices: String;
Weights: String;
ChoicesList: TStringList;
WeightsList: TStringList;
i: Integer;
Weight: Double;
begin
// Note: this seems to be far more complicated than one would normally expect
// The idea though is to have a list of pages and a separate list of weights
// where the weights are like 0.5, 0.25, 0.25
// So we have to add up all the weights and then use the portion of the total
// to get the individual weights. This is to be able to handle as much bad
// input data as possible.
// Check options for anything that might indicate a redirect, otherwise
// it is just the next question in the array.
Result := CurrentIndex + 1;
uOptions := uppercase(Options);
// Figure out what our Choices are
if Pos('CHOICES:', uOptions) > 0 then
begin
Choices := Copy(uOptions, Pos('CHOICES:', uOptions)+9, maxint);
if Pos('WEIGHTS:', Choices) > 0
then Choices := Copy(Choices, 1, Pos('WEIGHTS:',Choices) - 1);
Choices := Trim(Choices);
end;
// Figure out what our Weights are
if Pos('WEIGHTS:', uOptions) > 0 then
begin
Weights := Copy(uOptions, Pos('WEIGHTS:', uOptions)+9, maxint);
if Pos('CHOICES:', Weights) > 0
then Weights := Copy(Weights, 1, Pos('CHOICES:',Weights) - 1);
Weights := Trim(Weights);
end;
// See if we can get list of questions
ChoicesList := TStringList.Create;
ChoicesList.StrictDelimiter := True;
ChoicesList.Delimiter := ',';
ChoicesList.DelimitedText := Choices;
if ChoicesList.Count = 0 then exit;
// get list of weights
WeightsList := TStringList.Create;
WeightsList.StrictDelimiter := True;
WeightsList.Delimiter := ',';
WeightsList.DelimitedText := Weights;
// If we don't have a matching list, create an even split
if WeightsList.Count <> ChoicesList.Count then
begin
WeightsList.Text := '';
for i := 0 to ChoicesList.Count -1 do
begin
WeightsList.Add(FloatToStr(1.0 / double(ChoicesList.Count)));
end;
end;
// Check that we've got numbers for them all
Weight := 0.0;
for i := 0 to WeightsList.Count -1 do
begin
if StrToFloatDef(Trim(WeightsList[i]), 0.0) = 0.0
then WeightsList[i] := FloatToStr(1.0 / double(WeightsList.Count));
Weight := Weight + StrToFloat(WeightsList[i]);
end;
// Alright. Got a list of q's and a list of w's and a TotalWeight
Weight := Weight * Random;
// Find out who our winner is
i := 0;
NextQ := '';
while NextQ = '' do
begin
if StrToFloat(WeightsList[i]) >= Weight
then NextQ := Trim(ChoicesList[i])
else Weight := Weight - StrToFloat(WeightsList[i]);
i := i + 1;
end;
// If we don't have a winner, give up
if NextQ = '' then exit;
// If we do hava a winner, we need to find it in the list of questions
i := 0;
while i < SurveyQuestions.Length do
begin
if TJSObject(SurveyQuestions[i])['question_name'] <> nil then
begin
if Uppercase(String(TJSObject(SurveyQuestions[i])['question_name'])) = NextQ
then Result := i
end;
i := i + 1;
end;
ChoicesList.Free;
WeightsList.Free;
end;
procedure TForm1.GetSurveyData;
var
Response: TXDataClientResponse;
Data: JSValue;
Blob: JSValue;
SurveyTime: String;
Countdown: String;
begin
// An indicator that something is going on. Likely happens to fast to
// ever be seen, but maybe for a really large survey download...
btnNext.Caption := '<i class="fa-solid fa-spinner fa-spin fa-2x" style="font-size:42px; margin-top:-4px; margin-left:-8px;"></i>';
// Development server or Production server?
if GetQueryParam('Development') <> '' then
begin
ServerName := 'http://localhost:2001/tms/xdata';
LogActivity('Development Mode Specified');
LogActivity('Connecting to '+ServerName);
end
else
begin
ServerName := 'https://carnival.500foods.com:10101/500Surveys';
LogActivity('Connecting to '+ServerName);
end;
// See if we've got a SurveyID as a parameter?
if GetQueryParam('SurveyID') = '' then
begin
LogActivity('No Survey Specified');
exit;
end
else
begin
SurveyID := GetQueryParam('SurveyID');
LogActivity('SurveyID: '+SurveyID);
LogActivity('ClientID: '+ClientID);
end;
// Try and establish a connection to the server
if not(ServerConn.Connected) then
begin
ServerConn.URL := ServerName;
try
await(ServerConn.OpenAsync);
except on E: Exception do
begin
LogActivity('Connnection Error: ['+E.ClassName+'] '+E.Message);
console.log('Connnection Error: ['+E.ClassName+'] '+E.Message);
tmrRetry.Enabled := True;
end;
end;
end;
// We've got a connection, let's make the request
if (ServerConn.Connected) then
begin
try
Response := await(ClientConn.RawInvokeAsync('ISurveyClientService.GetSurvey', [
SurveyID,
ClientID,
'SC/'+AppVer,
AppRel
]));
Blob := Response.Result;
Data := Blob;
asm
Data = await Blob.text();
end;
except on E: Exception do
begin
LogActivity('Survey Download Error: ['+E.ClassName+'] '+E.Message);
console.log('Survey Download Error: ['+E.ClassName+'] '+E.Message);
tmrRetry.Enabled := True;
end;
end;
end;
// Do we have any data?
if (Length(String(Data)) > 0) then
begin
// Yes we do!
SurveyData := TJSJSON.parseObject(String(Data));
// console.log(TJSJSON.stringify(SurveyData));
// Extract some basic information
SurveyID := String(SurveyData['SurveyID']);
SurveyName := String(SurveyData['SurveyName']);
SurveyGroup := String(SurveyData['SurveyGroup']);
SurveyLink := String(SurveyData['SurveyLink']);
// If we don't have a SurveyName, then we've got nothing.
if ((SurveyName = 'undefined') or (SurveyID = '')) then exit;
// Make a note of it
LogActivity('');
LogActivity('Survey Retrieved:');
LogActivity('- ID: '+SurveyID);
LogActivity('- Group: '+SurveyGroup);
LogActivity('- Name: '+SurveyName);
LogActivity('- Link: '+SurveyLink);
LogActivity('');
// Let's Update the UI.
// First, we can set the About and Feedback values.
divAboutTitle.HTML.Text := String(SurveyData['About-Title']);
divAboutContent.HTML.Text := '<div class="InnerContent">'+String(SurveyData['About-Content'])+'</div>';
divFeedbackTitle.HTML.Text := String(SurveyData['Feedback-Title']);
divFeedbackForm.HTML.Text := '<div class="FeedbackContent">'+String(SurveyData['Feedback-Content'])+'</div>';
// Then, we need to figure out the availability:
// - Pre: Availability is in future (countdown until survey starts)
// - Post: Availability is in the past (survey is done)
// - Pause: More than one availability and we're between them (survey is paused)
// - Active: Ready to go
// Default to active if no availability data is present
SurveyTime := 'Active';
if (SurveyData['Availability'] <> nil) then
begin
SurveyTime := '';
Countdown := '';
asm
var rows = JSON.parse(this.SurveyData['Availability']);
if (rows.length > 0) {
var now = luxon.DateTime.now();
var next = luxon.DateTime.now().plus({years: 100});
for (var i = 0; i < rows.length; i++) {
var start = luxon.DateTime.fromISO(rows[i]['opening']);
var finish = luxon.DateTime.fromISO(rows[i]['closing']);
if ((start < now) && (finish > now)) {
SurveyTime += 'Active ';
next = finish;
}
else if (start > now) {
SurveyTime += 'Pre ';
if (next > start) {
next = start;
}
}
else if (finish < now) {
SurveyTime += 'Post ';
next = finish;
}
}
Countdown = next.toISO();
if (SurveyTime == '') {
SurveyTime = 'Active';
}
else if (SurveyTime.indexOf('Active') > -1) {
SurveyTime = 'Active';
}
else if ((SurveyTime.indexOf('Pre') > -1) && (SurveyTime.indexOf('Post') == -1)) {
SurveyTime = 'Pre';
Countdown = next.toISO();
}
else if ((SurveyTime.indexOf('Post') > -1) && (SurveyTime.indexOf('Pre') == -1)) {
SurveyTime = 'Post';
}
else {
SurveyTime = 'Pause';
Countdown = next.toISO();
}
}
end;
if SurveyTime = '' then SurveyTime := 'Active';
end;
// Having done all that, now let's override it if we've been told to do so
if GetQueryParam('Status') <> '' then
begin
SurveyTime := GetQueryParam('Status');
end;
CountdownTimer := Countdown;
SurveyTime := Trim(Uppercase(SurveyTime));
if (SurveyTime = 'PRE') then
begin
LogActivity('Survey State: '+SurveyTime);
LogActivity('Countdown To: '+Countdown);
divTitle.HTML.Text := String(SurveyData['Banner-Pre-Title']);
divSubTitle.HTML.Text := String(SurveyData['Banner-Pre-Footer']);
divMiddle.HTML.Text := '<div class="InnerContent">'+String(SurveyData['Banner-Pre-Content'])+'</div>';
tmrCountdown.Enabled := True;
Exit;
end
else if (SurveyTime = 'PAUSE') then
begin
LogActivity('Survey State: '+SurveyTime);
LogActivity('Countdown To: '+Countdown);
divTitle.HTML.Text := String(SurveyData['Banner-Pause-Title']);
divSubTitle.HTML.Text := String(SurveyData['Banner-Pause-Footer']);
divMiddle.HTML.Text := '<div class="InnerContent">'+String(SurveyData['Banner-Pause-Content'])+'</div>';
tmrCountdown.Enabled := True;
Exit;
end
else if (SurveyTime = 'POST') then
begin
LogActivity('Survey State: '+SurveyTime);
divTitle.HTML.Text := String(SurveyData['Banner-Post-Title']);
divSubTitle.HTML.Text := String(SurveyData['Banner-Post-Footer']);
divMiddle.HTML.Text := '<div class="InnerContent">'+String(SurveyData['Banner-Post-Content'])+'</div>';
tmrCountdown.Enabled := False;
Exit;
end;
// Only choice left is that we're ACTIVE.
LogActivity('Survey State: '+SurveyTime);
divTitle.HTML.Text := String(SurveyData['Banner-Title']);
divSubTitle.HTML.Text := String(SurveyData['Banner-Footer']);
divMiddle.HTML.Text := '<div class="InnerContent">'+String(SurveyData['Banner-Content'])+'</div>';
tmrCountdown.Enabled := False;
// Go and get some questions
if (ServerConn.Connected) then
begin
try
Blob := nil;
Data := nil;
Response := await(ClientConn.RawInvokeAsync('ISurveyClientService.GetQuestions', [
SurveyID,
ClientID,
'SC/'+AppVer,
AppRel
]));
Blob := Response.Result;
Data := Blob;
asm
Data = await Blob.text();
end;
except on E: Exception do
begin
LogActivity('Survey Download Error: ['+E.ClassName+'] '+E.Message);
console.log ('Survey Download Error: ['+E.ClassName+'] '+E.Message);
end;
end;
end;
// Do we have any Questions?
if (Length(String(Data)) > 0) and (String(Data) <> 'null') then
begin
// Yes we do!
SurveyQuestions := TJSArray(TJSJSON.parseObject(String(Data)));
SurveyQuestionCount := 0;
if SurveyQuestions.length > 0 then
begin
SurveyQuestionCount := SurveyQuestions.Length;
SurveyState := 'Loaded';
LogActivity('Questions Returned: '+IntToStr(SurveyQuestions.Length));
end
else
begin
LogActivity('No Questions Returned');
end;
end
else
begin
LogActivity('No Questions Returned');
end;
end;
end;
procedure TForm1.HandleInput;
var