update query flow

parent fe7f44ad
...@@ -17,6 +17,8 @@ ...@@ -17,6 +17,8 @@
.ot-tbl tfoot .lbl{text-align:right;letter-spacing:.04em;font-size:.82rem} .ot-tbl tfoot .lbl{text-align:right;letter-spacing:.04em;font-size:.82rem}
.btn-del{border:1px solid #e53935;background:transparent;color:#e53935;border-radius:4px;padding:2px 9px;font-size:.78rem;cursor:pointer;line-height:1.6} .btn-del{border:1px solid #e53935;background:transparent;color:#e53935;border-radius:4px;padding:2px 9px;font-size:.78rem;cursor:pointer;line-height:1.6}
.btn-del:hover{background:#e53935;color:#fff} .btn-del:hover{background:#e53935;color:#fff}
.btn-edit{border:1px solid #2185d0;background:transparent;color:#2185d0;border-radius:4px;padding:2px 9px;font-size:.78rem;cursor:pointer;line-height:1.6;margin-right:4px}
.btn-edit:hover{background:#2185d0;color:#fff}
.auto-field,input[readonly]{background:#f4f9ff!important;color:#555!important;cursor:default!important} .auto-field,input[readonly]{background:#f4f9ff!important;color:#555!important;cursor:default!important}
.badge-auto{display:inline-block;font-size:.68rem;font-weight:600;background:#e3f0ff;color:#1565c0;border-radius:3px;padding:1px 5px;margin-left:.25rem} .badge-auto{display:inline-block;font-size:.68rem;font-weight:600;background:#e3f0ff;color:#1565c0;border-radius:3px;padding:1px 5px;margin-left:.25rem}
.field-hint{font-size:.76rem;color:#999;margin-top:.3rem;display:flex;align-items:center;gap:.3rem} .field-hint{font-size:.76rem;color:#999;margin-top:.3rem;display:flex;align-items:center;gap:.3rem}
...@@ -25,6 +27,7 @@ ...@@ -25,6 +27,7 @@
.query-history th,.query-history td{border:1px solid #cfd8e3;padding:8px 10px;vertical-align:top} .query-history th,.query-history td{border:1px solid #cfd8e3;padding:8px 10px;vertical-align:top}
.query-history th{background:#f5f7fa;text-align:left} .query-history th{background:#f5f7fa;text-align:left}
.query-radio{display:flex;justify-content:flex-end;gap:1rem;flex-wrap:wrap} .query-radio{display:flex;justify-content:flex-end;gap:1rem;flex-wrap:wrap}
.row-editing{outline:2px solid #2185d0;outline-offset:-2px}
</style> </style>
<div class="ui segment" style="padding-bottom:2rem;"> <div class="ui segment" style="padding-bottom:2rem;">
...@@ -147,6 +150,8 @@ ...@@ -147,6 +150,8 @@
</div> </div>
<div class="button-row" style="display:flex;justify-content:flex-end;gap:.55rem;"> <div class="button-row" style="display:flex;justify-content:flex-end;gap:.55rem;">
<button type="button" class="ui teal button" id="btn-add-row"><i class="plus icon"></i>Add to Table</button> <button type="button" class="ui teal button" id="btn-add-row"><i class="plus icon"></i>Add to Table</button>
<button type="button" class="ui blue button" id="btn-update-row" style="display:none;"><i class="edit icon"></i>Update Row</button>
<button type="button" class="ui basic button" id="btn-cancel-edit" style="display:none;"><i class="times icon"></i>Cancel Edit</button>
<button type="button" class="ui grey button" id="btn-reset"><i class="redo icon"></i>Clear</button> <button type="button" class="ui grey button" id="btn-reset"><i class="redo icon"></i>Clear</button>
</div> </div>
</div> </div>
...@@ -217,6 +222,7 @@ ...@@ -217,6 +222,7 @@
'3': 'Hari Cuti Umum', '3': 'Hari Cuti Umum',
'4': 'Hari Cuti Selain Cuti Umum' '4': 'Hari Cuti Selain Cuti Umum'
}; };
var editingDate = null;
$(document).ready(function () { $(document).ready(function () {
if ($.fn.dropdown) $('.ui.dropdown').dropdown({ fullTextSearch: true }); if ($.fn.dropdown) $('.ui.dropdown').dropdown({ fullTextSearch: true });
...@@ -226,6 +232,8 @@ ...@@ -226,6 +232,8 @@
function bindEvents() { function bindEvents() {
$('#btn-add-row').on('click', addDay); $('#btn-add-row').on('click', addDay);
$('#btn-update-row').on('click', updateDay);
$('#btn-cancel-edit').on('click', cancelEditMode);
$('#btn-reset').on('click', resetForm); $('#btn-reset').on('click', resetForm);
$('#btn-save-draft').on('click', saveDetails); $('#btn-save-draft').on('click', saveDetails);
$('#btn-submit').on('click', submitTuntutan); $('#btn-submit').on('click', submitTuntutan);
...@@ -470,7 +478,10 @@ function renderTable() { ...@@ -470,7 +478,10 @@ function renderTable() {
html += '<td>' + pmReviewHtml + '</td>'; html += '<td>' + pmReviewHtml + '</td>';
html += '<td>' + totalValue.toFixed(1) + '</td>'; html += '<td>' + totalValue.toFixed(1) + '</td>';
html += '<td>' + effectiveValue.toFixed(1) + '</td>'; html += '<td>' + effectiveValue.toFixed(1) + '</td>';
html += '<td><button class="btn-del" onclick="removeDay(\'' + dateStr + '\')"><i class="trash icon"></i></button></td>'; html += '<td>';
html += '<button class="btn-edit" onclick="editDay(\'' + dateStr + '\')"><i class="edit icon"></i></button>';
html += '<button class="btn-del" onclick="removeDay(\'' + dateStr + '\')"><i class="trash icon"></i></button>';
html += '</td>';
html += '</tr>'; html += '</tr>';
}); });
tbody.html(html); tbody.html(html);
...@@ -556,6 +567,138 @@ function addDay() { ...@@ -556,6 +567,138 @@ function addDay() {
}); });
} }
function editDay(dateStr) {
var row = details[dateStr];
if (!row) {
showError('Entry not found.');
return;
}
editingDate = dateStr;
$('#ot-tbody tr').removeClass('row-editing');
$('#ot-tbody tr[data-date="' + dateStr + '"]').addClass('row-editing');
$('#ocd_date_input').val(dateStr);
var dayTypeCode = mapAttendanceDayTypeCode(null, row.dayType || '');
setDayTypeSelection(dayTypeCode, row.dayType || '');
$('#ocd_office_start').val(row.officeStart || '').prop('readonly', false).removeClass('auto-field');
$('#ocd_office_end').val(row.officeEnd || '').prop('readonly', true).addClass('auto-field');
$('#ocd_overtime_from').val(row.overtimeFrom || '');
$('#ocd_overtime_to').val(row.overtimeTo || '');
$('#ocd_total_hours').val((parseFloat(row.totalHours || 0) || 0).toFixed(1));
$('#ocd_effective_hours').val((parseFloat(row.effectiveHours || 0) || 0).toFixed(1));
$('#ocd_tasks').val(row.tasks || '');
$('#fk_lkp_project').val(String(row.projectId || ''));
$('#btn-add-row').hide();
$('#btn-update-row').show();
$('#btn-cancel-edit').show();
showSuccess('Editing row for ' + dateStr + '.');
}
function updateDay() {
if (!editingDate) {
showError('No row selected for editing.');
return;
}
var row = details[editingDate];
if (!row || !row.id) {
showError('Entry ID not found.');
return;
}
var dateVal = $('#ocd_date_input').val();
var dayType = $('#ocd_day_type').val();
var officeStart = $('#ocd_office_start').val();
var officeEnd = $('#ocd_office_end').val();
var overtimeFrom = $('#ocd_overtime_from').val();
var overtimeTo = $('#ocd_overtime_to').val();
var totalHours = $('#ocd_total_hours').val();
var effectiveHours = $('#ocd_effective_hours').val();
var tasks = $('#ocd_tasks').val().trim();
var projectId = $('#fk_lkp_project').val();
var projectName = $('#fk_lkp_project option:selected').text();
if (projectId === '') projectName = '-';
if (!dateVal) { showError('Please select a date.'); return; }
if (otMonth && otYear) {
var dParts = dateVal.split('-');
var dYear = parseInt(dParts[0], 10);
var dMonth = parseInt(dParts[1], 10);
if (dYear !== otYear || dMonth !== otMonth) { showError('Date must be within the claim month.'); return; }
}
if (!dayType) { showError('Please select a day type.'); return; }
if (!officeStart) { showError('Please enter Office Hour Start.'); return; }
if (!overtimeFrom) { showError('Please enter OT From.'); return; }
if (!overtimeTo) { showError('Please enter OT To.'); return; }
if (!totalHours) { showError('Total Hours cannot be empty.'); return; }
if (!effectiveHours) { showError('Effective Hours cannot be empty.'); return; }
if (!tasks) { showError('Please enter the tasks.'); return; }
$.ajax({
url: "{{ route('overtime::overtime.updateovertimeclaimdetail', ':id') }}".replace(':id', row.id),
method: 'POST',
data: {
_token: csrfToken(),
ocd_date: dateVal,
ocd_day_type: dayType,
ocd_office_start: officeStart,
ocd_office_end: officeEnd,
ocd_overtime_from: overtimeFrom,
ocd_overtime_to: overtimeTo,
ocd_total_hours: totalHours,
ocd_effective_hours: effectiveHours,
ocd_tasks: tasks,
fk_lkp_project: projectId || null,
},
success: function (res) {
if (!res.success) { showError(res.message || 'Error while updating.'); return; }
if (editingDate !== dateVal) {
delete details[editingDate];
}
details[dateVal] = {
id: res.detail.id,
totalHours: parseFloat(res.detail.ocd_total_hours || totalHours) || 0,
effectiveHours: parseFloat(res.detail.ocd_effective_hours || effectiveHours) || 0,
overtimeFrom: res.detail.ocd_overtime_from || overtimeFrom,
overtimeTo: res.detail.ocd_overtime_to || overtimeTo,
tasks: res.detail.ocd_tasks || tasks,
dayType: res.detail.ocd_day_type || dayType,
officeStart: officeStart,
officeEnd: officeEnd,
officeHour: res.detail.ocd_office_hour || (officeStart ? officeStart + ' – ' + (officeEnd || '?') : ''),
projectId: res.detail.fk_lkp_project || '',
projectName: res.detail.project_name || projectName,
ocd_pm_reviewed: false,
ocd_pm_reviewed_by_name: '',
ocd_pm_reviewed_at: null,
};
renderTable();
cancelEditMode();
showSuccess(res.message || 'Entry updated.');
},
error: function (xhr) {
var msg = 'Error while updating entry.';
if (xhr.responseJSON && xhr.responseJSON.message) msg = xhr.responseJSON.message;
if (xhr.responseJSON && xhr.responseJSON.errors) msg = Object.values(xhr.responseJSON.errors).flat().join(' ');
showError(msg);
},
});
}
function cancelEditMode() {
editingDate = null;
$('#ot-tbody tr').removeClass('row-editing');
$('#btn-update-row').hide();
$('#btn-cancel-edit').hide();
$('#btn-add-row').show();
resetForm();
}
function removeDay(dateStr) { function removeDay(dateStr) {
if (!confirm('Remove entry ' + dateStr + ' from the table?')) return; if (!confirm('Remove entry ' + dateStr + ' from the table?')) return;
var detailId = details[dateStr] && details[dateStr].id; var detailId = details[dateStr] && details[dateStr].id;
...@@ -567,6 +710,9 @@ function removeDay(dateStr) { ...@@ -567,6 +710,9 @@ function removeDay(dateStr) {
success: function (res) { success: function (res) {
if (!res.success) { showError(res.message || 'Error while removing.'); return; } if (!res.success) { showError(res.message || 'Error while removing.'); return; }
delete details[dateStr]; delete details[dateStr];
if (editingDate === dateStr) {
cancelEditMode();
}
renderTable(); renderTable();
showSuccess(res.message || 'Entry removed.'); showSuccess(res.message || 'Entry removed.');
}, },
...@@ -656,6 +802,7 @@ function resetForm() { ...@@ -656,6 +802,7 @@ function resetForm() {
resetDayTypeOptions(); resetDayTypeOptions();
$('#ocd_day_type').val(''); $('#ocd_day_type').val('');
$('#ocd_office_start').prop('readonly', false).removeClass('auto-field'); $('#ocd_office_start').prop('readonly', false).removeClass('auto-field');
$('#ocd_office_start').attr('placeholder', '');
$('#ocd_office_start, #ocd_office_end').val(''); $('#ocd_office_start, #ocd_office_end').val('');
$('#ocd_overtime_from, #ocd_overtime_to').val(''); $('#ocd_overtime_from, #ocd_overtime_to').val('');
$('#ocd_total_hours').val(''); $('#ocd_total_hours').val('');
......
...@@ -130,8 +130,12 @@ ...@@ -130,8 +130,12 @@
alert(res.message || 'Error while canceling. Please try again'); alert(res.message || 'Error while canceling. Please try again');
} }
}, },
error: function () { error: function (xhr) {
alert('Network error.'); var msg = 'Network error.';
if (xhr.responseJSON && xhr.responseJSON.message) {
msg = xhr.responseJSON.message;
}
alert(msg);
}, },
}); });
}); });
......
...@@ -23,6 +23,7 @@ function () { ...@@ -23,6 +23,7 @@ function () {
Route::get('claim/{id}/view', ['uses' => 'OvertimeClaimController@viewOvertimeClaim', 'as' => 'overtime.viewovertimeclaim']); Route::get('claim/{id}/view', ['uses' => 'OvertimeClaimController@viewOvertimeClaim', 'as' => 'overtime.viewovertimeclaim']);
Route::get('claim/{id}/edit', ['uses' => 'OvertimeClaimController@editOvertimeClaim', 'as' => 'overtime.editovertimeclaim']); Route::get('claim/{id}/edit', ['uses' => 'OvertimeClaimController@editOvertimeClaim', 'as' => 'overtime.editovertimeclaim']);
Route::post('claim/{id}/detail/add', ['uses' => 'OvertimeClaimController@addOvertimeClaimDetail', 'as' => 'overtime.addovertimeclaim']); Route::post('claim/{id}/detail/add', ['uses' => 'OvertimeClaimController@addOvertimeClaimDetail', 'as' => 'overtime.addovertimeclaim']);
Route::post('claim/detail/{id}/update', ['uses' => 'OvertimeClaimController@updateOvertimeClaimDetail', 'as' => 'overtime.updateovertimeclaimdetail']);
Route::post('claim/detail/{id}/remove', ['uses' => 'OvertimeClaimController@removeOvertimeClaimDetail', 'as' => 'overtime.removeovertimeclaim']); Route::post('claim/detail/{id}/remove', ['uses' => 'OvertimeClaimController@removeOvertimeClaimDetail', 'as' => 'overtime.removeovertimeclaim']);
Route::post('claim/{id}/save-details', ['uses' => 'OvertimeClaimController@saveOvertimeClaimDetails', 'as' => 'overtime.saveovertimeclaim']); Route::post('claim/{id}/save-details', ['uses' => 'OvertimeClaimController@saveOvertimeClaimDetails', 'as' => 'overtime.saveovertimeclaim']);
Route::post('claim/{id}/submit', ['uses' => 'OvertimeClaimController@submitOvertimeClaim', 'as' => 'overtime.submitovertimeclaim']); Route::post('claim/{id}/submit', ['uses' => 'OvertimeClaimController@submitOvertimeClaim', 'as' => 'overtime.submitovertimeclaim']);
......
...@@ -150,7 +150,7 @@ public function sokongClaim($request, int $claimId): OvertimeClaimMain ...@@ -150,7 +150,7 @@ public function sokongClaim($request, int $claimId): OvertimeClaimMain
'updated_by' => Auth::id(), 'updated_by' => Auth::id(),
]); ]);
$this->logAudit('UPDATE', $claim->id, null, $this->logAudit('SUPPORT', $claim->id, null,
"supported claim {$claim->ocm_apply_no} and sent it to the PD."); "supported claim {$claim->ocm_apply_no} and sent it to the PD.");
return $claim; return $claim;
......
...@@ -97,61 +97,19 @@ private function currentPdProjectNames(): \Illuminate\Support\Collection ...@@ -97,61 +97,19 @@ private function currentPdProjectNames(): \Illuminate\Support\Collection
public function getPdReviewList($request) public function getPdReviewList($request)
{ {
$search = $request->get('search'); $search = $request->get('search');
$pdProjectIds = $this->currentPdProjectIds();
$pdProjectNames = $this->currentPdProjectNames();
$currentPdUserId = $this->currentPdUserId(); $currentPdUserId = $this->currentPdUserId();
return OvertimeClaimMain::where('ocm_status', 7) return OvertimeClaimMain::where('ocm_status', 7)
->whereNull('deleted_at')
->where(function ($q) use ($search) { ->where(function ($q) use ($search) {
$q->where('ocm_apply_no', 'like', "%{$search}%") $q->where('ocm_apply_no', 'like', "%{$search}%")
->orWhere('ocm_staff_name', 'like', "%{$search}%"); ->orWhere('ocm_staff_name', 'like', "%{$search}%");
}) })
->where(function ($q) use ($pdProjectIds, $pdProjectNames, $currentPdUserId) { // Route to Staff PD (staff_info.pelulus), not project_team PD.
// Primary path: claim has at least one detail row in PD's project scope. ->whereIn('fk_lkp_staff_info', function ($sub) use ($currentPdUserId) {
if (!$pdProjectIds->isEmpty() || !$pdProjectNames->isEmpty()) { $sub->select('id')
$q->whereExists(function ($sub) use ($pdProjectIds, $pdProjectNames) { ->from('staff_info')
$sub->select(DB::raw('1')) ->where('pelulus', $currentPdUserId);
->from('overtime_claim_detail')
->whereRaw('overtime_claim_detail.fk_overtime_claim_main = overtime_claim_main.id')
->where(function ($d) use ($pdProjectIds, $pdProjectNames) {
if (!$pdProjectIds->isEmpty()) {
$d->whereIn('overtime_claim_detail.fk_lkp_project', $pdProjectIds->all());
}
if (!$pdProjectNames->isEmpty()) {
$d->orWhereIn('overtime_claim_detail.fk_lkp_project', function ($ss) use ($pdProjectNames) {
$ss->select('id')
->from('lkp_project')
->whereIn('p_project_description', $pdProjectNames->all());
});
}
});
});
}
// Fallback path: No Project-only claim routes to applicant's pelulus.
$q->orWhere(function ($fallback) use ($currentPdUserId) {
$fallback->whereIn('fk_lkp_staff_info', function ($sub) use ($currentPdUserId) {
$sub->select('id')
->from('staff_info')
->where('pelulus', $currentPdUserId);
})
->whereExists(function ($hasNoProject) {
$hasNoProject->select(DB::raw('1'))
->from('overtime_claim_detail')
->whereRaw('overtime_claim_detail.fk_overtime_claim_main = overtime_claim_main.id')
->where('overtime_claim_detail.fk_lkp_project', self::NO_PROJECT_ID);
})
->whereNotExists(function ($hasNormalProject) {
$hasNormalProject->select(DB::raw('1'))
->from('overtime_claim_detail')
->whereRaw('overtime_claim_detail.fk_overtime_claim_main = overtime_claim_main.id')
->where(function ($d) {
$d->whereNull('overtime_claim_detail.fk_lkp_project')
->orWhere('overtime_claim_detail.fk_lkp_project', '!=', self::NO_PROJECT_ID);
});
});
});
}) })
->orderBy('created_at', 'desc') ->orderBy('created_at', 'desc')
->paginate(10); ->paginate(10);
...@@ -169,54 +127,13 @@ public function findClaim(int $id): OvertimeClaimMain ...@@ -169,54 +127,13 @@ public function findClaim(int $id): OvertimeClaimMain
throw new AuthorizationException('Unauthorized claim access.'); throw new AuthorizationException('Unauthorized claim access.');
} }
// Ensure claim's projects match current PD's ownership/membership by $assignedToCurrentPd = DB::table('staff_info')
// inspecting the claim detail rows (fk_lkp_project).
$pdProjectIds = $this->currentPdProjectIds();
$pdProjectNames = $this->currentPdProjectNames();
$matches = DB::table('overtime_claim_detail')
->where('fk_overtime_claim_main', $claim->id)
->where(function ($q) use ($pdProjectIds, $pdProjectNames) {
if (!$pdProjectIds->isEmpty()) {
$q->whereIn('fk_lkp_project', $pdProjectIds->all());
}
if (!$pdProjectNames->isEmpty()) {
$q->orWhereIn('fk_lkp_project', function ($sub) use ($pdProjectNames) {
$sub->select('id')->from('lkp_project')->whereIn('p_project_description', $pdProjectNames->all());
});
}
})
->exists();
if ($matches) {
return $claim;
}
// Fallback access: No Project-only claim belongs to current PD when
// applicant's staff_info.pelulus points to this PD user.
$fallbackEligible = DB::table('staff_info')
->where('id', $claim->fk_lkp_staff_info) ->where('id', $claim->fk_lkp_staff_info)
->where('pelulus', $this->currentPdUserId()) ->where('pelulus', $this->currentPdUserId())
->exists(); ->exists();
if ($fallbackEligible) { if ($assignedToCurrentPd) {
$hasNoProject = DB::table('overtime_claim_detail') return $claim;
->where('fk_overtime_claim_main', $claim->id)
->where('fk_lkp_project', self::NO_PROJECT_ID)
->exists();
$hasNormalProject = DB::table('overtime_claim_detail')
->where('fk_overtime_claim_main', $claim->id)
->where(function ($q) {
$q->whereNull('fk_lkp_project')
->orWhere('fk_lkp_project', '!=', self::NO_PROJECT_ID);
})
->exists();
if ($hasNoProject && !$hasNormalProject) {
return $claim;
}
} }
throw new AuthorizationException('Unauthorized claim access.'); throw new AuthorizationException('Unauthorized claim access.');
...@@ -264,7 +181,7 @@ public function sokongClaim($request, int $claimId): OvertimeClaimMain ...@@ -264,7 +181,7 @@ public function sokongClaim($request, int $claimId): OvertimeClaimMain
'updated_by' => Auth::id(), 'updated_by' => Auth::id(),
]); ]);
$this->logAudit('UPDATE', $claim->id, null, $this->logAudit('APPROVE', $claim->id, null,
"approved claim {$claim->ocm_apply_no}."); "approved claim {$claim->ocm_apply_no}.");
return $claim; return $claim;
......
...@@ -5,6 +5,7 @@ ...@@ -5,6 +5,7 @@
use Carbon\Carbon; use Carbon\Carbon;
use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Portal\Overtime\Model\OvertimeAuditQuery;
use Portal\Overtime\Model\OvertimeClaimDetail; use Portal\Overtime\Model\OvertimeClaimDetail;
use Portal\Overtime\Model\OvertimeClaimMain; use Portal\Overtime\Model\OvertimeClaimMain;
use Portal\Overtime\Model\OvertimeAuditTrail; use Portal\Overtime\Model\OvertimeAuditTrail;
...@@ -251,7 +252,13 @@ public function addOvertimeClaimDetail(int $id, $request): OvertimeClaimDetail ...@@ -251,7 +252,13 @@ public function addOvertimeClaimDetail(int $id, $request): OvertimeClaimDetail
->first(); ->first();
if ($existing) { if ($existing) {
$existing->update($payload); $existing->update(array_merge($payload, [
// Editing an existing row (including query-back corrections)
// must return the row to PM re-review.
'ocd_pm_reviewed' => 0,
'ocd_pm_reviewed_by' => null,
'ocd_pm_reviewed_at' => null,
]));
$detail = $existing->fresh(); $detail = $existing->fresh();
$this->getAuditTrail('UPDATE', $id, $detail->id, $this->getAuditTrail('UPDATE', $id, $detail->id,
...@@ -287,6 +294,69 @@ public function removeOvertimeClaimDetail(int $id): void ...@@ -287,6 +294,69 @@ public function removeOvertimeClaimDetail(int $id): void
} }
// UPDATE DETAIL
public function updateOvertimeClaimDetail(int $detailId, $request): OvertimeClaimDetail
{
$detail = OvertimeClaimDetail::findOrFail($detailId);
$officeHour = $request->ocd_office_start
? $request->ocd_office_start . ' – ' . ($request->ocd_office_end ?? '?')
: null;
$attendance = DB::table('attendance')
->where('fk_staff_info', $this->currentStaffInfoId())
->whereDate('date', $request->ocd_date)
->first(['fk_lkp_day_type', 'attendance_status']);
$attendanceDayType = $attendance && isset($attendance->fk_lkp_day_type)
? (int) $attendance->fk_lkp_day_type
: null;
$attendanceStatus = $attendance && isset($attendance->attendance_status)
? (int) $attendance->attendance_status
: null;
$resolvedDayType = $this->buildAttendanceDayTypeLabel(
$attendanceDayType,
$attendanceStatus
) ?? $this->mapDayTypeCodeToLabel($request->ocd_day_type) ?? $request->ocd_day_type;
$duplicate = OvertimeClaimDetail::where('fk_overtime_claim_main', $detail->fk_overtime_claim_main)
->whereDate('ocd_date', $request->ocd_date)
->where('id', '!=', $detailId)
->first();
if ($duplicate) {
throw new \Exception('Tarikh ini sudah wujud dalam tuntutan. Sila kemaskini baris sedia ada atau pilih tarikh lain.');
}
$detail->update([
'ocd_date' => $request->ocd_date,
'ocd_day_type' => $resolvedDayType,
'ocd_office_hour' => $officeHour,
'ocd_overtime_from' => $request->ocd_overtime_from,
'ocd_overtime_to' => $request->ocd_overtime_to,
'ocd_total_hours' => $request->ocd_total_hours,
'ocd_effective_hours' => $request->ocd_effective_hours,
'ocd_tasks' => $request->ocd_tasks,
'fk_lkp_project' => $request->fk_lkp_project ?: null,
// Any row edit should be re-reviewed by PM except No Project auto-flow on submit.
'ocd_pm_reviewed' => 0,
'ocd_pm_reviewed_by' => null,
'ocd_pm_reviewed_at' => null,
'updated_by' => Auth::id(),
]);
$updated = $detail->fresh();
$this->getAuditTrail('UPDATE', $detail->fk_overtime_claim_main, $detailId,
'Entry updated for date ' . $request->ocd_date . '.');
return $updated;
}
// UPDATE MAIN // UPDATE MAIN
...@@ -309,6 +379,37 @@ public function updateOvertimeClaim($request, int $id): OvertimeClaimMain ...@@ -309,6 +379,37 @@ public function updateOvertimeClaim($request, int $id): OvertimeClaimMain
return $record; return $record;
} }
private function hasDetailChangesSinceLatestQuery(OvertimeClaimMain $record): bool
{
$latestQuery = OvertimeAuditQuery::where('fk_main', $record->id)
->orderByDesc('tarikh')
->orderByDesc('created_at')
->first();
if (! $latestQuery) {
return false;
}
$queryAt = $latestQuery->tarikh ?? $latestQuery->created_at;
if (! $queryAt) {
return false;
}
$detailTaskIds = DB::table('lkp_overtime_task')
->whereIn('task_code', ['CREATE', 'UPDATE', 'DELETE'])
->pluck('id');
if ($detailTaskIds->isEmpty()) {
return false;
}
return OvertimeAuditTrail::where('fk_overtime_claim_main', $record->id)
->whereIn('fk_lkp_overtime_task', $detailTaskIds)
->whereNotNull('fk_overtime_claim_detail')
->where('created_at', '>', $queryAt)
->exists();
}
// SUBMIT // SUBMIT
...@@ -326,7 +427,8 @@ public function submitOvertimeClaim($request, int $id): OvertimeClaimMain ...@@ -326,7 +427,8 @@ public function submitOvertimeClaim($request, int $id): OvertimeClaimMain
throw new \Exception('Please add at least one overtime claim day.'); throw new \Exception('Please add at least one overtime claim day.');
} }
$isResubmission = in_array((int) $record->ocm_status, [6, 8, 10], true) && (int) $record->ocm_query_status === 1; $currentStatus = (int) $record->ocm_status;
$isResubmission = in_array($currentStatus, [6, 8, 10], true) && (int) $record->ocm_query_status === 1;
$newStatus = $isResubmission ? 3 : 2; $newStatus = $isResubmission ? 3 : 2;
// If all detail rows belong to the dedicated "No Project" entry, // If all detail rows belong to the dedicated "No Project" entry,
...@@ -348,6 +450,15 @@ public function submitOvertimeClaim($request, int $id): OvertimeClaimMain ...@@ -348,6 +450,15 @@ public function submitOvertimeClaim($request, int $id): OvertimeClaimMain
} }
} }
$detailChangedAfterQuery = false;
if ($isResubmission && in_array($currentStatus, [8, 10], true)) {
$detailChangedAfterQuery = $this->hasDetailChangesSinceLatestQuery($record);
if (! $detailChangedAfterQuery) {
// No detail changes after HOD/PD query: route back to the same query level.
$newStatus = $currentStatus === 8 ? 5 : 7;
}
}
// For first-time submissions, clear PM review flags so PMs review unless // For first-time submissions, clear PM review flags so PMs review unless
// this is a No Project claim — in that case mark details as reviewed // this is a No Project claim — in that case mark details as reviewed
// and send straight to HOD (status 5). // and send straight to HOD (status 5).
...@@ -370,10 +481,16 @@ public function submitOvertimeClaim($request, int $id): OvertimeClaimMain ...@@ -370,10 +481,16 @@ public function submitOvertimeClaim($request, int $id): OvertimeClaimMain
]); ]);
} }
} else { } else {
// Resubmission: if all details are No Project, ensure routing goes to HOD // Resubmission: if all details are No Project, ensure routing goes to HOD.
if ($allNoProject) { if ($allNoProject) {
$newStatus = 5; $newStatus = 5;
} }
// HOD/PD query with changed details must return to default flow (PM -> HOD -> PD).
// Keep PM gating as-is: only rows with ocd_pm_reviewed = 0 are re-reviewed.
if (in_array($currentStatus, [8, 10], true) && $detailChangedAfterQuery && ! $allNoProject) {
$newStatus = 3;
}
} }
$record->update([ $record->update([
...@@ -401,6 +518,29 @@ public function deleteOvertimeClaim(int $id): void ...@@ -401,6 +518,29 @@ public function deleteOvertimeClaim(int $id): void
} }
// BATAL (soft-cancel via status)
public function batalOvertimeClaim(int $id): OvertimeClaimMain
{
$record = $this->findOvertimeClaim($id);
// Allow cancellation for Draft and queried statuses by PM/HOD/PD.
if (!in_array((int) $record->ocm_status, [1, 6, 8, 10], true)) {
throw new \Exception('The claim cannot be cancelled in its current status.');
}
$record->update([
'ocm_status' => 4, // Batal
'updated_by' => Auth::id(),
]);
$this->getAuditTrail('DELETE', $record->id, null, 'Claim cancelled by the applicant.');
return $record;
}
// AUDIT TRAIL // AUDIT TRAIL
public function getAuditTrail(string $taskCode, int $claimId, ?int $detailId = null, string $extra = ''): void public function getAuditTrail(string $taskCode, int $claimId, ?int $detailId = null, string $extra = ''): void
{ {
......
...@@ -351,9 +351,9 @@ public function updateRequestForm($request, int $id): OvertimeRequestMain ...@@ -351,9 +351,9 @@ public function updateRequestForm($request, int $id): OvertimeRequestMain
public function batalRequestForm(int $id): OvertimeRequestMain public function batalRequestForm(int $id): OvertimeRequestMain
{ {
$record = $this->findRequestForm($id); $record = $this->findRequestForm($id);
$this->authorizePmRequestAccess($record, [1]); $this->authorizePmRequestAccess($record, [1, 8, 10]);
if ($record->orm_status != 1) { if (!in_array((int) $record->orm_status, [1, 8, 10], true)) {
throw new \Exception('The request form cannot be cancelled in its current status.'); throw new \Exception('The request form cannot be cancelled in its current status.');
} }
...@@ -363,7 +363,7 @@ public function batalRequestForm(int $id): OvertimeRequestMain ...@@ -363,7 +363,7 @@ public function batalRequestForm(int $id): OvertimeRequestMain
]); ]);
// Audit trail: cancel request form // Audit trail: cancel request form
$this->logAuditTrail('UPDATE', $record->id, null, 'Request form cancelled by the applicant.'); $this->logAuditTrail('DELETE', $record->id, null, 'Request form cancelled by the applicant.');
return $record; return $record;
} }
......
...@@ -311,6 +311,72 @@ public function addOvertimeClaimDetail(Request $request, int $id): JsonResponse ...@@ -311,6 +311,72 @@ public function addOvertimeClaimDetail(Request $request, int $id): JsonResponse
}); });
} }
// UPDATE DETAIL
public function updateOvertimeClaimDetail(Request $request, int $id): JsonResponse
{
$detail = \Portal\Overtime\Model\OvertimeClaimDetail::findOrFail($id);
$main = $this->repos->findOvertimeClaim($detail->fk_overtime_claim_main);
if (!in_array($main->ocm_status, [1, 6, 8, 10])) {
return response()->json([
'success' => false,
'message' => 'Permohonan yang telah dihantar tidak boleh dikemaskini.',
], 403);
}
$request->validate(
[
'ocd_date' => 'required|date',
'ocd_day_type' => 'required|string',
'ocd_office_start' => 'required|string',
'ocd_overtime_from' => 'required|string',
'ocd_overtime_to' => 'required|string',
'ocd_total_hours' => 'required|numeric|min:0.5',
'ocd_effective_hours' => 'required|numeric|min:0.5',
'ocd_tasks' => 'required|string|max:2000',
],
[
'ocd_date.required' => 'Tarikh diperlukan.',
'ocd_day_type.required' => 'Jenis hari diperlukan.',
'ocd_office_start.required' => 'Masa mula pejabat diperlukan.',
'ocd_overtime_from.required' => 'Masa mula lebih masa diperlukan.',
'ocd_overtime_to.required' => 'Masa tamat lebih masa diperlukan.',
'ocd_total_hours.required' => 'Total hours diperlukan.',
'ocd_effective_hours.required' => 'Effective hours diperlukan.',
'ocd_tasks.required' => 'Sila huraikan tugasan.',
]
);
return $this->withTransaction(function () use ($id, $request) {
$updated = $this->repos->updateOvertimeClaimDetail($id, $request);
$projectName = $updated->fk_lkp_project
? DB::table('lkp_project')->where('id', $updated->fk_lkp_project)->value('p_project_description') ?? ''
: '';
return response()->json([
'success' => true,
'message' => 'Entri lebih masa berjaya dikemaskini.',
'detail' => [
'id' => $updated->id,
'ocd_date' => $updated->ocd_date->format('Y-m-d'),
'ocd_day_type' => $updated->ocd_day_type,
'ocd_office_hour' => $updated->ocd_office_hour,
'ocd_overtime_from' => $updated->ocd_overtime_from,
'ocd_overtime_to' => $updated->ocd_overtime_to,
'ocd_total_hours' => $updated->ocd_total_hours,
'ocd_effective_hours' => $updated->ocd_effective_hours,
'ocd_tasks' => $updated->ocd_tasks,
'fk_lkp_project' => $updated->fk_lkp_project,
'project_name' => $projectName,
],
]);
});
}
// REMOVE DETAIL // REMOVE DETAIL
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment