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.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]
@ -19,29 +15,32 @@ namespace PSTW_CentralSystem.Areas.OTcalculate.Models
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; }
[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;
}
}
}

View File

@ -92,7 +92,7 @@
<div class="mb-3 mt-3">
<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>
</div>
@ -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',
});
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;
}
else {
this.userId = this.currentUser?.id || null;
} else {
console.error(`Failed to fetch user: ${response.statusText}`);
}
} catch (error) {
console.error("Error fetching user:", error);
}
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");
</script>
}

View File

@ -384,6 +384,7 @@ namespace PSTW_CentralSystem.Controllers.API
public async Task<IActionResult> 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());
}
// 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.");
}
catch (Exception timeEx)
{
_logger.LogError(timeEx, "Error parsing timespans");
return StatusCode(500, "Error parsing timespans");
}
_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.");
}
}