diff --git a/Areas/OTcalculate/Models/OtRegisterModel.cs b/Areas/OTcalculate/Models/OtRegisterModel.cs index 28a852c..89054d6 100644 --- a/Areas/OTcalculate/Models/OtRegisterModel.cs +++ b/Areas/OTcalculate/Models/OtRegisterModel.cs @@ -1,15 +1,11 @@ -using Microsoft.AspNetCore.Http; -using System; +using PSTW_CentralSystem.Areas.Inventory.Models; +using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; -using PSTW_CentralSystem.Areas.Inventory.Models; -using PSTW_CentralSystem.Models; namespace PSTW_CentralSystem.Areas.OTcalculate.Models { [Table("otregisters")] - - public class OtRegisterModel { [Key] @@ -17,31 +13,34 @@ namespace PSTW_CentralSystem.Areas.OTcalculate.Models [Required] public DateTime OtDate { get; set; } - + public TimeSpan? OfficeFrom { get; set; } - public TimeSpan? OfficeTo { get; set; } - public int? OfficeBreak { get; set; } - public TimeSpan? OutsideFrom { get; set; } - public TimeSpan? OutsideTo { get; set; } - public int? OutsideBreak { get; set; } - - public int? StationId { get; set; } + public int? StationId { get; set; } [ForeignKey("StationId")] public virtual StationModel? Stations { get; set; } public string OtDescription { get; set; } - public string OtDays { get; set; } - public required string PDFBase64 { get; set; } [Required] public int UserId { get; set; } + + // Convert string times to TimeSpan before saving + public TimeSpan? GetOfficeFrom() => ParseTimeSpan(OfficeFrom?.ToString()); + public TimeSpan? GetOfficeTo() => ParseTimeSpan(OfficeTo?.ToString()); + public TimeSpan? GetOutsideFrom() => ParseTimeSpan(OutsideFrom?.ToString()); + public TimeSpan? GetOutsideTo() => ParseTimeSpan(OutsideTo?.ToString()); + + private TimeSpan? ParseTimeSpan(string? time) + { + return TimeSpan.TryParse(time, out TimeSpan result) ? result : null; + } } -} \ No newline at end of file +} diff --git a/Areas/OTcalculate/Views/Overtime/OtRegister.cshtml b/Areas/OTcalculate/Views/Overtime/OtRegister.cshtml index 1821e22..c3d6db5 100644 --- a/Areas/OTcalculate/Views/Overtime/OtRegister.cshtml +++ b/Areas/OTcalculate/Views/Overtime/OtRegister.cshtml @@ -92,7 +92,7 @@
- + *upload pdf file only
@@ -155,44 +155,23 @@ if (!response.ok) throw new Error("Failed to fetch stations"); this.airstationList = await response.json(); - console.log("Fetched Stations:", this.airstationList); } catch (error) { console.error("Error fetching stations:", error); } }, - async fetchUser() { - try { - const response = await fetch(`/IdentityAPI/GetUserInformation/`, { - method: 'POST', - }); - if (response.ok) { - const data = await response.json(); - this.currentUser = data?.userInfo || null; - this.userId = await this.currentUser.id; + async fetchUser() { + try { + const response = await fetch(`/IdentityAPI/GetUserInformation/`, { method: 'POST' }); + if (response.ok) { + const data = await response.json(); + this.currentUser = data?.userInfo || null; + this.userId = this.currentUser?.id || null; + } else { + console.error(`Failed to fetch user: ${response.statusText}`); + } + } catch (error) { + console.error("Error fetching user:", error); } - else { - console.error(`Failed to fetch user: ${response.statusText}`); - } - } - catch (error) { - console.error('There was a problem with the fetch operation:', error); - } - }, - - clearForm() { - this.selectedDate = ""; - this.officeFrom = ""; - this.officeTo = ""; - this.officeBreak = 0; - this.outsideFrom = ""; - this.outsideTo = ""; - this.outsideBreak = 0; - this.selectedAirStation = ""; - this.otDescription = ""; - this.selectedDayType = ""; - this.totalOTHours = "0 hr 0 min"; - this.totalBreakHours = "0 hr 0 min"; - this.uploadedFile = null; }, calculateOTAndBreak() { let officeOT = this.calculateTimeDifference(this.officeFrom, this.officeTo, this.officeBreak); @@ -240,9 +219,7 @@ formatTime(timeString) { if (!timeString) return null; const [hours, minutes] = timeString.split(':'); - const formattedHours = hours.padStart(2, '0'); - const formattedMinutes = minutes.padStart(2, '0'); - return `${formattedHours}:${formattedMinutes}`; + return `${hours.padStart(2, '0')}:${minutes.padStart(2, '0')}:00`; // Ensure valid HH:mm:ss format }, async addOvertime() { if (!this.selectedDate || !this.selectedDayType || !this.selectedAirStation) { @@ -261,21 +238,20 @@ return; } - console.log("Sending userId:", this.userId); // Log userId + console.log("Sending userId:", this.userId); const reader = new FileReader(); - reader.onload = async (event) => { const base64String = event.target.result.split(',')[1]; const payload = { otDate: this.selectedDate, - officeFrom: this.officeFrom, - officeTo: this.officeTo, - officeBreak: this.officeBreak, - outsideFrom: this.outsideFrom ? this.outsideFrom : null, - outsideTo: this.outsideTo ? this.outsideTo : null, - outsideBreak: this.outsideBreak, + officeFrom: this.formatTime(this.officeFrom) || null, + officeTo: this.formatTime(this.officeTo) || null, + officeBreak: this.officeBreak || 0, + outsideFrom: this.formatTime(this.outsideFrom) || null, + outsideTo: this.formatTime(this.outsideTo) || null, + outsideBreak: this.outsideBreak || 0, stationId: this.selectedAirStation, otDescription: this.otDescription, otDays: this.selectedDayType, @@ -285,10 +261,8 @@ try { const response = await fetch(`${window.location.origin}/OvertimeAPI/AddOvertime`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, + method: "POST", + headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload), }); @@ -298,11 +272,11 @@ } const result = await response.json(); - alert(result); + alert(result.message); this.clearForm(); } catch (error) { - console.error('Error adding overtime:', error); - alert('Failed to save overtime. Please check the console for errors.'); + console.error("Error adding overtime:", error); + alert("Failed to save overtime. Please check the console for errors."); } }; @@ -312,10 +286,26 @@ }; reader.readAsDataURL(this.uploadedFile); - } + }, + clearForm() { + this.selectedDate = ""; + this.officeFrom = ""; + this.officeTo = ""; + this.officeBreak = 0; + this.outsideFrom = ""; + this.outsideTo = ""; + this.outsideBreak = 0; + this.selectedAirStation = ""; + this.otDescription = ""; + this.selectedDayType = ""; + this.totalOTHours = "0 hr 0 min"; + this.totalBreakHours = "0 hr 0 min"; + this.uploadedFile = null; + this.$refs.fileInput.value = ''; + }, } }); - app.mount('#app'); + app.mount("#app"); } \ No newline at end of file diff --git a/Controllers/API/OvertimeAPI.cs b/Controllers/API/OvertimeAPI.cs index 2ec8e3e..92a79f2 100644 --- a/Controllers/API/OvertimeAPI.cs +++ b/Controllers/API/OvertimeAPI.cs @@ -384,6 +384,7 @@ namespace PSTW_CentralSystem.Controllers.API public async Task AddOvertimeAsync([FromBody] OtRegisterModel model) { _logger.LogInformation("AddOvertimeAsync called."); + if (model == null) { _logger.LogError("Model is null."); @@ -400,42 +401,24 @@ namespace PSTW_CentralSystem.Controllers.API return BadRequest("User ID is required."); } - try - { - if (!string.IsNullOrEmpty(model.OfficeFrom?.ToString())) - { - model.OfficeFrom = TimeSpan.Parse(model.OfficeFrom.ToString()); - } - if (!string.IsNullOrEmpty(model.OfficeTo?.ToString())) - { - model.OfficeTo = TimeSpan.Parse(model.OfficeTo.ToString()); - } - if (!string.IsNullOrEmpty(model.OutsideFrom?.ToString())) - { - model.OutsideFrom = TimeSpan.Parse(model.OutsideFrom.ToString()); - } - if (!string.IsNullOrEmpty(model.OutsideTo?.ToString())) - { - model.OutsideTo = TimeSpan.Parse(model.OutsideTo.ToString()); - } - _logger.LogInformation($"Time spans parsed successfully."); - } - catch (Exception timeEx) - { - _logger.LogError(timeEx, "Error parsing timespans"); - return StatusCode(500, "Error parsing timespans"); - } + // Convert string time values to TimeSpan before saving + model.OfficeFrom = model.GetOfficeFrom(); + model.OfficeTo = model.GetOfficeTo(); + model.OutsideFrom = model.GetOutsideFrom(); + model.OutsideTo = model.GetOutsideTo(); + + _logger.LogInformation($"Time spans parsed successfully."); _centralDbContext.Otregisters.Add(model); await _centralDbContext.SaveChangesAsync(); _logger.LogInformation("Overtime registered successfully."); - return Ok("Overtime registered successfully."); + return Ok(new { message = "Overtime registered successfully." }); } catch (Exception ex) { _logger.LogError(ex, "Error registering overtime."); - return StatusCode(500, "An error occurred."); + return StatusCode(500, "An error occurred while saving overtime."); } }