Register Update

This commit is contained in:
Naz 2025-03-30 16:20:19 +08:00
parent 32d8689eb1
commit db408bb2db
3 changed files with 70 additions and 98 deletions

View File

@ -1,15 +1,11 @@
using Microsoft.AspNetCore.Http; using PSTW_CentralSystem.Areas.Inventory.Models;
using System; using System;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations.Schema;
using PSTW_CentralSystem.Areas.Inventory.Models;
using PSTW_CentralSystem.Models;
namespace PSTW_CentralSystem.Areas.OTcalculate.Models namespace PSTW_CentralSystem.Areas.OTcalculate.Models
{ {
[Table("otregisters")] [Table("otregisters")]
public class OtRegisterModel public class OtRegisterModel
{ {
[Key] [Key]
@ -19,29 +15,32 @@ namespace PSTW_CentralSystem.Areas.OTcalculate.Models
public DateTime OtDate { get; set; } public DateTime OtDate { get; set; }
public TimeSpan? OfficeFrom { get; set; } public TimeSpan? OfficeFrom { get; set; }
public TimeSpan? OfficeTo { get; set; } public TimeSpan? OfficeTo { get; set; }
public int? OfficeBreak { get; set; } public int? OfficeBreak { get; set; }
public TimeSpan? OutsideFrom { get; set; } public TimeSpan? OutsideFrom { get; set; }
public TimeSpan? OutsideTo { get; set; } public TimeSpan? OutsideTo { get; set; }
public int? OutsideBreak { get; set; } public int? OutsideBreak { get; set; }
public int? StationId { get; set; } public int? StationId { get; set; }
[ForeignKey("StationId")] [ForeignKey("StationId")]
public virtual StationModel? Stations { get; set; } public virtual StationModel? Stations { get; set; }
public string OtDescription { get; set; } public string OtDescription { get; set; }
public string OtDays { get; set; } public string OtDays { get; set; }
public required string PDFBase64 { get; set; } public required string PDFBase64 { get; set; }
[Required] [Required]
public int UserId { get; set; } 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;
}
} }
} }

View File

