All files / src/app/components/timetrack/work-time work-time.component.ts

76.59% Statements 72/94
52.77% Branches 19/36
81.25% Functions 13/16
76.34% Lines 71/93

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 2033x 3x 3x 3x 3x 3x 3x 3x 3x   3x   3x 3x 3x                                   3x             7x       7x 7x         7x 7x 7x 7x 7x   7x 7x 7x                   4x     1x       1x 1x 1x 1x   1x 1x 1x 1x           4x 1x         1x   1x             1x 1x                                                               2x       2x   1x   1x     2x   2x             2x 1x 1x   1x   1x 1x 1x           2x 2x 2x   2x 2x 2x 1x 1x 1x   2x     2x 2x 2x 2x       1x             1x 1x      
import { CommonModule } from "@angular/common";
import { ChangeDetectorRef, Component, EventEmitter, Input, OnChanges, OnInit, Output } from "@angular/core";
import { FormBuilder, FormGroup, FormsModule, ReactiveFormsModule, Validators } from "@angular/forms";
import { TranslateModule, TranslateService } from "@ngx-translate/core";
import { TimeInputComponent } from "@shared/components/time-input/time-input.component";
import { getCurrentTime } from "@shared/helper/utils";
import { positiveNumberValidator } from "@shared/validators/number.validator";
import { ToastrService } from "ngx-toastr";
import { debounceTime, distinctUntilChanged, map, Observable, tap } from "rxjs";
import { DateI } from "../date";
import { WorkTimeService } from "../services/work-time.service";
import { UserInfo } from "../user-info/user-info";
import { BreakTrackerComponent } from "./break-tracker/break-tracker.component";
import { validateBreaks } from "./break-tracker/break.validator";
import { TimeOverviewComponent } from "./time-overview/time-overview.component";
import { WorkBreak, WorkTime } from "./work-time";
 
@Component({
    selector: "app-work-time",
    standalone: true,
    imports: [
        FormsModule,
        ReactiveFormsModule,
        CommonModule,
        TimeInputComponent,
        TimeOverviewComponent,
        BreakTrackerComponent,
        TranslateModule,
    ],
    templateUrl: "./work-time.component.html",
})
 
export class WorkTimeComponent implements OnInit, OnChanges {
    @Input() date: DateI | undefined;
 
    @Input() userInfo!: UserInfo;
 
    @Input() workTime: WorkTime | undefined;
 
    @Output() readonly saved = new EventEmitter<void>();
 
    dayForm!: FormGroup;
 
    workMinutes = 0;
    breakMinutes = 0;
 
    workTypes$?: Observable<string[][]>;
 
    constructor (
        private readonly cdr: ChangeDetectorRef,
        private readonly translate: TranslateService,
        private readonly fb: FormBuilder,
        private readonly toaster: ToastrService,
        private readonly ts: WorkTimeService
    ) {
        const req = Validators.required;
        const posNumber = [req, positiveNumberValidator];
        this.dayForm = this.fb.group({
            workType: [null, req],
            start: [null, posNumber],
            end: [null, posNumber],
            breaks: [null, validateBreaks()],
            description: [null, Validators.minLength(5)],
        });
    }
 
    ngOnInit () {
        this.dayForm.valueChanges
            .pipe(
                debounceTime(100),
                tap(value => this.calculateTimes(value)),
                debounceTime(2000),
                distinctUntilChanged()
            ).subscribe(() => {
                if(this.dayForm && this.dayForm.valid && this.dayForm.dirty) {
                    const title = "timetrack.toast.saving.title";
                    const msg = "timetrack.toast.saving.message";
                    this.translate.get([title, msg])
                        .subscribe(value => {
                            this.ts.setWorktime(this.date!, this.dayForm.value).subscribe(() => {
                                this.toaster.success(value[msg],value[title]);
                                this.dayForm?.markAsPristine();
                                this.saved.emit();
                            });
                           
                        });
                }
            });
        this.workTypes$ = this.translate.stream("timetrack.workTypes").pipe(
            map(types => Object.entries(types))
        );
    }
 
    ngOnChanges (): void {
        Iif(!this.dayForm)
            return;
        Iif (!this.workTime || !this.workTime.breaks)
            this.workTime = {
                breaks: [],
                end: undefined,
                start: undefined,
                workType: "workTime",
            };
        this.dayForm.patchValue(this.workTime);
        this.updateWorkTime();
    }
 
    getTime (input: string): Date {
        const [hours, minutes] = input.split(":").map(Number);
        const date = new Date();
        date.setHours(hours, minutes);
        return date;
    }
 
    updateTime (controlName: "start" | "end", action: "setNow" | "clear") {
        if (action === "setNow") {
            this.dayForm.patchValue({ [controlName]: getCurrentTime() });
        } else Iif (action === "clear") {
            this.dayForm.patchValue({ [controlName]: null });
        }
    }
 
    checkWorkTimes (endTimeChanged: boolean) {
        Iif (!this.workTime)
            return;
        Iif (!this.workTime.start || !this.workTime.end)
            return;
        Iif (this.workTime.start > this.workTime.end) {
            if (endTimeChanged)
                this.workTime.end = this.workTime.start;
            else
                this.workTime.start = this.workTime.end;
        }
    }
 
    calculateTimes (workTime: WorkTime) {
        Iif(!workTime.end || !workTime.start)
            return;
 
        //Calculate Break Time
        this.breakMinutes =
            workTime.breaks.reduce((total, currBreak) => {
                Iif (!currBreak.end || !currBreak.start)
                    return total;
                return currBreak.end - currBreak.start + total;
            }, 0);
 
        this.workMinutes = workTime.end! - workTime.start!;
 
        const defaultBreak: WorkBreak = {
            start: 12 * 60,
            end: 12 * 60 + 30,
            isOn: false,
            type: "mandatory",
        };
 
        setTimeout(() => {
            const value: WorkTime = this.dayForm.value;
            Iif (!value)
                return;
            if (this.workMinutes >= 360 && this.breakMinutes < 30) {
                // Delay automatic break to wait for complete input of user
                if (this.workMinutes >= 360 && this.breakMinutes < 30) {
                    value.breaks.push(defaultBreak);
                    this.dayForm.patchValue(value);
                }
            }
        }, 400);
    }
    updateWorkTime () {
        const timeVal = [Validators.required, positiveNumberValidator()];
        this.dayForm.get("start")?.addValidators(timeVal);
        this.dayForm.get("end")?.addValidators(timeVal);
 
        this.workMinutes = 0;
        this.breakMinutes = 0;
        if (["school", "defaultAttendance", "vacation", "illness", "compensation"].includes(this.dayForm.value.workType)) {
            this.workMinutes = this.dayForm.value.workType === "compensation" ? 0 : this.userInfo.dailyTime;
            this.dayForm.get("start")?.clearValidators();
            this.dayForm.get("end")?.clearValidators();
        }
        Iif("defaultAttendance" === this.dayForm.value.workType)
            this.dayForm.get("description")?.addValidators(Validators.minLength(5));
        else 
            this.dayForm.get("description")?.clearValidators();
        this.dayForm.get("start")?.updateValueAndValidity();
        this.dayForm.get("end")?.updateValueAndValidity();
        this.dayForm.get("description")?.updateValueAndValidity();
    }
 
    changeWorkType () {
        this.dayForm.patchValue({
            start: undefined,
            end: undefined,
            description: undefined,
            breaks: [],
        });
 
        this.updateWorkTime(); 
        this.cdr.detectChanges();
    }
}