import {Component, Inject, OnInit} from '@angular/core'; import {FormBuilder, FormGroup} from "@angular/forms"; import {MAT_DIALOG_DATA, MatDialogRef} from "@angular/material/dialog"; import {HttpClient} from "@angular/common/http"; import {ToastrService} from "ngx-toastr"; import {ConfigService} from "@services/config.service"; @Component({ selector: 'app-create-task-schedule', templateUrl: './create-task-schedule.component.html', styleUrl: './create-task-schedule.component.css' }) export class CreateTaskScheduleComponent implements OnInit{ form: FormGroup; baseUrl: string; apiUrl: string; recurrenceTypes = ['none', 'custom']; weekDays: string[] = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']; isSingleDateSelected: boolean = true; monthsList: string[] = [ 'january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december' ]; monthRows: string[][] = []; editing: boolean = false; selectedMonths: { [key: string]: boolean } = {}; selectedDays: { [key: string]: boolean } = {}; constructor( private fb: FormBuilder, public dialogRef: MatDialogRef, private http: HttpClient, private toastr: ToastrService, private configService: ConfigService, @Inject(MAT_DIALOG_DATA) public data: any ) { this.baseUrl = this.configService.apiUrl; this.apiUrl = `${this.baseUrl}/command-task-schedules`; this.form = this.fb.group({ executionDate: [new Date()], executionTime: ['08:00'], recurrenceType: ['none'], recurrenceDetails: this.fb.group({ daysOfWeek: [[]], months: this.fb.control([]), initDate: [null], endDate: [null] }), enabled: [true] }); if (this.data.schedule) { this.editing = true; this.loadData(); } this.form.get('recurrenceType')?.valueChanges.subscribe((value) => { if (value === 'none') { this.form.get('recurrenceDetails')?.disable(); } else { this.form.get('recurrenceDetails')?.enable(); } }); } ngOnInit(): void { this.monthRows = [ this.monthsList.slice(0, 6), this.monthsList.slice(6, 12) ]; } loadData(): void { this.http.get(`${this.baseUrl}${this.data.schedule['@id']}`).subscribe( (data) => { const formattedExecutionTime = this.formatExecutionTime(data.executionTime); this.form.patchValue({ executionDate: data.executionDate, executionTime: formattedExecutionTime, recurrenceType: data.recurrenceType, recurrenceDetails: { ...data.recurrenceDetails, initDate: data.recurrenceDetails.initDate || null, endDate: data.recurrenceDetails.endDate || null, daysOfWeek: data.recurrenceDetails.daysOfWeek || [], months: data.recurrenceDetails.months || [] }, enabled: data.enabled }); this.selectedDays = data.recurrenceDetails.daysOfWeek.reduce((acc: any, day: string) => { acc[day] = true; return acc; }, {}); this.selectedMonths = data.recurrenceDetails.months.reduce((acc: any, month: string) => { acc[month] = true; return acc; }, {}); }, (error) => { console.error('Error loading schedule data', error); } ); } formatExecutionTime(time: string | Date): string { const date = (time instanceof Date) ? time : new Date(time); if (isNaN(date.getTime())) { console.error('Invalid execution time:', time); return ''; } return date.toISOString().substring(11, 16); } onSubmit() { const formData = this.form.value; const payload: any = { commandTask: this.data.task['@id'], executionDate: formData.recurrenceType === 'none' ? formData.executionDate : null, executionTime: formData.executionTime, recurrenceType: formData.recurrenceType, recurrenceDetails: { ...formData.recurrenceDetails, initDate: formData.recurrenceDetails.initDate || null, endDate: formData.recurrenceDetails.endDate || null, daysOfWeek: formData.recurrenceDetails.daysOfWeek || [], months: formData.recurrenceDetails.months || [] }, enabled: formData.enabled } if (this.editing) { const taskId = this.data.task.uuid; this.http.patch(`${this.baseUrl}${this.data.schedule['@id']}`, payload).subscribe({ next: () => { this.toastr.success('Programacion de tarea actualizada con éxito'); this.dialogRef.close(true); }, error: () => { this.toastr.error('Error al actualizar la tarea'); } }); } else { this.http.post(this.apiUrl, payload).subscribe({ next: () => { this.toastr.success('Programacion de tarea creada con éxito'); this.dialogRef.close(true); }, error: () => { this.toastr.error('Error al crear la tarea'); } }); } } onCancel(): void { this.dialogRef.close(false); } get summaryText(): string { const recurrence = this.form.get('recurrenceType')?.value; const start = this.form.get('recurrenceType')?.value === 'none' ? this.form.get('executionDate')?.value : this.form.get('recurrenceDetails.initDate')?.value; const end = this.form.get('recurrenceType')?.value === 'none' ? this.form.get('executionDate')?.value : this.form.get('recurrenceDetails.endDate')?.value; const time = this.form.get('executionTime')?.value; const days = Object.keys(this.selectedDays).filter(day => this.selectedDays[day]); const months = Object.keys(this.selectedMonths).filter(month => this.selectedMonths[month]); if (recurrence === 'none') { return `Esta acción se ejecutará una sola vez el ${ this.formatDate(start)} a las ${time}.`; } return `Esta acción se ejecutará todos los ${days.join(', ')} de ${months.join(', ')}, desde el ${this.formatDate(start)} hasta el ${this.formatDate(end)} a las ${time}.`; } formatDate(date: string | Date): string { const realDate = (date instanceof Date) ? date : new Date(date); return new Intl.DateTimeFormat('es-ES', { dateStyle: 'long' }).format(realDate); } toggleDay(day: string) { this.selectedDays[day] = !this.selectedDays[day]; const days = Object.keys(this.selectedDays).filter(d => this.selectedDays[d]); this.form.get('recurrenceDetails.daysOfWeek')?.setValue(days); } toggleMonth(month: string) { this.selectedMonths[month] = !this.selectedMonths[month]; const months = Object.keys(this.selectedMonths).filter(m => this.selectedMonths[m]); this.form.get('recurrenceDetails.months')?.setValue(months); } }