-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathwork_tracking_procedures.sql
More file actions
1482 lines (1112 loc) · 49.3 KB
/
work_tracking_procedures.sql
File metadata and controls
1482 lines (1112 loc) · 49.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
-- '''
-- Copyright 2022 DigitME2
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
-- http://www.apache.org/licenses/LICENSE-2.0
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-- '''
-- this file contains definitions for all events, functions, and procedures in the timelogger database
DELIMITER ;;
DROP EVENT IF EXISTS `autoClockOff`;;
CREATE DEFINER=`root`@`localhost` EVENT `autoClockOff` ON SCHEDULE EVERY 1 DAY STARTS '2018-08-13 23:59:00' ON COMPLETION PRESERVE ENABLE DO CALL clockOffAllUsers();;
DROP FUNCTION IF EXISTS `CalcOvertimeDuration`;;
CREATE DEFINER=`root`@`localhost` FUNCTION `CalcOvertimeDuration`(
JobStartTime TIME,
JobEndTime TIME,
RecordDate DATE
) RETURNS int(11)
MODIFIES SQL DATA
BEGIN
DECLARE startTimeSec INT DEFAULT 9999999;
DECLARE endTimeSec INT DEFAULT 9999999;
DECLARE startWorkDaySec INT DEFAULT 9999999;
DECLARE endWorkDaySec INT DEFAULT 9999999;
DECLARE calcualtedOvertime INT DEFAULT 9999999;
SET startTimeSec = TIME_TO_SEC(JobStartTime);
SET endTimeSec = TIME_TO_SEC(JobEndTime);
SELECT TIME_TO_SEC(workHours.startTime)
INTO startWorkDaySec
FROM workHours
WHERE DAYNAME(dayDate) = DAYNAME(RecordDate);
SELECT TIME_TO_SEC(workHours.endTime)
INTO endWorkDaySec
FROM workHours
WHERE DAYNAME(dayDate) = DAYNAME(RecordDate);
-- SELECT startTimeSec, endTimeSec, startWorkDaySec, endWorkDaySec;
-- If both the start and end times are within the normal workday,
-- overtime is zero
IF (startTimeSec BETWEEN startWorkDaySec AND endWorkDaySec) AND
(endTimeSec BETWEEN startWorkDaySec AND endWorkDaySec) THEN
SET calcualtedOvertime = 0;
-- If the start time is before the day start and the end time is
-- after the day end, return the total time minus the normal workday
-- duration
ELSEIF startTimeSec < startWorkDaySec
AND endTimeSec > endWorkDaySec THEN
SET calcualtedOvertime =
(endTimeSec - startTimeSec)
- (endWorkDaySec - startWorkDaySec);
-- if the times are both outside work hours (by this point both must
-- be at the start or the end of the day), return the difference
ELSEIF (startTimeSec NOT BETWEEN
startWorkDaySec AND endWorkDaySec)
AND (endTimeSec NOT BETWEEN
startWorkDaySec AND endWorkDaySec) THEN
SET calcualtedOvertime = endTimeSec - startTimeSec;
-- If the start is before the start of the normal day, return the
-- difference between the two
ELSEIF (startTimeSec < startWorkDaySec) THEN
SET calcualtedOvertime = startWorkDaySec - startTimeSec;
-- If the end is after the end of the normal day, return the
-- difference between the two
ELSEIF (endTimeSec > endWorkDaySec) THEN
SET calcualtedOvertime = endTimeSec - endWorkDaySec;
END IF;
RETURN calcualtedOvertime;
-- SELECT calcualtedOvertime;
END;;
DROP PROCEDURE IF EXISTS `CalcWorkedTimes`;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `CalcWorkedTimes`(
IN JobId VARCHAR(20),
IN LimitDateRange TINYINT(1),
IN StartDate DATE,
IN EndDate DATE,
OUT WorkedTimeSec INT,
OUT OvertimeSec INT
)
MODIFIES SQL DATA
BEGIN
-- Calculates the total worked time and total overtime, including currently open timelog records.
-- See method used in overview.sql
CREATE TEMPORARY TABLE openTimes (openDuration INT, openOvertimeDuration INT);
SET @query =
CONCAT("INSERT INTO openTimes (openDuration, openOvertimeDuration)
SELECT
TIME_TO_SEC(TIMEDIFF(CURRENT_TIME, clockOnTime)),
CalcOvertimeDuration(clockOnTime, CURRENT_TIME, CURRENT_DATE)
FROM timeLog WHERE clockOffTime IS NULL AND timeLog.jobId='",JobId,"' ");
IF LimitDateRange THEN
SET @query = CONCAT(@query, " AND timeLog.recordDate >= '", StartDate, "' AND timeLog.recordDate <= '", EndDate, "'");
END IF;
PREPARE stmt FROM @query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
-- dummy value so the table isn't empty
INSERT INTO openTimes VALUES (0,0);
IF LimitDateRange THEN
-- get the duration data from timelog of dates selected
SELECT
SUM(workedDuration),
SUM(overtimeDuration)
INTO
@totalWorkedTime,
@totalOvertime
FROM timeLog WHERE
(NOT (clockOffTime IS NULL))
AND timeLog.jobId = JobId
AND timeLog.recordDate >= StartDate
AND timeLog.recordDate <= EndDate;
ELSE
-- get the duration data pre-calculated in jobs table
SELECT
closedWorkedDuration,
closedOvertimeDuration
INTO
@totalWorkedTime,
@totalOvertime
FROM jobs WHERE jobs.jobId= JobId;
END IF;
IF @totalWorkedTime IS NULL THEN
SET @totalWorkedTime = 0;
END IF;
IF @totalOvertime IS NULL THEN
SET @totalOvertime = 0;
END IF;
SET @totalWorkedTime = @totalWorkedTime + (SELECT SUM(openDuration) FROM openTimes);
SET @totalOvertime = @totalOvertime + (SELECT SUM(openOvertimeDuration) FROM openTimes);
SELECT @totalWorkedTime, @totalOvertime INTO WorkedTimeSec, OvertimeSec;
END;;
DROP PROCEDURE IF EXISTS `CheckChangeOfRoute`;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `CheckChangeOfRoute`(IN `JobId` VARCHAR(20), IN `InputRouteName` VARCHAR(100))
MODIFIES SQL DATA
BEGIN
SELECT jobs.routeName into @ExistingRouteName FROM jobs WHERE jobs.jobId = JobId;
IF @ExistingRouteName != InputRouteName THEN
UPDATE timeLog SET routeCurrentStageIndex = -1 WHERE timeLog.jobId = JobId;
END IF;
END;;
DROP PROCEDURE IF EXISTS `ClockUser`;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ClockUser`(
IN JobId VARCHAR(20),
IN UserId VARCHAR(20),
IN StationId VARCHAR(50),
IN StationStatus VARCHAR(20)
)
MODIFIES SQL DATA
BEGIN
DECLARE inputComboOpenRecordRef INT DEFAULT -1;
DECLARE userOtherOpenRecordRef INT DEFAULT -1;
DECLARE newlyClosedRecordRef INT DEFAULT -1;
DECLARE newlyOpenRecordRef INT DEFAULT -1;
DECLARE newlyClosedDuration INT DEFAULT 0;
DECLARE newlyClosedOvertime INT DEFAULT 0;
DECLARE userIdValid INT DEFAULT 0;
DECLARE jobIDValid INT DEFAULT 0;
CREATE TEMPORARY TABLE routeStages (stageIndex INT PRIMARY KEY AUTO_INCREMENT, stageName VARCHAR(50));
START TRANSACTION;
SELECT timeLog.ref INTO inputComboOpenRecordRef FROM timeLog
WHERE timeLog.clockOffTime IS NULL
AND timeLog.userId=UserId
AND timeLog.jobId=JobId
AND timeLog.stationId=StationId
ORDER BY timeLog.recordTimestamp DESC LIMIT 1;
-- Check that user and job ID are present in relevant tables
SELECT COUNT(userId) INTO userIdValid FROM users WHERE users.userId=UserId LIMIT 1;
SELECT COUNT(jobId) INTO jobIDValid FROM jobs WHERE jobs.jobId=JobId LIMIT 1;
-- Confirm that both user and job ID are valid
IF userIdValid > 0 AND jobIDValid > 0 THEN
-- Create a new record
IF inputComboOpenRecordRef = -1 OR inputComboOpenRecordRef IS NULL THEN
-- An open record for another station or job may exist if the
-- user has not clocked off a previous job. This should be
-- closed before a new record is created. Only applies if
-- allowMultipleClockOn is set to false in config.
SELECT paramValue INTO @allowMultipleClockOn
FROM config WHERE paramName = "allowMultipleClockOn" LIMIT 1;
IF @allowMultipleClockOn = "false" THEN
SELECT ref INTO userOtherOpenRecordRef FROM timeLog
WHERE timeLog.userId=UserId AND timeLog.clockOffTime IS NULL
ORDER BY timeLog.recordTimestamp DESC LIMIT 1;
IF userOtherOpenRecordRef != -1 THEN
UPDATE timeLog SET clockOffTime = CURRENT_TIME, workStatus='unknown' WHERE ref = userOtherOpenRecordRef;
SET newlyClosedRecordRef = userOtherOpenRecordRef;
END IF;
END IF;
-- Create a new record in the time log and set the status of the job to "workInProgress".
-- The job status is assumed to be either pending, workInProgress, or complete.
INSERT INTO timeLog (jobId, stationId, userId, clockOnTime, recordDate, workStatus)
VALUES (JobId, StationId, UserId, CURRENT_TIME, CURRENT_DATE, 'workInProgress');
UPDATE jobs SET currentStatus='workInProgress' WHERE jobs.jobId=JobId;
SELECT timeLog.ref INTO newlyOpenRecordRef FROM timeLog
WHERE timeLog.clockOffTime IS NULL
AND timeLog.userId=UserId
AND timeLog.jobId=JobId
AND timeLog.stationId=StationId
ORDER BY timeLog.recordTimestamp DESC LIMIT 1;
SELECT "clockedOn" as result, newlyOpenRecordRef as logRef;
-- or close an open one
ELSE
SELECT ref INTO newlyClosedRecordRef FROM timeLog
WHERE timeLog.userId=UserId AND clockOffTime IS NULL AND timeLog.jobId=JobId
ORDER BY recordTimestamp DESC LIMIT 1;
UPDATE timeLog SET clockOffTime=CURRENT_TIME, workStatus=StationStatus WHERE ref = newlyClosedRecordRef;
SELECT "clockedOff" as result, newlyClosedRecordRef as logRef;
-- Get lunch config options
SELECT paramValue INTO @addLunchBreak
FROM config WHERE paramName = "addLunchBreak" LIMIT 1;
IF @addLunchBreak = "true" THEN
SELECT paramValue INTO @trimLunch
FROM config WHERE paramName = "trimLunch" LIMIT 1;
SELECT clockOffTime, clockOnTime INTO @jobClockOffTime, @jobClockOnTime FROM timeLog
WHERE ref = newlyClosedRecordRef;
CALL addLunch(newlyClosedRecordRef, @jobClockOnTime, @jobClockOffTime, CURRENT_DATE, @trimLunch);
END IF;
END IF;
-- Update the jobs table. This is most easily done here, as references to the
-- rows updated in this procedure are required.
IF newlyClosedRecordRef != -1 THEN
SELECT clockOnTime, clockOffTime INTO @clockOnTime, @clockOffTime
FROM timeLog
WHERE timeLog.ref=newlyClosedRecordRef;
-- find the newly closed total duration
SET newlyClosedDuration = TIME_TO_SEC(TIMEDIFF(@clockOffTime, @clockOnTime));
-- find the newly closed overtime duration
SET newlyClosedOvertime = CalcOvertimeDuration(@clockOnTime, @clockOffTime, CURRENT_DATE);
-- update records
UPDATE jobs
SET closedWorkedDuration = closedWorkedDuration + newlyClosedDuration,
closedOvertimeDuration = closedOvertimeDuration + newlyClosedOvertime
WHERE jobs.jobId=(SELECT timeLog.jobId FROM timeLog WHERE timeLog.ref=newlyClosedRecordRef LIMIT 1);
UPDATE timeLog
SET workedDuration = newlyClosedDuration,
overtimeDuration = newlyClosedOvertime
WHERE timeLog.ref=newlyClosedRecordRef;
END IF;
-- If the route name for this job is defined, create a list of station names from the comma-separated list
-- in the routes table, and then determine where in this list the current station is. If its position is
-- greater than the index of the current, update the index and route stage in the job record to reflect
-- this. Note that the stage of the route can only ever move forward here. If the station is not listed on
-- the route, it is simply ignored. This is assumed to be a mistake on the part of the end user, but isn't
-- something we can correct here.
SELECT routeName, routeCurrentStageIndex
INTO @routeName, @routeCurrentStageIndex
FROM jobs
WHERE jobs.jobId = JobId LIMIT 1;
IF @routeName IS NOT NULL AND @routeName != "" THEN
SELECT routeDescription INTO @routeDescription FROM routes WHERE routes.routeName = @routeName;
-- use a loop to parse the routeDescription, adding each stage name to the routeStages table
REPEAT
SELECT INSTR(@routeDescription,",") INTO @index;
IF @index != 0 THEN
INSERT INTO routeStages (stageName) SELECT SUBSTR(@routeDescription, 1, @index-1);
SELECT SUBSTR(@routeDescription, @index+1) INTO @routeDescription;
ELSE
INSERT INTO routeStages (stageName) VALUES (@routeDescription);
END IF;
UNTIL @index = 0
END REPEAT;
-- check if the station being clocked clocked on at is the current route stage or further in the route
SELECT stageIndex, stageName
INTO @stageIndex, @stageName
FROM routeStages
WHERE routeStages.stageIndex >= @routeCurrentStageIndex
AND routeStages.stageName = StationId
LIMIT 1;
SELECT @stageIndex, @stageName;
-- if station is current route stage or futher in route
IF @stageIndex IS NOT NULL THEN
-- get config option for if a stage complete is required for route progression
SELECT paramValue INTO @requireStageComplete
FROM config WHERE paramName = "requireStageComplete" LIMIT 1;
-- Set route stage index for work log record if new record
IF newlyOpenRecordRef != -1 THEN
UPDATE timeLog SET timeLog.routeStageIndex = @stageIndex WHERE timeLog.ref = newlyOpenRecordRef;
END IF;
IF @requireStageComplete = "false" OR (@routeCurrentStageIndex <= 1 AND @stageIndex = 1) THEN
-- update current route stage to station being clocked on at
UPDATE jobs
SET routeCurrentStageIndex = @stageIndex, routeCurrentStageName = StationId
WHERE jobs.jobId = JobId;
ELSE
-- get previous stage name
SELECT stageName INTO @prevStageName FROM routeStages
WHERE routeStages.stageIndex = @stageIndex - 1
LIMIT 1;
-- check if previous stage has a stage complete time log entry or is first stage
SELECT count(jobId)
INTO @prevComplete FROM timeLog
WHERE timeLog.jobId=JobId AND timeLog.stationId=@prevStageName AND timeLog.workStatus="stageComplete";
SELECT @prevComplete;
IF @prevComplete > 0 THEN
UPDATE jobs
SET routeCurrentStageIndex = @stageIndex, routeCurrentStageName = StationId
WHERE jobs.jobId = JobId;
END IF;
END IF;
--
SELECT MAX(stageIndex) INTO @maxStageIndex FROM routeStages;
-- if last current station last in route and stage complete pressed mark job as complete
IF @maxStageIndex = @stageIndex AND StationStatus = "stageComplete" AND newlyClosedRecordRef != -1 THEN
CALL MarkJobComplete(JobId);
UPDATE jobs
SET routeCurrentStageIndex = -1, routeCurrentStageName = Null
WHERE jobs.jobId = JobId;
END IF;
ELSE
-- if no possible change to current route stage index check if station included in route at at any point
SELECT 'HERE';
SELECT stageIndex
INTO @stageIndex
FROM routeStages
WHERE routeStages.stageName = StationId
ORDER BY stageIndex DESC
LIMIT 1;
select @stageIndex;
-- Set route stage index for work log record if new record
IF @stageIndex IS NOT NULL AND newlyOpenRecordRef != -1 THEN
UPDATE timeLog SET timeLog.routeStageIndex = @stageIndex WHERE timeLog.ref = newlyOpenRecordRef;
END IF;
END IF;
END IF;
ELSE
-- error message returned
SELECT "unknownId" as result;
END IF;
COMMIT;
END;;
DROP PROCEDURE IF EXISTS `CompleteStationRenaming`;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `CompleteStationRenaming`(
IN StationNewName VARCHAR(50)
)
MODIFIES SQL DATA
BEGIN
DELETE FROM connectedClients
WHERE connectedClients.stationId = (
SELECT currentName
FROM clientNames
WHERE newName = StationNewName
LIMIT 1
);
DELETE FROM clientNames WHERE newName = StationNewName;
INSERT INTO connectedClients (stationId, lastSeen) VALUES (StationNewName, CURRENT_TIMESTAMP);
END;;
DROP PROCEDURE IF EXISTS `GetCollapsedJobTimeLog`;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetCollapsedJobTimeLog`(
IN JobId VARCHAR(20),
IN LimitDateRange TINYINT(1),
IN StartDate DATE,
IN EndDate DATE
)
MODIFIES SQL DATA
BEGIN
SELECT numberOfUnits INTO @num_units FROM jobs WHERE jobs.jobId=JobId LIMIT 1;
-- create temporary tables to hold records for this
-- job, then find the collapsed form of the records.
CREATE TEMPORARY TABLE collapsedTimeRecords(stationId VARCHAR(50), recordStartDate DATE, recordEndDate DATE, workedDuration INT, overtimeDuration INT, workStatus VARCHAR(20), quantityComplete INT, outstanding INT, routeStageIndex INT(11));
IF LimitDateRange THEN
CREATE TEMPORARY TABLE timeRecords AS SELECT * FROM timeLog WHERE timeLog.jobId=JobId AND recordDate >= StartDate AND recordDate <= EndDate;
ELSE
CREATE TEMPORARY TABLE timeRecords AS SELECT * FROM timeLog WHERE timeLog.jobId=JobId;
END IF;
-- close off and update the local copy of any open records.
SET @query =
"UPDATE timeRecords
SET workedDuration = TIME_TO_SEC(TIMEDIFF(CURRENT_TIME, clockOnTime)),
overtimeDuration = CalcOvertimeDuration(clockOnTime, CURRENT_TIME, CURRENT_DATE)
WHERE clockOffTime IS NULL ";
PREPARE stmt FROM @query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
CREATE INDEX IDX_date_status ON timeRecords (recordDate, workStatus);
-- loop search condition
SET @remainingCount = 0;
SET @stationId = "";
SET @startDate = NULL;
SET @endDate = NULL;
CREATE TEMPORARY TABLE stations AS SELECT DISTINCT stationId, routeStageIndex FROM timeRecords;
SELECT COUNT(*) INTO @remainingCount FROM stations;
REPEAT
SET @stationId = '';
SET @startDate = NULL;
SET @endDate = NULL;
SELECT stationId, routeStageIndex INTO @stationId, @routeStageIndex FROM stations LIMIT 1;
-- Get the earliest remaining record in our copy of timeLog.
SELECT recordDate INTO @startDate
FROM timeRecords
WHERE stationId = @stationId AND routeStageIndex = @routeStageIndex
ORDER BY recordTimestamp ASC LIMIT 1;
-- Attempt to find the latest corresponding record, where the status is 'stageComplete'. May return null.
SELECT recordDate, workStatus
INTO @endDate, @workStatus
FROM timeRecords
WHERE stationId = @stationId AND routeStageIndex = @routeStageIndex
ORDER BY recordDate DESC LIMIT 1;
SELECT sum(quantityComplete) INTO @stationQuantityComplete
FROM timeRecords WHERE stationId=@stationId AND routeStageIndex = @routeStageIndex AND recordDate >= @startDate;
INSERT INTO collapsedTimeRecords(stationId, recordStartDate, recordEndDate, workedDuration, overtimeDuration, workStatus, quantityComplete, outstanding, routeStageIndex)
SELECT @stationId, @startDate, @endDate, SUM(workedDuration), SUM(overtimeDuration), @workStatus, @stationQuantityComplete, (@num_units - @stationQuantityComplete), @routeStageIndex
FROM timeRecords WHERE stationId=@stationId AND routeStageIndex = @routeStageIndex AND recordDate >= @startDate;
DELETE FROM stations WHERE stationId=@stationId AND routeStageIndex = @routeStageIndex;
SELECT COUNT(*) INTO @remainingCount FROM stations;
UNTIL @remainingCount = 0
END REPEAT;
SELECT
stationId,
recordStartDate,
recordEndDate,
workedDuration,
overtimeDuration,
workStatus,
quantityComplete,
outstanding,
routeStageIndex
FROM collapsedTimeRecords
ORDER BY recordStartDate DESC;
END;;
DROP PROCEDURE IF EXISTS `GetCollapsedJobTimeLog`;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetCollapsedJobTimeLog`(
IN JobId VARCHAR(20),
IN LimitDateRange TINYINT(1),
IN StartDate DATE,
IN EndDate DATE
)
MODIFIES SQL DATA
BEGIN
SELECT numberOfUnits INTO @num_units FROM jobs WHERE jobs.jobId=JobId LIMIT 1;
-- create temporary tables to hold records for this
-- job, then find the collapsed form of the records.
CREATE TEMPORARY TABLE collapsedTimeRecords(stationId VARCHAR(50), recordStartDate DATE, recordEndDate DATE, workedDuration INT, overtimeDuration INT, workStatus VARCHAR(20), quantityComplete INT, outstanding INT, routeStageIndex INT(11));
IF LimitDateRange THEN
CREATE TEMPORARY TABLE timeRecords AS SELECT * FROM timeLog WHERE timeLog.jobId=JobId AND recordDate >= StartDate AND recordDate <= EndDate;
ELSE
CREATE TEMPORARY TABLE timeRecords AS SELECT * FROM timeLog WHERE timeLog.jobId=JobId;
END IF;
-- close off and update the local copy of any open records.
SET @query =
"UPDATE timeRecords
SET workedDuration = TIME_TO_SEC(TIMEDIFF(CURRENT_TIME, clockOnTime)),
overtimeDuration = CalcOvertimeDuration(clockOnTime, CURRENT_TIME, CURRENT_DATE)
WHERE clockOffTime IS NULL ";
PREPARE stmt FROM @query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
CREATE INDEX IDX_date_status ON timeRecords (recordDate, workStatus);
-- loop search condition
SET @remainingCount = 0;
SET @stationId = "";
SET @startDate = NULL;
SET @endDate = NULL;
CREATE TEMPORARY TABLE stations AS SELECT DISTINCT stationId, routeStageIndex FROM timeRecords;
SELECT COUNT(*) INTO @remainingCount FROM stations;
REPEAT
SET @stationId = '';
SET @startDate = NULL;
SET @endDate = NULL;
SELECT stationId, routeStageIndex INTO @stationId, @routeStageIndex FROM stations LIMIT 1;
-- Get the earliest remaining record in our copy of timeLog.
SELECT recordDate INTO @startDate
FROM timeRecords
WHERE stationId = @stationId AND routeStageIndex = @routeStageIndex
ORDER BY recordTimestamp ASC LIMIT 1;
-- Attempt to find the latest corresponding record, where the status is 'stageComplete'. May return null.
SELECT recordDate, workStatus
INTO @endDate, @workStatus
FROM timeRecords
WHERE stationId = @stationId AND routeStageIndex = @routeStageIndex
ORDER BY recordDate DESC LIMIT 1;
SELECT sum(quantityComplete) INTO @stationQuantityComplete
FROM timeRecords WHERE stationId=@stationId AND routeStageIndex = @routeStageIndex AND recordDate >= @startDate;
INSERT INTO collapsedTimeRecords(stationId, recordStartDate, recordEndDate, workedDuration, overtimeDuration, workStatus, quantityComplete, outstanding, routeStageIndex)
SELECT @stationId, @startDate, @endDate, SUM(workedDuration), SUM(overtimeDuration), @workStatus, @stationQuantityComplete, (@num_units - @stationQuantityComplete), @routeStageIndex
FROM timeRecords WHERE stationId=@stationId AND routeStageIndex = @routeStageIndex AND recordDate >= @startDate;
DELETE FROM stations WHERE stationId=@stationId AND routeStageIndex = @routeStageIndex;
SELECT COUNT(*) INTO @remainingCount FROM stations;
UNTIL @remainingCount = 0
END REPEAT;
SELECT
stationId,
recordStartDate,
recordEndDate,
workedDuration,
overtimeDuration,
workStatus,
quantityComplete,
outstanding,
routeStageIndex
FROM collapsedTimeRecords
ORDER BY recordStartDate DESC;
END;;
DROP PROCEDURE IF EXISTS `GetJobRecord`;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetJobRecord`(IN `JobId` VARCHAR(20))
MODIFIES SQL DATA
BEGIN
-- get the total worked time and overtime from a procedure,
-- then reads the rest of the data directly from the table
CALL CalcWorkedTimes(JobId, 0, "", "", @totalWorkedTime, @totalOvertime);
SELECT routes.routeDescription INTO @routeDescription FROM routes WHERE routes.routeName = (SELECT jobs.routeName FROM jobs WHERE jobs.jobId = JobId) LIMIT 1;
SELECT
jobs.expectedDuration,
@totalWorkedTime,
@totalOvertime,
jobs.description,
jobs.currentStatus,
jobs.relativePathToQrCode,
jobs.recordAdded,
jobs.notes,
jobs.routeName,
jobs.routeCurrentStageName,
jobs.routeCurrentStageIndex,
@routeDescription,
jobs.priority,
jobs.dueDate,
jobs.stoppages,
jobs.numberOfUnits,
jobs.totalParts,
jobs.totalChargeToCustomer,
jobs.productId,
jobs.customerName
FROM jobs
WHERE jobs.jobId = JobId
LIMIT 1;
END;;
DROP PROCEDURE IF EXISTS `GetOverviewData`;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetOverviewData`(IN `UseSearchKey` TINYINT(1), IN `SearchKey` VARCHAR(200), IN `HideCompletedJobs` TINYINT(1), IN `LimitDateCreatedRange` TINYINT(1), IN `DateCreatedStart` DATE, IN `DateCreatedEnd` DATE, IN `LimitDateDueRange` TINYINT(1), IN `DateDueStart` DATE, IN `DateDueEnd` DATE, IN `ShowOnlyUrgentJobs` TINYINT(1), IN `ShowOnlyNonurgentJobs` TINYINT(1), IN `OrderByCreatedAsc` TINYINT(1), IN `OrderByCreatedDesc` TINYINT(1), IN `OrderByDueAsc` TINYINT(1), IN `OrderByDueDesc` TINYINT(1), IN `OrerByJobId` TINYINT(1), IN `OrderBypriority` TINYINT(1), IN `SubOrderByPriority` TINYINT(1))
BEGIN
CREATE TEMPORARY TABLE openTimes (jobId VARCHAR(20), openDuration INT, openOvertimeDuration INT);
CREATE TEMPORARY TABLE selectedJobIds (counter INT PRIMARY KEY AUTO_INCREMENT, jobId VARCHAR(20));
-- Construct a query to select the job IDs meeting the required selection criteria (completed or not, date range, etc)...
SET @selectionQuery = "INSERT INTO selectedJobIds (jobId) SELECT jobId FROM jobs ";
IF UseSearchKey THEN
SET @searchPattern = CONCAT("%", SearchKey, "%");
END IF;
SET @conditionPrecederTerm = " WHERE ";
-- ...appending the relevant selection options...
IF UseSearchKey IS TRUE THEN
SET @selectionQuery = CONCAT(@selectionQuery, " WHERE (description LIKE '", @searchPattern, "' OR jobId LIKE '", @searchPattern, "' OR customerName LIKE '", @searchPattern, "' or productId LIKE '", @searchPattern, "')");
-- this is set to " WHERE ", then changed to " AND " after the first condition is set.
SET @conditionPrecederTerm = " AND ";
END IF;
IF HideCompletedJobs IS TRUE THEN
SET @selectionQuery = CONCAT(@selectionQuery, @conditionPrecederTerm, "currentStatus != 'complete'");
SET @conditionPrecederTerm = " AND ";
END IF;
IF LimitDateCreatedRange IS TRUE THEN
SET @selectionQuery = CONCAT(@selectionQuery, @conditionPrecederTerm,
"DATE(recordAdded) >= '", DateCreatedStart, "' AND DATE(recordAdded) <= '", DateCreatedEnd, "' "
);
SET @conditionPrecederTerm = " AND ";
END IF;
IF LimitDateDueRange IS TRUE THEN
SET @selectionQuery = CONCAT(@selectionQuery, @conditionPrecederTerm,
"dueDate >= '", DateDueStart, "' AND dueDate <= '", DateDueEnd, "' "
);
SET @conditionPrecederTerm = " AND ";
END IF;
IF ShowOnlyUrgentJobs IS TRUE THEN
SET @selectionQuery = CONCAT(@selectionQuery, @conditionPrecederTerm,
"priority=4"
);
ELSEIF ShowOnlyNonurgentJobs IS TRUE THEN
SET @selectionQuery = CONCAT(@selectionQuery, @conditionPrecederTerm,
"priority<>4"
);
END IF;
-- test
-- SELECT @selectionQuery;
-- ... and run the query
PREPARE jobSelectionStmt FROM @selectionQuery;
EXECUTE jobSelectionStmt;
DEALLOCATE PREPARE jobSelectionStmt;
-- test
-- SELECT * FROM selectedJobIds;
-- Perform a few actions to produce a create a list of times for open records. This is required to get an accurate time
-- if a job is currently being worked on.
-- Get the relevant jobs
INSERT INTO openTimes(jobId, openDuration, openOvertimeDuration)
SELECT
timeLog.jobId,
TIME_TO_SEC(TIMEDIFF(CURRENT_TIME, clockOnTime)),
CalcOvertimeDuration(clockOnTime, CURRENT_TIME, CURRENT_DATE)
FROM timeLog
WHERE clockOffTime IS NULL AND timeLog.jobId IN (SELECT jobId FROM selectedJobIds);
-- test
-- SELECT * FROM openTimes;
-- Create dummy entries to simplify things a little later on. These are used to ensure that there
-- is at least one entry for each job.
INSERT INTO openTimes (jobId, openDuration, openOvertimeDuration)
SELECT jobId, 0, 0 FROM selectedJobIds;
CREATE INDEX idx_openTimes_jobIds ON openTimes(jobId);
-- test
-- SELECT * FROM openTimes;
-- Create and run the final query to select the data from the timeLog and combine
-- it with the calculated durations for jobs that are still open. Efficiency is
-- also calculated here, to minimise post processing required in PHP or JS.
-- Selects jobId, description, currentStatus, timestamp, current total worked
-- duration, of which current overtime worked, efficiency (total time / expected,
-- maximum of 1), expectedDuration
SET @finalSelectorQuery =
"SELECT\r\n jobs.jobId AS jobId,\r\n description,\r\n currentStatus,\r\n recordAdded,\r\n closedWorkedDuration + SUM(openDuration) AS totalWorkedDuration,\r\n closedOvertimeDuration + SUM(openOvertimeDuration) AS totalOvertimeDuration,\r\n LEAST((expectedDuration/(closedWorkedDuration + SUM(openDuration))),1) AS efficiency,\r\n expectedDuration,\r\n\trouteCurrentStageName,\r\n\tpriority,\r\n\tdueDate,\r\n\tstoppages,\r\n\tnumberOfUnits,\r\n\ttotalParts,\r\n\ttotalChargeToCustomer,\r\n\tproductId,\r\n\tcustomerName,\r\n\tnotes\r\n FROM jobs LEFT JOIN openTimes ON jobs.jobId = openTimes.jobId\r\n WHERE jobs.jobId IN (SELECT jobId FROM selectedJobIds ORDER BY counter ASC)\r\n GROUP BY jobs.jobId ";
-- ... and the ordering constraint...
IF OrderBycreatedAsc IS TRUE THEN
SET @finalSelectorQuery = CONCAT(@finalSelectorQuery, " ORDER BY recordAdded ASC ");
ELSEIF OrderByCreatedDesc IS TRUE THEN
SET @finalSelectorQuery = CONCAT(@finalSelectorQuery, " ORDER BY recordAdded DESC ");
ELSEIF OrderByDueAsc IS TRUE THEN
SET @finalSelectorQuery = CONCAT(@finalSelectorQuery, " ORDER BY dueDate ASC ");
ELSEIF OrderByDueDesc IS TRUE THEN
SET @finalSelectorQuery = CONCAT(@finalSelectorQuery, " ORDER BY dueDate DESC ");
ELSEIF OrerByJobId IS TRUE THEN
SET @finalSelectorQuery = CONCAT(@finalSelectorQuery, " ORDER BY jobs.jobId ASC ");
ELSEIF OrderBypriority IS TRUE THEN
SET @finalSelectorQuery = CONCAT(@finalSelectorQuery, " ORDER BY jobs.priority DESC ");
END IF;
IF SubOrderByPriority IS TRUE THEN
SET @finalSelectorQuery = CONCAT(@finalSelectorQuery, ", priority DESC ");
END IF;
PREPARE jobSelectionStmt FROM @finalSelectorQuery;
EXECUTE jobSelectionStmt;
DEALLOCATE PREPARE jobSelectionStmt;
DROP TABLE openTimes;
DROP TABLE selectedJobIds;
END;;
DROP PROCEDURE IF EXISTS `GetStoppagesLog`;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetStoppagesLog`(
IN JobId VARCHAR(20)
)
MODIFIES SQL DATA
BEGIN
CREATE TEMPORARY TABLE stoppagesLogData AS SELECT * FROM stoppagesLog WHERE stoppagesLog.jobId=JobId;
-- SET @now = CURRENT_TIME;
-- UPDATE timeLogData
-- SET workedDuration = TIME_TO_SEC(TIMEDIFF(@now, clockOnTime)),
-- overtimeDuration = CalcOvertimeDuration(clockOnTime, @now, recordDate)
-- WHERE workedDuration IS NULL;
-- control selection within date range
SELECT
ref,
jobId,
stationId,
stoppageReasonName,
description,
startTime,
endTime,
startDate,
endDate,
duration,
status
FROM stoppagesLogData
JOIN stoppageReasons ON stoppagesLogData.stoppageReasonId = stoppageReasons.stoppageReasonId
ORDER BY recordTimeStamp DESC;
END;;
DROP PROCEDURE IF EXISTS `GetTimesheet`;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetTimesheet`(
IN UserId VARCHAR(20),
IN StartDate DATE,
IN EndDate DATE
)
MODIFIES SQL DATA
BEGIN
-- Calculates the total worked time and total overtime, including currently open jobs.
-- See method used in overview.sql
-- DROP TABLE IF EXISTS jobDurations;
CREATE TEMPORARY TABLE jobDurations (recordDate DATE, jobId VARCHAR(20), duration INT, overtimeDuration INT);
-- test
-- SELECT * FROM jobDurations;
-- handle open records first
INSERT INTO jobDurations (recordDate, jobId, duration, overtimeDuration)
SELECT
recordDate,
timeLog.jobId,
TIME_TO_SEC(TIMEDIFF(CURRENT_TIME, clockOnTime)),
CalcOvertimeDuration(clockOnTime, CURRENT_TIME, CURRENT_DATE)
FROM timeLog WHERE clockOffTime IS NULL
AND timeLog.userId=UserId
AND recordDate >= StartDate
AND recordDate <= EndDate;
-- test
-- SELECT * FROM jobDurations;
-- Then the rest of the records
INSERT INTO jobDurations (recordDate, jobId, duration, overtimeDuration)
SELECT
recordDate,
timeLog.jobId,
TIME_TO_SEC(TIMEDIFF(clockOffTime, clockOnTime)),
CalcOvertimeDuration(clockOnTime, clockOffTime, recordDate)
FROM timeLog WHERE clockOffTime IS NOT NULL
AND timeLog.userId=UserId
AND recordDate >= StartDate
AND recordDate <= EndDate;
-- test
-- SELECT * FROM jobDurations;
CREATE INDEX IDX_durations_date_jobId ON jobDurations(recordDate, jobId);
SELECT paramValue INTO @allowMultipleClockOn
FROM config WHERE paramName = "allowMultipleClockOn" LIMIT 1;
-- Note that if multiple jobs may be clocked onto simultaneously by a
-- single user, then the total worked time and overtime is considered
-- to be undefined.
IF @allowMultipleClockOn = "true" THEN
SET @totalDuration = -1;
SET @totalOvertimeDuration = -1;
ELSE
SELECT SUM(duration) INTO @totalDuration FROM jobDurations;
SELECT SUM(overtimeDuration) INTO @totalOvertimeDuration FROM jobDurations;
END IF;
-- Create a list of unique IDs. This is returned as the first of two results sets.
SELECT DISTINCT jobId FROM jobDurations ORDER BY jobId ASC;
-- select the times from the table, ordered appropriately. This second result set is
-- processed into the rows and columns of a time sheet in the PHP code that called
-- this procedure.
SELECT recordDate, jobId, SUM(duration) AS workedDuration, SUM(overtimeDuration) AS overtimeDuration FROM jobDurations GROUP BY recordDate, jobId ORDER BY recordDate;
SELECT @totalDuration, @totalOvertimeDuration;
END;;
DROP PROCEDURE IF EXISTS `GetWorkedTimes`;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetWorkedTimes`(
IN JobId VARCHAR(20),
IN LimitDateRange TINYINT(1),
IN StartDate DATE,
IN EndDate DATE
)
MODIFIES SQL DATA
BEGIN
CALL CalcWorkedTimes(JobId, 0, "", "", @totalWorkedTime, @totalOvertime);
SELECT @totalWorkedTime, @totalOvertime;
END;;
DROP PROCEDURE IF EXISTS `MarkJobComplete`;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `MarkJobComplete`(
IN JobId VARCHAR(20)
)
MODIFIES SQL DATA
BEGIN
-- Get references to any open records, close them,
-- update the jobs table with the new times, then
-- sets the status of the job to complete.
CREATE TEMPORARY TABLE jobRefs(ref BIGINT);
INSERT INTO jobRefs(ref) SELECT ref FROM timeLog WHERE timeLog.jobId=JobId AND clockOffTime IS NULL;
UPDATE timeLog SET clockOffTime = CURRENT_TIME WHERE timeLog.ref IN (SELECT ref FROM jobRefs);
SELECT COUNT(ref) INTO @refCount FROM jobRefs;
IF @refCount > 0 THEN
UPDATE timeLog SET
workedDuration = TIME_TO_SEC(TIMEDIFF(clockOffTime, clockOnTime)),
overtimeDuration = CalcOvertimeDuration(clockOnTime, clockOffTime, recordDate),
workStatus = "stageComplete"
WHERE timeLog.ref in (SELECT ref FROM jobRefs);
UPDATE jobs SET
closedWorkedDuration = closedWorkedDuration + (SELECT SUM(workedDuration) FROM timeLog WHERE timeLog.ref IN (SELECT ref FROM jobRefs))
WHERE jobs.jobId=JobId;