-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdmAutoBuildV2.pas
1290 lines (1182 loc) · 41.6 KB
/
dmAutoBuildV2.pas
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 dmAutoBuildV2;
interface
uses
System.SysUtils, System.Classes, FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf,
FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, FireDAC.Comp.Client,
Data.DB, FireDAC.Comp.DataSet, SCMDefines, dmSCM;
type
TAutoBuildV2 = class(TDataModule)
qryHeatsToDelete: TFDQuery;
qryNominees: TFDQuery;
qryRenumberHeats: TFDQuery;
qryGenderSwimmerCATCount: TFDQuery;
qryGenderCount: TFDQuery;
qrySwimmerCATCount: TFDQuery;
qryAgeCount: TFDQuery;
qryGenderAgeCount: TFDQuery;
qryGenericCount: TFDQuery;
qryHeatMaxSeedNumber: TFDQuery;
tbl_ABHeat: TFDTable;
tbl_ABEntrant: TFDTable;
qrySourceEvent: TFDQuery;
qryNomineeCountExt: TFDQuery;
qryNomineesExt: TFDQuery;
qryInsertEvent: TFDQuery;
qryUnplaced: TFDQuery;
procedure DataModuleCreate(Sender: TObject);
private
{ Private declarations }
prefHeatAlgorithm: integer;
prefGroupBy: integer;
prefRaceTimeTopPercent: double;
prefUseDefRaceTime: boolean;
prefExcludeOutsideLanes: boolean;
prefSeperateGender: boolean;
prefSeedMethod: seedMethod; // enum defined in SCMDefines
prefSeedDepth: integer;
// SEEDTIME IS USED TO INJECT DATA INTO THE ENTRANT TABLE
// use the preference dialog to enable and set options.
prefImportSeedTime: integer;
{ TODO -oBSA -cGeneral : Check order of params for calling procedures. }
function AssertConnection(): boolean;
procedure ReadPreferences(iniFileName: string);
// Auto build sub-routines
// SECTION A
function AssignHeats(EventID, numOfSwimmingLanes, GroupBy,
Unplaced: integer; SeperateGender: boolean): integer;
function AssignNomineesExt(DataSet: TFDQuery;
destEventID, MaxNumOfNominees: integer): integer;
function AssignLanes(DataSet: TFDQuery;
HeatID, numOfNomineesInHeat: integer): integer;
function AssignLane(DataSet: TFDQuery; HeatID, laneNumber: integer)
: boolean;
// seedDepth is base 1 - must remain in the index bounds of the DynamicArrays
// A bounds is check and adjusted.
function CircleSeed(DataSet: TFDQuery; seedDepth: integer): integer;
function AssignNominees(DataSet: TFDQuery; EventID: integer;
Age: integer = 0; GenderID: integer = 0;
SwimmerCategoryID: integer = 0): boolean;
// Autobuild startup functions
function GetNumOfSwimmingLanes(var NumOfPoolLanes: integer;
DoExcludeOutsideLanes: boolean): integer;
function GetHeatMaxSeedNumber(EventID: integer): integer;
// function CountNominees(EventID: integer): integer; //--
// function RenumberHeats(EventID: integer): integer; //--
// Autobuild support functions
// DEPRECIATED: 2023.02.21 - NOW SHARED CODE FOUND IN SCMUtility
// function ScatterLanes(index, NumOfPoolLanes: integer): integer;
function CreateNewEmptyHeat(EventID: integer): integer;
function SeedNominees(DataSet: TFDQuery; mySeedMethod: seedMethod;
mySeedDepth: integer = 3): integer;
procedure PrepDynamicArrays(EventID, numOfNominees, numberOfHeats: integer);
function CreateNewEvent(SourceEvent: TFDQuery;
TypeOfFinals: scmEventFinalsType): integer;
public
{ Public declarations }
// DEFAULT Auto build ... ENTRY POINT
// IMPORTANT NOTE:
// if TMain's instance of Heat DataSet isn't sent to Auto-Build
// ... unable to delete Heat record. (locked) !!!!!!!!!!!!
function AutoBuildExecute(DatasetHeat: TDataSet; EventID: integer;
Verbose: boolean = true): boolean;
// Auto build FINALS ... ENTRY POINT (also SEMI and QUARTER finals)
function AutoBuildExecuteExt(SourceEventID: integer;
TypeOfFinals: scmEventFinalsType = ftFinals): boolean;
end;
var
AutoBuildV2: TAutoBuildV2;
implementation
{%CLASSGROUP 'Vcl.Controls.TControl'}
uses SCMUtility, System.Math, vcl.Dialogs, System.Variants, dmSCMNom, IniFiles,
vcl.StdCtrls, System.UITypes, dmSCMHelper;
{$R *.dfm}
VAR
NomineesInHeat: Array of integer;
HeatIDs: Array of integer;
function TAutoBuildV2.AssertConnection: boolean;
begin
result := false;
if Assigned(SCM) then
if SCM.SCMActive then
result := true;
end;
function TAutoBuildV2.AssignHeats(EventID, numOfSwimmingLanes, GroupBy,
Unplaced: integer; SeperateGender: boolean): integer;
var
Success: boolean;
numberOfHeats, numOfNominees, totalNumberOfHeats: integer;
fAge, fGenderID, fSwimmerCategoryID: integer;
ds: TFDQuery;
Param: TFDParam;
begin
ds := nil;
totalNumberOfHeats := 0;
result := 0;
{ INFO: group on....
0-No (DEFAULT),
1-Entrant Age,
2-Entrant Swimming Category,
3-Division
}
{
function AssignAutoBuildQuery(SeperateGender: boolean; GroupBy: integer ): AQuery: TFDQuery;
Assign the query to run for AutoBuild.
Stack nominees on param:Gender (optional).
Then split stack on param:GroupBy
}
if (SeperateGender) then
begin
case (GroupBy) of
1: // GroupBy Gender. may produce a very large amount of heats!
ds := qryGenderAgeCount;
2:
// GroupBy Swimming Category
ds := qryGenderSwimmerCATCount;
3:
{ TODO -oBSA -cGeneral : Sperate gender and GroupBy Division }
;
else
// DON'T GROUP ... split stack on param:Gender
ds := qryGenderCount;
end;
end
// prefSeperateGender = false
// Group nominee without seperating genders
else
begin
case (GroupBy) of
1: // Gender
ds := qryAgeCount;
2: // Membership type.
ds := qrySwimmerCATCount;
{ TODO -oBSA -cGeneral : CASE 3: GroupBy Division }
else
// DON'T GROUP.
// A simple count of the nominees who are UNPLACED.
ds := qryGenericCount;
;
end;
end;
// was a dataset assigned?
if not Assigned(ds) then
begin
ds.Close;
qryNominees.Close;
exit;
end;
if Assigned(ds) then
begin
// prepare dataset with params ...
ds.Close;
ds.ParamByName('EVENTID').AsInteger := EventID;
// not all queries use param SESSIONSTART
Param := ds.FindParam('SESSIONSTART');
if Assigned(Param) then
begin
if (GroupBy = 1) then // Group by AGE
Param.AsDateTime := SCM.Session_Start
else
Param.Clear; // SESSIONSTART = <null>;
end;
ds.Prepare;
ds.Open;
// *******************************************************************
// iterate through the QUERY COUNT records
// building the DynamicArray items
// and creating heats and empty entrant records (wit empty Lanes)
// *******************************************************************
// BEGIN : AssignHeats MAIN LOOP
while not ds.Eof do
begin
numOfNominees := ds.FieldByName('countNominees').AsInteger;
{ TODO -oBSA -cGeneral : Unexpected error not handled
if (numOfNominees > Unplaced) then
}
// no nominees found - move to next event.
if (numOfNominees = 0) then
begin
ds.Next;
Continue;
end;
// Calculate the number of heats in each event.
if (numOfNominees > numOfSwimmingLanes) then
numberOfHeats :=
Ceil(double(numOfNominees) / double(numOfSwimmingLanes))
else
numberOfHeats := 1;
// TOT - accumulative number of heats
totalNumberOfHeats := totalNumberOfHeats + numberOfHeats;
// ***************************************************************
// Q R Y N O M I N E E S . . . .
// Prepare and make active the Nominees query
// A list of qualified nominees sorted fastest to slowest
// ***************************************************************
fAge := 0;
fGenderID := 0;
fSwimmerCategoryID := 0;
// FINALIZE DATA PARAM ASSIGNMENT
// Specific queries need specific data prior to calling AssignNominees.
if (SeperateGender) then
fGenderID := ds.FieldByName('GENDERID').AsInteger;
case (GroupBy) of
1: // Group on age.
fAge := ds.FieldByName('Age').AsInteger;
2: // Group on membership type.
fSwimmerCategoryID := ds.FieldByName('SwimmerCategoryID').AsInteger;
{ TODO -oBSA -cGeneral : CASE 3: GroupBy Division }
end;
// C A L L T O C O L L A T E E N T R A N T S
Success := AssignNominees(qryNominees, EventID, fAge, fGenderID,
fSwimmerCategoryID);
if not Success then
begin
// Hide all messages 11/12/22
// MessageDlg('ERR: SCM.AssignHeats(...) - Nominees list empty.',
// mtError, [mbOK], 0);
// SetLength(NomineesInHeat, 0);
// SetLength(HeatIDs, 0);
ds.Next;
Continue;
end;
// ***************************************************************
// CREATE DYNAMIC ARRAY DATA
// CREATE HEATS AND ENTRANT RECORDS.
// ***************************************************************
// NomineesInHeat - The number of nominees to place into each heat.
// HeatIDs - The IDs of the newly created heats
// s i z e . . . .
// SetLength(NomineesInHeat, numberOfHeats);
// SetLength(HeatIDs, numberOfHeats);
// ***************************************************************
PrepDynamicArrays(EventID, numOfNominees, numberOfHeats);
{
// DYNAMIC ARRAY CHECK ...
// 15/03/2022 - HIDE ALL WARNINGS - ERRORS
err := false;
j := 0;
for i in HeatIDs do
begin
if (HeatIDs[i] = 0) then err := true;
end;
for i in NomineesInHeat do
begin
j := j + NomineesInHeat[i];
end;
if (j <> numOfNominees) then
err := true;
if (err) then
// MessageDlg("CheckSum error in DynamicArray", mtWarning, TMsgDlgButtons() << mbOK, 0);
;
}
// ****************************************************************
// SEED THE NOMINEES
// ****************************************************************
SeedNominees(qryNominees, prefSeedMethod, prefSeedDepth);
// ****************************************************************
// FREE DYNAMIC ARRAY
// then rinse and repeat ....
// ****************************************************************
SetLength(NomineesInHeat, 0);
SetLength(HeatIDs, 0);
// ****************************************************************
// NEXT SET OF NOMINEES.
// ****************************************************************
ds.Next;
end; // AssignHeats MAIN LOOP
ds.Close;
qryNominees.Close;
end;
result := totalNumberOfHeats;
end;
function TAutoBuildV2.AssignLane(DataSet: TFDQuery;
HeatID, laneNumber: integer): boolean;
var
SearchOptions: TLocateOptions;
begin
result := false;
tbl_ABEntrant.Open;
if (laneNumber > 0) then
begin
SearchOptions := [];
result := tbl_ABEntrant.Locate('HeatID; Lane',
VarArrayOf([HeatID, laneNumber]), SearchOptions);
if (result) then
begin
tbl_ABEntrant.Edit;
tbl_ABEntrant.FieldByName('MemberID').AsInteger :=
DataSet.FieldByName('MemberID').AsInteger;
(*
NOTE:
The dataset is either qryNominees or qryNomineesExt.
The default is to send the TimeToBeat to field 'TTB'.
When a finals, semi and quarter is seeded then the TFDQuery dataset
re-directs the RACETIME time value to 'TTB' ...
*)
tbl_ABEntrant.FieldByName('TimeToBeat').AsDateTime :=
DataSet.FieldByName('TTB').AsDateTime;
tbl_ABEntrant.FieldByName('PersonalBest').AsDateTime :=
DataSet.FieldByName('PB').AsDateTime;
(*
INJECT the Nominee.SeedTime value into the designated Entrant field
To enable and set options use the prefence dialog.
The default : 0 = DISABLED.
*)
if prefImportSeedTime > 0 then
begin
case prefImportSeedTime of
1: // RaceTime
tbl_ABEntrant.FieldByName('RaceTime').AsDateTime :=
DataSet.FieldByName('SeedTime').AsDateTime;
end;
end;
end;
tbl_ABEntrant.Post;
end;
end;
function TAutoBuildV2.AssignLanes(DataSet: TFDQuery;
HeatID, numOfNomineesInHeat: integer): integer;
var
pass: boolean;
NumOfPoolLanes, laneNumber, i, entrantsAssigned: integer;
begin
entrantsAssigned := 0;
// The total number of pool lanes must be passed to scatter
// (ignore: preExcludeOutsideLanes)
NumOfPoolLanes := SCM.SwimClub_NumberOfLanes;
for i := 0 to numOfNomineesInHeat - 1 do
begin
if DataSet.Eof then
break;
// *******************************************
// For each nominee - assign a lane number.
// nominees are ordered fastest to slowest
// index i=0 results in lane number 4 when the pool lane count = 8
laneNumber := SCMUtility.ScatterLanes(i, NumOfPoolLanes);
if (laneNumber <> 0) then
begin
pass := AssignLane(DataSet, HeatID, laneNumber);
if (pass) then
begin
entrantsAssigned := entrantsAssigned + 1;
DataSet.Next;
end;
end;
end;
result := entrantsAssigned;
end;
// ***********************************************************************
// C O L L A T E E N T R A N T S . . . .
// ***********************************************************************
function TAutoBuildV2.AssignNominees(DataSet: TFDQuery;
EventID, Age, GenderID, SwimmerCategoryID: integer): boolean;
begin
{
BASED ON THE GIVEN EVENTID ...
Prepare a list of swimmer who have nominated for the
event - they will be sorted by TimeToBeat
(this excluding nominees in closed or raced heats)
Default assignment - age, GenderID, SwimmerCategoryID , DivisionID = 0
The MSSQL is written - such that CASE statements...
Values > zero enables filtering to INCLUDE SPECIFIC records.
}
DataSet.Close;
DataSet.ParamByName('AGE').AsInteger := Age;
DataSet.ParamByName('GENDERID').AsInteger := GenderID;
DataSet.ParamByName('SWIMMERCATEGORYID').AsInteger := SwimmerCategoryID;
{ TODO -oBSA -cGeneral : dataset.ParamByName('DIVISIONID').AsInteger := DivisionID }
DataSet.ParamByName('EVENTID').AsInteger := EventID;
// if you are injecting data - the session date will pre-date the DOB of
// most swimmers. So the SESSIONSTART should be set to Now()
if (prefImportSeedTime > 0) then
DataSet.ParamByName('SESSIONSTART').AsDateTime := Now
else
DataSet.ParamByName('SESSIONSTART').AsDateTime := SCM.Session_Start;
DataSet.ParamByName('ALGORITHM').AsInteger := prefHeatAlgorithm;
DataSet.ParamByName('CALCDEFAULT').AsInteger := integer(prefUseDefRaceTime);
DataSet.ParamByName('PERCENT').AsFloat := double(prefRaceTimeTopPercent);
DataSet.Prepare;
// ************************************************************
// PULL QUALIFIED NOMINEE LIST ORDERED BY FASTEST FIRST
// ************************************************************
DataSet.Open;
if (DataSet.Active) then
begin
if DataSet.IsEmpty then
DataSet.Close;
end;
result := DataSet.Active;
end;
function TAutoBuildV2.AssignNomineesExt(DataSet: TFDQuery;
destEventID, MaxNumOfNominees: integer): integer;
var
i: integer;
nom: TSCMNom;
begin
// NOMINATE the members from the destination event
// 'dataset' - a list of members and their RaceTimes ..
// from the sourceEvent - sorted by RaceTime ASCENDING.
DataSet.First;
nom := TSCMNom.CreateWithConnection(self, SCM.scmConnection);
// for the max number of racing lanes ...
for i := 0 to MaxNumOfNominees - 1 do
begin
if DataSet.Eof then
break;
nom.NominateMember(DataSet.FieldByName('MemberID').AsInteger, destEventID);
DataSet.Next;
end;
nom.Free;
result := i;
end;
function TAutoBuildV2.AutoBuildExecute(DatasetHeat: TDataSet; EventID: integer;
Verbose: boolean): boolean;
// ***********************************************************************
// A U T O B U I L D . . . ENTRY POINT
// SPECIAL NOTES:
// Prior to calling here ....
// ALL Heats (and associated Entrants) that are NOT CLOSED OR RACED
// have been REMOVED.
//
// ***********************************************************************
// IMPORTANT NOTE:
// TMain's instance of the Heat DataSet must be sent to AutoBuildExecute(...)
// Normally a call SCM.dsHeat.DataSet.Delete would be use but this
// doesn't work!... (tbl is locked?)
//
//
// EventID - CURRENT EVENT in SCM.dsEvent.DataSet
// dataHeat - ptr to SCM.dsHeat.DataSet
//
// Verbose
// USED BY BATCH Auto-Build Heats. DEFAULT := ON. Displays/Hides messages.
//
var
Unplaced, NumberOfPoolLanes, numOfSwimmingLanes, numberOfHeats: integer;
s: string;
begin
result := false;
Unplaced := 0;
if not AssertConnection then
begin
if (Verbose) then
MessageDlg('No database connection!' + sLineBreak +
'Auto-Build Heats will abort..', mtError, [mbOK], 0, mbOK);
exit;
end;
if (EventID = 0) then
begin
if (Verbose) then
MessageDlg('The event ID was invalid.' + sLineBreak +
'Auto-Build Heats will abort.', mtError, [mbOK], 0, mbOK);
exit;
end;
if (prefSeedMethod = smDualSeeding) then
begin
if (Verbose) then
MessageDlg('The event selected is an individual event.' + sLineBreak +
'Dual seeding can only be applied to teamed events (relays).' +
sLineBreak + 'Auto-Build Heats will abort.', mtError, [mbOK], 0, mbOK);
exit;
end;
if (prefSeedMethod = smMastersChampionSeeding) then
begin
if (Verbose) then
MessageDlg('Master Champion seeding is in development' + sLineBreak +
'and was made not available for this build.' + sLineBreak +
'Auto-Build Heats will abort.', mtError, [mbOK], 0, mbOK);
exit;
end;
// G R O U P B Y D I V I S I O N S . . .
if (prefGroupBy = 3) then
begin
if (Verbose) then
MessageDlg('GroupBy Divisions is in development' + sLineBreak +
'and was made not available for this build.' + sLineBreak +
'Auto-Build Heats will abort.', mtError, [mbOK], 0, mbOK);
exit;
end;
// TODO : Test/Locate SwimClubID ... for future multi-club DB.
numOfSwimmingLanes := GetNumOfSwimmingLanes(NumberOfPoolLanes,
prefExcludeOutsideLanes);
// There must be a least 2 lanes for the scatter algorithm.
if (numOfSwimmingLanes < 2) then
begin
if (Verbose) then
begin
s := '';
s := s + 'Your pool needs at least two swimming lanes' + sLineBreak +
'else the scatter algorithm cannot run.' + sLineBreak +
'Is the Club''s number of pool lanes correctly assigned?' + sLineBreak +
'Auto-Build Heats will abort.';
MessageDlg(s, mtError, [mbOK], 0, mbOK);
end;
exit;
end;
// FROM THIS POINT ...
// Auto-Build must return true as the grids need a refresh.
// *******************************************************
result := true;
// *******************************************************
// CLEAN UP HEATS - make readyfor auto build
if not DatasetHeat.IsEmpty then
begin
// EXCLUDE RACED OR CLOSED HEATS
SCM.Heat_DeleteAll(EventID, true); // also renumbers heats.
// RenumberHeats(EventID);
end;
{
With Heats CLEANED ....
Count the number of Nominees to be placed into lanes.
EXCLUDES pre-placed nominees in closed or raced heats
}
qryUnplaced.Close;
qryUnplaced.Params.ParamByName('EVENTID').AsInteger := EventID;
qryUnplaced.Prepare;
qryUnplaced.Open;
if (qryUnplaced.Active) then
begin
Unplaced := qryUnplaced.FieldByName('NomCount').AsInteger -
qryUnplaced.FieldByName('EntCount').AsInteger;
// FINISHED WITH QUERY
qryUnplaced.Close;
// Message disabled for BATCH AUTO-BUILD
if (Unplaced = 0) then
begin
if (Verbose) then
begin
s := 'Heats have been cleaned.' + sLineBreak;
s := s + 'After excluding entrants in closed and raced heats ...' +
sLineBreak + 'all outstanding nominees have been given a lane.' +
sLineBreak + 'Done - Auto-Build Heats will exit.';
MessageDlg(s, mtError, [mbOK], 0, mbOK);
end;
// All the nominees are placed - nothing more to do. OK.
exit;
end;
// Message disabled for BATCH AUTO-BUILD
// NOTE: if UnPlaced < 0 :: UNEXPECTED ERROR.
if (Unplaced < 0) then
begin
if (Verbose) then
begin
s := 'Heats have been cleaned.' + sLineBreak;
s := s + 'Unexpected error ...' + sLineBreak +
'There are more entrants (assigned a lane)' + sLineBreak +
'than club members who nominated for the event!' + sLineBreak +
'Auto-Build Heats will exit.';
MessageDlg(s, mtError, [mbOK], 0, mbOK);
end;
// Return true - need refresh of grids after cleaning heats.
exit;
end;
end;
// ***************************************************
// GOTO SECTION A. - HEAT ASSIGNMENT
numberOfHeats := AssignHeats(EventID, numOfSwimmingLanes, prefGroupBy,
Unplaced, prefSeperateGender);
// no heats were constructed!
// Message disabled for BATCH AUTO-BUILD
if (numberOfHeats = 0) then
begin
if (Verbose) then
MessageDlg('An error occurred while constructing heats.' + sLineBreak +
'The number of new heats built was nil!' + sLineBreak +
'Auto-Build Heats was aborted.', mtError, [mbOK], 0, mbOK);
// Return true - need refresh of grids after cleaning heats.
exit;
end;
end;
function TAutoBuildV2.AutoBuildExecuteExt(SourceEventID: integer;
TypeOfFinals: scmEventFinalsType): boolean;
var
NomineeCountExt, numOfSwimmingLanes, NumOfPoolLanes, MaxNumOfNominees,
numberOfHeats, numOfNominees, destEventID, mySeedDepth: integer;
begin
result := false;
NomineeCountExt := 0;
mySeedDepth := 2;
numOfSwimmingLanes := GetNumOfSwimmingLanes(NumOfPoolLanes,
prefExcludeOutsideLanes);
qryNomineeCountExt.Close;
qryNomineeCountExt.ParamByName('EVENTID').AsInteger := SourceEventID;
qryNomineeCountExt.Prepare;
qryNomineeCountExt.Open;
if (qryNomineeCountExt.Active) then
NomineeCountExt := qryNomineeCountExt.FieldByName('NomineeCountExt')
.AsInteger;
qryNomineeCountExt.Close;
case (TypeOfFinals) of
ftFinals:
if (NomineeCountExt < 2) then
begin
MessageDlg('A least two swimmers are needed to build a final.', mtError,
[mbOK], 0);
exit;
end;
ftSemi:
if (NomineeCountExt < 4) then
begin
MessageDlg('The selected event must have at least' + sLineBreak +
'four swimmers to build semi-finals.', mtError, [mbOK], 0);
exit;
end;
ftQuarter:
if (NomineeCountExt < 8) then
begin
MessageDlg('The selected event must have at least' + sLineBreak +
'eight swimmers to build quarter-finals.', mtError, [mbOK], 0);
exit;
end;
end;
SCM.dsEvent.DataSet.DisableControls();
qrySourceEvent.Close;
qrySourceEvent.ParamByName('EVENTID').AsInteger := SourceEventID;
qrySourceEvent.Prepare;
qrySourceEvent.Open;
if (qrySourceEvent.Active) then
begin
if (qrySourceEvent.IsEmpty) then
begin
qrySourceEvent.Close;
exit;
end;
case (TypeOfFinals) of
ftFinals:
begin
MaxNumOfNominees := numOfSwimmingLanes;
numberOfHeats := 1;
end;
ftSemi:
begin
MaxNumOfNominees := (numOfSwimmingLanes * 2);
numberOfHeats := 2;
end;
ftQuarter:
begin
MaxNumOfNominees := (numOfSwimmingLanes * 4);
numberOfHeats := 4;
end;
else
begin
MaxNumOfNominees := 0;
numberOfHeats := 0;
end;
end;
if (prefSeperateGender) then
begin
SCM.luGender.DataSet.First;
while not SCM.luGender.DataSet.Eof do
begin
// CREATE A NEW EVENT FOR EACH DATATYPE.
destEventID := CreateNewEvent(qrySourceEvent, TypeOfFinals);
// FILTER BY GENDER
qrySourceEvent.Filter := 'GenderID := ' +
SCM.luGender.DataSet.FieldByName('GenderID').AsString;
qrySourceEvent.Filtered := true;
// build the list of nominees for the FINAL TYPE ...
numOfNominees := AssignNomineesExt(qrySourceEvent, destEventID,
MaxNumOfNominees);
// Special arrays that manage the seeding
PrepDynamicArrays(destEventID, numOfNominees, numberOfHeats);
// prepare the destination query
qryNomineesExt.Close;
qryNomineesExt.ParamByName('SRCEVENTID').AsInteger := SourceEventID;
qryNomineesExt.ParamByName('DESTEVENTID').AsInteger := destEventID;
qryNomineesExt.ParamByName('SESSIONSTART').AsDateTime :=
SCM.Session_Start;
qryNomineesExt.ParamByName('GENDERID').AsInteger :=
SCM.luGender.DataSet.FieldByName('GenderID').AsInteger;
qryNomineesExt.Prepare;
qryNomineesExt.Open;
if (qryNomineesExt.Active) then
begin
// Seed nominees into FINAL TYPE
SeedNominees(qryNomineesExt, prefSeedMethod, mySeedDepth);
end;
SCM.luGender.DataSet.Next;
end;
end
else
begin
qrySourceEvent.Filter := '';
qrySourceEvent.Filtered := false;
destEventID := CreateNewEvent(qrySourceEvent, TypeOfFinals);
numOfNominees := AssignNomineesExt(qrySourceEvent, destEventID,
MaxNumOfNominees);
PrepDynamicArrays(destEventID, numOfNominees, numberOfHeats);
qryNomineesExt.Close;
// retrive memberID, genderID and RaceTime . TTB
qryNomineesExt.ParamByName('SRCEVENTID').AsInteger := SourceEventID;
// Nominees for the destination event have been fully populated
qryNomineesExt.ParamByName('DESTEVENTID').AsInteger := destEventID;
// for PersonalBest PB
qryNomineesExt.ParamByName('SESSIONSTART').AsDateTime :=
SCM.Session_Start;
// display all genders ....
qryNomineesExt.ParamByName('GENDERID').AsInteger := 0;
qryNomineesExt.Prepare;
qryNomineesExt.Open;
if (qryNomineesExt.Active) then
SeedNominees(qryNomineesExt, prefSeedMethod, mySeedDepth);
end;
end;
// ****************************************************************
// FREE DYNAMIC ARRAY
// ****************************************************************
SetLength(NomineesInHeat, 0);
SetLength(HeatIDs, 0);
SCM.dsEvent.DataSet.EnableControls;
result := true;
end;
function TAutoBuildV2.CircleSeed(DataSet: TFDQuery; seedDepth: integer)
: integer;
var
i, j, laneNumber, NumOfPoolLanes, entrantsAssigned, lowBounds: integer;
Success: boolean;
begin
// if depth is 3 and number of pool lanes is 8 then
// fastest three swimmers will use index = 1 and
// will be placed into lane 4.
// Second fastest swimmers will be index 2 and
// will be placed into lane 5.
entrantsAssigned := 0;
// ********************************
// seedDepth IS BASE 1 : Dynamic Arrays are base 0....
// ********************************
// The total number of pool lanes must be passed to scatter
// (the routine ignores preExcludeOutsideLanes)
NumOfPoolLanes := SCM.SwimClub_NumberOfLanes;
// seedDepth is BASE 1 - brackets needed!
lowBounds := (High(HeatIDs) - (seedDepth - 1)); // must have brackets!
if (lowBounds < Low(HeatIDs)) then
begin
lowBounds := Low(HeatIDs);
end;
// ITERATE over number of pool lanes
// get the next SET of fastest swimmers
for i := 0 to NumOfPoolLanes - 1 do
begin
// Reverse ITERATE over Heats - down to depth.
// Stacking the fastest heat to be the last to run.
for j := High(HeatIDs) downto lowBounds do
begin
if DataSet.Eof then
break;
// if lane count exceed the number of nominees in the heat
// move the current nominee into to next heat ...
if (i < NomineesInHeat[j]) then
begin
// swimmers index value is passed as base 0
laneNumber := SCMUtility.ScatterLanes(i, NumOfPoolLanes);
Success := AssignLane(DataSet, HeatIDs[j], laneNumber);
// next nominee
if (Success) then
begin
DataSet.Next;
entrantsAssigned := entrantsAssigned + 1;
end;
end;
end;
end;
result := entrantsAssigned;
end;
{
function TAutoBuildV2.CountNominees(EventID: integer): integer;
begin
result := 0;
if AssertConnection then
begin
qryGenericCount.Close;
qryGenericCount.ParamByName('EVENTID').AsInteger := EventID;
qryGenericCount.Prepare;
qryGenericCount.Open;
if not qryGenericCount.Active then
exit;
if not qryGenericCount.IsEmpty then
// return the number of nominees
result := qryGenericCount.FieldByName('countNominees').AsInteger;
qryGenericCount.Close;
end;
end;
}
function TAutoBuildV2.CreateNewEmptyHeat(EventID: integer): integer;
var
SearchOptions: TLocateOptions;
NextHeatNum, NumberOfLanes, iterLanes, HeatID: integer;
pass: boolean;
begin
result := 0;
SearchOptions := [];
// GET a lane count for ALL pool lanes. (ignore prefExcludeOutsideLanes)
NumberOfLanes := SCM.SwimClub_NumberOfLanes;
// find the next heat number **tblEvent.tbl_ABHeat.MAX(HeatNum)+1**
// if no heats in event or error ... returns 0
NextHeatNum := GetHeatMaxSeedNumber(EventID) + 1;
tbl_ABHeat.Open;
tbl_ABHeat.Append;
// Heat Number as calculated by GetMaxHeatNum()
tbl_ABHeat.FieldByName('HeatNum').AsInteger := NextHeatNum;
// Assign EventID ...
tbl_ABHeat.FieldByName('EventID').AsInteger := EventID;
// set to heat (or alt... quarter, semi, final)
tbl_ABHeat.FieldByName('HeatTypeID').AsInteger := 1;
// set to Open (or alt... raced, Closed)
tbl_ABHeat.FieldByName('HeatStatusID').AsInteger := 1;
tbl_ABHeat.Post;
// CREATE all the LANES (empty of entrants)
pass := tbl_ABHeat.Locate('HeatNum; EventID',
VarArrayOf([NextHeatNum, EventID]), SearchOptions);
if (pass) then
begin
tbl_ABEntrant.Open;
HeatID := tbl_ABHeat.FieldByName('HeatID').AsInteger;
for iterLanes := 0 to NumberOfLanes - 1 do
begin
tbl_ABEntrant.Append;
// Assign new created tbl_ABHeat.HeatID
tbl_ABEntrant.FieldByName('HeatID').AsInteger :=
tbl_ABHeat.FieldByName('HeatID').AsInteger;
// Assign lane number
tbl_ABEntrant.FieldByName('Lane').AsInteger := (iterLanes + 1);
// Assert bit initialisation BSA FIX 20240309
tbl_ABEntrant.FieldByName('IsDisqualified').AsBoolean:= false;
tbl_ABEntrant.FieldByName('IsScratched').AsBoolean:= false;
tbl_ABEntrant.Post;
end;
tbl_ABEntrant.Close;
result := HeatID;
end;
tbl_ABHeat.Close;
end;
function TAutoBuildV2.CreateNewEvent(SourceEvent: TFDQuery;
TypeOfFinals: scmEventFinalsType): integer;
var
s: string;
begin
case (TypeOfFinals) of
ftFinals:
s := 'FINALS (seed event# ';
ftSemi:
s := 'SEMI-FINALS (seed event# ';
ftQuarter:
s := 'QUATER-FINALS (seed event# ';
end;
s := s + SourceEvent.FieldByName('EventNum').AsString;
s := s + '): ';
s := s + SourceEvent.FieldByName('Caption').AsString;
qryInsertEvent.Close;
qryInsertEvent.ParamByName('CAPTION').AsString := s;
qryInsertEvent.ParamByName('DISTANCEID').AsInteger :=
SourceEvent.FieldByName('DistanceID').AsInteger;;
qryInsertEvent.ParamByName('STROKEID').AsInteger :=
SourceEvent.FieldByName('StrokeID').AsInteger;;
qryInsertEvent.ParamByName('SESSIONID').AsInteger := SCM.Session_ID();
qryInsertEvent.Prepare();
qryInsertEvent.Execute();
{ TODO -oBSA -cGeneral : Check new Scalar function. }
// How To Get Last Inserted ID On SQL Server for a specific table.
s := 'SELECT IDENT_CURRENT(''SwimClubMeet.dbo.Event'') AS LastID;';
// return EventID
result := SCM.scmConnection.ExecSQLScalar(s);
end;
procedure TAutoBuildV2.DataModuleCreate(Sender: TObject);
var
iniFileName: string;
begin
// Default preferences ...
prefExcludeOutsideLanes := false;
prefHeatAlgorithm := 1; // average of the 3 best racetimes
prefUseDefRaceTime := true;
prefRaceTimeTopPercent := 50.0;
prefSeperateGender := false;
prefGroupBy := 0;
prefSeedMethod := smSCMSeeding;
prefSeedDepth := 3; // Base 1
prefImportSeedTime := 0;
if not Assigned(SCM) then
raise Exception.Create('SCM data module not assigned.');
// As SCM is a TEMPORY connection - ASSERT assignment for FireDAC.
qrySwimmerCATCount.Connection := SCM.scmConnection;
qryGenderCount.Connection := SCM.scmConnection;
qryHeatsToDelete.Connection := SCM.scmConnection;
qryUnplaced.Connection := SCM.scmConnection;
qryRenumberHeats.Connection := SCM.scmConnection;
qryInsertEvent.Connection := SCM.scmConnection;
qryNomineesExt.Connection := SCM.scmConnection;
qryNomineeCountExt.Connection := SCM.scmConnection;
qrySourceEvent.Connection := SCM.scmConnection;
qryHeatMaxSeedNumber.Connection := SCM.scmConnection;