-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathwork_tracking_db_setup.sql
1921 lines (1489 loc) · 67.9 KB
/
work_tracking_db_setup.sql
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.
-- '''
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `work_tracking`
--
DELIMITER $$
--
-- Procedures
--
CREATE DEFINER=`root`@`localhost` PROCEDURE `addLunch` (IN `workLogRef` INT(11), IN `jobClockOnTime` TIME, IN `jobClockOffTime` TIME, IN `RecordDate` DATE, IN `configTrimLunch` VARCHAR(100)) MODIFIES SQL DATA
BEGIN
DECLARE startLunch TIME;
DECLARE endLunch TIME;
SELECT lunchTimes.startTime
INTO startLunch
FROM lunchTimes
WHERE DAYNAME(dayDate) = DAYNAME(RecordDate);
SELECT lunchTimes.endTime
INTO endLunch
FROM lunchTimes
WHERE DAYNAME(dayDate) = DAYNAME(RecordDate);
IF jobClockOnTime < startLunch and endLunch < jobClockOffTime THEN
-- clock on period covers entire lunch
-- insert break
CALL insertBreak(workLogRef, startLunch, endLunch);
ELSEIF configTrimLunch = "true" THEN
IF startLunch < jobClockOnTime and jobClockOffTime < endLunch THEN
-- clock on and off within lunch period
-- set end time equal to start time
UPDATE timeLog
SET timeLog.clockOffTime = jobClockOnTime
WHERE ref = workLogRef;
-- Should clocking off or on be trimmed to lunch start or end if clocked off or on in lunch
ELSEIF jobClockOnTime < startLunch AND startLunch < jobClockOffTime AND jobClockOffTime < endLunch THEN
-- Clocked off in lunch, Set clock off time to start of lunch
UPDATE timeLog
SET timeLog.clockOffTime = startLunch
WHERE ref = workLogRef;
ELSEIF startLunch < jobClockOnTime AND jobClockOnTime < endLunch AND endLunch < jobClockOffTime THEN
-- Clocked on in lunch, Set clock on time to end of lunch
UPDATE timeLog
SET timeLog.clockOnTime = endLunch
WHERE ref = workLogRef;
END IF;
END IF;
END$$
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 stationId IS NOT NULL AND userId IS NOT NULL AND clockOnTime IS NOT NULL AND recordDate IS NOT 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
SUM(workedDuration),
SUM(overtimeDuration)
INTO
@totalWorkedTime,
@totalOvertime
FROM timeLog WHERE
(NOT (clockOffTime IS NULL))
AND timeLog.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$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `changeWorkLogRecord` (IN `workLogRef` VARCHAR(20), IN `station` VARCHAR(50), IN `userId` VARCHAR(20), IN `recordDate` DATE, IN `clockOnTime` TIME, IN `clockOffTime` TIME, IN `clockOffTimeValid` TINYINT(1), IN `workStatus` VARCHAR(20), IN `quantityComplete` INT(11)) MODIFIES SQL DATA
BEGIN
DECLARE newDuration INT DEFAULT 0;
DECLARE newOvertime INT DEFAULT 0;
DECLARE newClockOffTime TIME DEFAULT NULL;
IF clockOffTimeValid IS TRUE THEN -- this represents an open record.
-- find the new total duration
SET newDuration = TIME_TO_SEC(TIMEDIFF(clockOffTime, clockOnTime));
-- find the new overtime duration
SET newOvertime = CalcOvertimeDuration(clockOnTime, clockOffTime, recordDate);
SET newClockOffTime = clockOffTime;
END IF;
UPDATE timeLog
SET clockOnTime = clockOnTime,
clockOffTime = newClockOffTime,
workedDuration = newDuration,
overtimeDuration = newOvertime,
recordDate = recordDate,
userId = userId,
stationId = station,
workStatus = workStatus,
quantityComplete = quantityComplete
WHERE timeLog.ref=workLogRef;
SELECT "success" as result;
END$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `addWorkLogRecord` (IN `JobId` VARCHAR(20)) MODIFIES SQL DATA
BEGIN
INSERT INTO `timeLog` (`jobId`, `workStatus`) VALUES (JobId, 'workInProgress');
SELECT ref FROM timeLog WHERE jobId = JobId ORDER BY ref DESC LIMIT 1;
END$$
CREATE DEFINER=`root`@`localhost` PROCEDURE GetFullJobTimeLog(
IN JobId VARCHAR(20),
IN LimitDateRange TINYINT(1),
IN StartDate DATE,
IN EndDate DATE
)
MODIFIES SQL DATA
BEGIN
CREATE TEMPORARY TABLE timeLogData AS SELECT * FROM timeLog WHERE timeLog.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
IF LimitDateRange THEN
SELECT
ref,
stationId,
userName,
clockOnTime,
clockOffTime,
recordDate,
workedDuration AS workedTime,
overtimeDuration AS overtime,
workStatus,
quantityComplete
FROM timeLogData
JOIN users ON timeLogData.userId = users.userId
WHERE recordDate >= StartDate AND recordDate <= EndDate
ORDER BY recordTimeStamp DESC;
ELSE
SELECT
ref,
stationId,
userName,
clockOnTime,
clockOffTime,
recordDate,
workedDuration AS workedTime,
overtimeDuration AS overtime,
workStatus,
quantityComplete
FROM timeLogData
JOIN users ON timeLogData.userId = users.userId
ORDER BY recordTimeStamp DESC;
END IF;
END$$
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 routeStageIndex = -1 WHERE timeLog.jobId = JobId;
END IF;
END$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `clockOffAllUsers` () MODIFIES SQL DATA
BEGIN
-- The current time and date are unboxed ensure that all records are
-- processed using the correct timestamp, rather than risking a large
-- enough number being processed that it pushes the current date into
-- tomorrow and messes up the calculations
SELECT CURRENT_TIME, CURRENT_DATE INTO @currentTime, @currentDate;
CREATE TEMPORARY TABLE refs(ref INT PRIMARY KEY, jobId VARCHAR(20));
START TRANSACTION;
INSERT INTO refs(ref, jobId)
SELECT timeLog.ref, timeLog.jobId FROM timeLog
WHERE clockOffTime IS NULL;
SELECT endTime
INTO @dayEndTime
FROM workHours
WHERE DAYNAME(dayDate) = DAYNAME(@currentDate)
LIMIT 1;
UPDATE timeLog
SET clockOffTime = SEC_TO_TIME(
GREATEST(
TIME_TO_SEC(clockOnTime),
TIME_TO_SEC(@dayEndTime)
)
)
WHERE timeLog.ref IN (SELECT ref FROM refs);
UPDATE timeLog
SET workedDuration = TIME_TO_SEC(
TIMEDIFF(
clockOffTime,
clockOnTime
)
),
overtimeDuration = CalcOvertimeDuration(
clockOnTime,
clockOffTime,
@currentDate
),
workStatus = "unknown"
WHERE timeLog.ref IN (SELECT ref FROM refs);
-- update jobs table. Loop through the references recorded in the
-- temporary table. Definitely not the most efficient way, but I'm
-- getting a headache and this will work. Runs late at night, so
-- shouldn't get in the way of normal operations.
REPEAT
SELECT ref, jobId
INTO @ref, @jobId
FROM refs
ORDER BY ref LIMIT 1;
SELECT workedDuration, overtimeDuration
INTO @workedDuration, @overtimeDuration
FROM timeLog
WHERE timeLog.ref = @ref;
UPDATE jobs SET
jobs.closedWorkedDuration = jobs.closedWorkedDuration + @workedDuration,
jobs.closedOvertimeDuration = jobs.closedOvertimeDuration + @overtimeDuration
WHERE jobs.jobId = @jobId;
DELETE FROM refs WHERE refs.ref = @ref;
SELECT COUNT(*) INTO @countRemaining FROM refs;
UNTIL @countRemaining = 0
END REPEAT;
COMMIT;
END$$
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;
SELECT "" INTO @outputLogRef;
SELECT "" INTO @outputUserState;
SELECT "workInProgress" INTO @outputWorkState;
SELECT "" INTO @outputRouteName;
SELECT "" INTO @outputRouteStageIndex;
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", newlyOpenRecordRef into @outputUserState, @outputLogRef;
-- 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", newlyClosedRecordRef into @outputUserState, @outputLogRef;
-- 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;
IF StationStatus = "complete" THEN
CALL MarkJobComplete(JobId);
UPDATE timeLog
SET clockOffTime=CURRENT_TIME, workStatus=StationStatus
WHERE timeLog.ref = newlyClosedRecordRef;
SELECT "complete" INTO @outputWorkState;
END IF;
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;
SELECT -1 INTO @outputRouteStageIndex;
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";
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;
SELECT "complete" INTO @outputWorkState;
ELSEIF StationStatus = "complete" AND newlyClosedRecordRef != -1 THEN
CALL MarkJobComplete(JobId);
UPDATE jobs
SET routeCurrentStageIndex = -1, routeCurrentStageName = Null, currentStatus = StationStatus
WHERE jobs.jobId = JobId;
SELECT "complete" INTO @outputWorkState;
END IF;
SELECT @stageIndex INTO @outputRouteStageIndex;
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;
SELECT @stageIndex INTO @outputRouteStageIndex;
END IF;
END IF;
SELECT @routeName INTO @outputRouteName;
SELECT @outputUserState as "result", @outputLogRef as "logRef", @outputWorkState as "workState", @outputRouteName as "routeName", @outputRouteStageIndex as "routeStageIndex";
ELSE
-- error message returned
SELECT "unknownId" as result;
END IF;
COMMIT;
END$$
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$$
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;
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$$
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$$
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, "2000-01-01", "3000-01-01", @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,
jobs.jobName
FROM jobs
WHERE jobs.jobId = JobId
LIMIT 1;
END$$
CREATE PROCEDURE `GetOverviewData` (IN `UseSearchKey` TINYINT(1), IN `SearchKey` VARCHAR(200), IN `ShowPendingJobs` TINYINT(1), IN `ShowWorkInProgressJobs` TINYINT(1), IN `ShowCompletedJobs` TINYINT(1), IN `LimitDateCreatedRange` TINYINT(1), IN `DateCreatedStart` DATE, IN `DateCreatedEnd` DATE, IN `LimitDateDueRange` TINYINT(1), IN `DateDueStart` DATE, IN `DateDueEnd` DATE, IN `LimitDateTimeWorkedRange` TINYINT(1), IN `DateTimeWorkStart` DATE, IN `DateTimeWorkEnd` DATE, IN `ExcludeUnworkedJobs` TINYINT(1), 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 `OrderByJobId` TINYINT(1), IN `OrderBypriority` TINYINT(1), IN `SubOrderByPriority` TINYINT(1)) MODIFIES SQL DATA
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));
CREATE TEMPORARY TABLE closedRecords (jobId VARCHAR(20), closedDuration INT, closedOvertimeDuration INT, quantityComplete INT);
CREATE TEMPORARY TABLE totalDurations (jobId VARCHAR(20), totalWorkedDuration INT, totalOvertimeDuration INT);
CREATE TEMPORARY TABLE quantities(jobId VARCHAR(20), quantityComplete INT); -- 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 jobName 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 ShowPendingJobs IS TRUE AND ShowWorkInProgressJobs IS TRUE AND ShowCompletedJobs IS TRUE THEN
SET @selectionQuery = CONCAT(@selectionQuery, @conditionPrecederTerm, "(currentStatus = 'pending' OR currentStatus = 'workInProgress' OR currentStatus = 'complete')");
SET @conditionPrecederTerm = " AND ";
ELSEIF ShowPendingJobs IS TRUE AND ShowWorkInProgressJobs IS TRUE AND ShowCompletedJobs IS FALSE THEN
SET @selectionQuery = CONCAT(@selectionQuery, @conditionPrecederTerm, "(currentStatus = 'pending' OR currentStatus = 'workInProgress')");
SET @conditionPrecederTerm = " AND ";
ELSEIF ShowPendingJobs IS TRUE AND ShowWorkInProgressJobs IS FALSE AND ShowCompletedJobs IS TRUE THEN
SET @selectionQuery = CONCAT(@selectionQuery, @conditionPrecederTerm, "(currentStatus = 'pending' OR currentStatus = 'complete')");
SET @conditionPrecederTerm = " AND ";
ELSEIF ShowPendingJobs IS FALSE AND ShowWorkInProgressJobs IS TRUE AND ShowCompletedJobs IS TRUE THEN
SET @selectionQuery = CONCAT(@selectionQuery, @conditionPrecederTerm, "(currentStatus = 'workInProgress' OR currentStatus = 'complete')");
SET @conditionPrecederTerm = " AND ";
ELSEIF ShowPendingJobs IS TRUE AND ShowWorkInProgressJobs IS FALSE AND ShowCompletedJobs IS FALSE THEN
SET @selectionQuery = CONCAT(@selectionQuery, @conditionPrecederTerm, "(currentStatus = 'pending')");
SET @conditionPrecederTerm = " AND ";
ELSEIF ShowPendingJobs IS FALSE AND ShowWorkInProgressJobs IS FALSE AND ShowCompletedJobs IS TRUE THEN
SET @selectionQuery = CONCAT(@selectionQuery, @conditionPrecederTerm, "(currentStatus = 'complete')");
SET @conditionPrecederTerm = " AND ";
ELSEIF ShowPendingJobs IS FALSE AND ShowWorkInProgressJobs IS TRUE AND ShowCompletedJobs IS FALSE THEN
SET @selectionQuery = CONCAT(@selectionQuery, @conditionPrecederTerm, "(currentStatus = 'workInProgress')");
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;
-- SELECT LimitDateTimeWorkedRange;
-- 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
-- if display time in date range is false ...
IF LimitDateTimeWorkedRange IS FALSE THEN
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) AND (timeLog.stationId IS NOT NULL)
AND (timeLog.userId IS NOT NULL) AND (timeLog.clockOnTime IS NOT NULL) AND (timeLog.recordDate IS NOT NULL);
INSERT INTO closedRecords(jobId, closedDuration, closedOvertimeDuration, quantityComplete)
SELECT
timeLog.jobId,
timeLog.workedDuration,
timeLog.overtimeDuration,
timeLog.quantityComplete
FROM timeLog
WHERE clockOffTime IS NOT NULL AND timeLog.jobId IN (SELECT jobId FROM selectedJobIds);
-- timelog.quantitycomplete add to the above tble
-- remove the below
ELSEIF LimitDateTimeWorkedRange IS TRUE THEN
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) AND (timeLog.recordDate >= DateTimeWorkStart AND timeLog.recordDate <= DateTimeWorkEnd) AND (timeLog.stationId IS NOT NULL)
AND (timeLog.userId IS NOT NULL) AND (timeLog.clockOnTime IS NOT NULL) AND (timeLog.recordDate IS NOT NULL);
INSERT INTO closedRecords(jobId, closedDuration, closedOvertimeDuration, quantityComplete)
SELECT
timeLog.jobId,
timeLog.workedDuration,
timeLog.overtimeDuration,
timeLog.quantityComplete
FROM timeLog
WHERE clockOffTime IS NOT NULL AND timeLog.jobId IN (SELECT jobId FROM selectedJobIds) AND (timeLog.recordDate >= DateTimeWorkStart AND timeLog.recordDate <= DateTimeWorkEnd);
END IF;
-- ... else if true
-- same insert statements, plus AND tiemlog.recordDate >= startDate AND timelog.recordDAte <= endDate
--
-- test
-- SELECT * FROM openTimes;
-- SELECT * FROM closedRecords;
-- SELECT * FROM recordQuantityComplete;
-- -- SELECT ExcludeUnworkedJobs;
IF LimitDateTimeWorkedRange IS TRUE AND ExcludeUnworkedJobs IS TRUE THEN
DELETE FROM selectedJobIds
WHERE selectedJobIds.jobId NOT IN (SELECT jobId FROM openTimes)
AND selectedJobIds.jobId NOT IN (SELECT jobId FROM closedRecords);
END IF;
-- SELECT * FROM selectedJobIds;
-- 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);
INSERT INTO closedRecords (jobId, closedDuration, closedOvertimeDuration, quantityComplete)
SELECT jobId, 0, 0, 0 FROM selectedJobIds;
CREATE INDEX idx_closedRecords_jobIds ON closedRecords(jobId);
-- SELECT * FROM openTimes;
-- SELECT * FROM closedRecords;
-- ...appending the relevant selection options...
IF UseSearchKey IS TRUE THEN
SET @selectionQuery = CONCAT(@selectionQuery, " WHERE (description LIKE '", @searchPattern, "' OR jobName 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;
INSERT INTO totalDurations (jobId, totalWorkedDuration, totalOvertimeDuration) SELECT jobId, SUM(openDuration), SUM(openOvertimeDuration) FROM openTimes GROUP BY jobId;
INSERT INTO totalDurations (jobId, totalWorkedDuration, totalOvertimeDuration) SELECT jobId, SUM(closedDuration), SUM(closedOvertimeDuration) FROM closedRecords GROUP BY jobId;
-- SELECT * FROM totalDurations;
-- SELECT jobs.jobId, SUM(totalDurations.totalWorkedDuration) FROM jobs LEFT JOIN totalDurations on jobs.jobId = totalDurations.jobId;
INSERT INTO quantities(jobId, quantityComplete) SELECT jobId, SUM(quantityComplete) FROM closedRecords GROUP BY jobId;
-- SELECT "Inserted into quantities";
-- SELECT * FROM quantities;
-- 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.
SET @finalSelectorQuery =
"SELECT
jobs.jobId AS jobId,
jobs.jobName AS jobName,
description,
currentStatus,
recordAdded,
SUM(totalDurations.totalWorkedDuration) AS totalWorkedDuration,
SUM(totalDurations.totalOvertimeDuration) AS totalOvertimeDuration,
SUM(quantities.quantityComplete) AS quantityComplete,
LEAST((expectedDuration/(SUM(totalDurations.totalWorkedDuration))),1) AS efficiency,
expectedDuration,
routeCurrentStageName,
priority,
dueDate,
stoppages,
numberOfUnits,
totalParts,
totalChargeToCustomer,