@ -92,7 +92,7 @@
<div class="mb-3 mt-3"> <div class="mb-3 mt-3">
<label for="fileUpload">Upload File:</label> <label for="fileUpload">Upload File:</label>
<input type="file" id="fileUpload" class="form-control" v-on:change="handleFileUpload"> <input type="file" id="fileUpload" class="form-control" v-on:change="handleFileUpload" ref="fileInput">
<small class="text-danger">*upload pdf file only</small> <small class="text-danger">*upload pdf file only</small>
</div> </div>
@ -155,44 +155,23 @@
if (!response.ok) throw new Error("Failed to fetch stations"); if (!response.ok) throw new Error("Failed to fetch stations");
this.airstationList = await response.json(); this.airstationList = await response.json();
console.log("Fetched Stations:", this.airstationList);
} catch (error) { } catch (error) {
console.error("Error fetching stations:", error); console.error("Error fetching stations:", error);
} }
}, },
async fetchUser() { async fetchUser() {
try { try {
const response = await fetch(`/IdentityAPI/GetUserInformation/`, { const response = await fetch(`/IdentityAPI/GetUserInformation/`, { method: 'POST' });
method: 'POST', if (response.ok) {
}); const data = await response.json();
if (response.ok) { this.currentUser = data?.userInfo || null;
const data = await response.json(); this.userId = this.currentUser?.id || null;
this.currentUser = data?.userInfo || null; } else {
this.userId = await this.currentUser.id; 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() { calculateOTAndBreak() {
let officeOT = this.calculateTimeDifference(this.officeFrom, this.officeTo, this.officeBreak); let officeOT = this.calculateTimeDifference(this.officeFrom, this.officeTo, this.officeBreak);
@ -240,9 +219,7 @@
formatTime(timeString) { formatTime(timeString) {
if (!timeString) return null; if (!timeString) return null;
const [hours, minutes] = timeString.split(':'); const [hours, minutes] = timeString.split(':');
const formattedHours = hours.padStart(2, '0'); return `${hours.padStart(2, '0')}:${minutes.padStart(2, '0')}:00`; // Ensure valid HH:mm:ss format
const formattedMinutes = minutes.padStart(2, '0');
return `${formattedHours}:${formattedMinutes}`;
}, },
async addOvertime() { async addOvertime() {
if (!this.selectedDate || !this.selectedDayType || !this.selectedAirStation) { if (!this.selectedDate || !this.selectedDayType || !this.selectedAirStation) {
@ -261,21 +238,20 @@
return; return;
} }
console.log("Sending userId:", this.userId); // Log userId console.log("Sending userId:", this.userId);
const reader = new FileReader(); const reader = new FileReader();
reader.onload = async (event) => { reader.onload = async (event) => {
const base64String = event.target.result.split(',')[1]; const base64String = event.target.result.split(',')[1];
const payload = { const payload = {
otDate: this.selectedDate, otDate: this.selectedDate,
officeFrom: this.officeFrom, officeFrom: this.formatTime(this.officeFrom) || null,
officeTo: this.officeTo, officeTo: this.formatTime(this.officeTo) || null,
officeBreak: this.officeBreak, officeBreak: this.officeBreak || 0,
outsideFrom: this.outsideFrom ? this.outsideFrom : null, outsideFrom: this.formatTime(this.outsideFrom) || null,
outsideTo: this.outsideTo ? this.outsideTo : null, outsideTo: this.formatTime(this.outsideTo) || null,
outsideBreak: this.outsideBreak, outsideBreak: this.outsideBreak || 0,
stationId: this.selectedAirStation, stationId: this.selectedAirStation,
otDescription: this.otDescription, otDescription: this.otDescription,
otDays: this.selectedDayType, otDays: this.selectedDayType,
@ -285,10 +261,8 @@
try { try {
const response = await fetch(`${window.location.origin}/OvertimeAPI/AddOvertime`, { const response = await fetch(`${window.location.origin}/OvertimeAPI/AddOvertime`, {
method: 'POST', method: "POST",
headers: { headers: { "Content-Type": "application/json" },
'Content-Type': 'application/json',
},
body: JSON.stringify(payload), body: JSON.stringify(payload),
}); });
@ -298,11 +272,11 @@
} }
const result = await response.json(); const result = await response.json();
alert(result); alert(result.message);
this.clearForm(); this.clearForm();
} catch (error) { } catch (error) {
console.error('Error adding overtime:', error); console.error("Error adding overtime:", error);
alert('Failed to save overtime. Please check the console for errors.'); alert("Failed to save overtime. Please check the console for errors.");
} }
}; };
@ -312,10 +286,26 @@
}; };
reader.readAsDataURL(this.uploadedFile); 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");
</script> </script>
} }

View File

@ -384,6 +384,7 @@ namespace PSTW_CentralSystem.Controllers.API
public async Task<IActionResult> AddOvertimeAsync([FromBody] OtRegisterModel model) public async Task<IActionResult> AddOvertimeAsync([FromBody] OtRegisterModel model)
{ {
_logger.LogInformation("AddOvertimeAsync called."); _logger.LogInformation("AddOvertimeAsync called.");
if (model == null) if (model == null)
{ {
_logger.LogError("Model is null."); _logger.LogError("Model is null.");
@ -400,42 +401,24 @@ namespace PSTW_CentralSystem.Controllers.API
return BadRequest("User ID is required."); return BadRequest("User ID is required.");
} }
try // Convert string time values to TimeSpan before saving
{ model.OfficeFrom = model.GetOfficeFrom();
if (!string.IsNullOrEmpty(model.OfficeFrom?.ToString())) model.OfficeTo = model.GetOfficeTo();
{ model.OutsideFrom = model.GetOutsideFrom();
model.OfficeFrom = TimeSpan.Parse(model.OfficeFrom.ToString()); model.OutsideTo = model.GetOutsideTo();
}
if (!string.IsNullOrEmpty(model.OfficeTo?.ToString())) _logger.LogInformation($"Time spans parsed successfully.");
{
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");
}
_centralDbContext.Otregisters.Add(model); _centralDbContext.Otregisters.Add(model);
await _centralDbContext.SaveChangesAsync(); await _centralDbContext.SaveChangesAsync();
_logger.LogInformation("Overtime registered successfully."); _logger.LogInformation("Overtime registered successfully.");
return Ok("Overtime registered successfully."); return Ok(new { message = "Overtime registered successfully." });
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "Error registering overtime."); _logger.LogError(ex, "Error registering overtime.");
return StatusCode(500, "An error occurred."); return StatusCode(500, "An error occurred while saving overtime.");
} }
} }