update pm flow

parent 358ba95d
......@@ -31,13 +31,13 @@ final class Permission extends Enum
const STAFF = "STAFF";
// start overtime menu
const APPLICATION_OT = "APPLICATION_OT";
const APPLICATION_OT_REVIEW = "APPLICATION_OT_REVIEW";
const REQUEST_OT = "REQUEST_OT";
const APPLICATION_OT_HOD = "APPLICATION_OT_HOD";
const APPLICATION_OT_PD = "APPLICATION_OT_PD";
const APPLICATION_OT_SUPPORT = "APPLICATION_OT_SUPPORT";
const APPLICATION_OT_APPROVE = "APPLICATION_OT_APPROVE";
const REQUEST_OT_PM = "REQUEST_OT_PM";
const REQUEST_OT_HOD = "REQUEST_OT_HOD";
const REQUEST_OT_PD = "REQUEST_OT_PD";
const CLAIM_OT = "CLAIM_OT";
const CLAIM_OT_PM = "CLAIM_OT_PM";
const CLAIM_OT_HOD = "CLAIM_OT_HOD";
const CLAIM_OT_PD = "CLAIM_OT_PD";
// end overtime menu
......
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('overtime_audit_trail', function (Blueprint $table) {
$table->integer('fk_overtime_request_main')->nullable()->after('id');
$table->integer('fk_overtime_request_detail')->nullable()->after('fk_overtime_request_main');
$table->index('fk_overtime_request_main');
$table->index('fk_overtime_request_detail');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('overtime_audit_trail', function (Blueprint $table) {
$table->dropIndex(['fk_overtime_request_main']);
$table->dropIndex(['fk_overtime_request_detail']);
$table->dropColumn(['fk_overtime_request_main', 'fk_overtime_request_detail']);
});
}
};
\ No newline at end of file
......@@ -67,7 +67,18 @@
<td>{{ $d->ocd_overtime_to ?? '-' }}</td>
<td>{{ $d->fk_lkp_project ? (\DB::table('lkp_project')->where('id', $d->fk_lkp_project)->value('p_project_description') ?? '-') : '-' }}</td>
<td class="td-left">{{ $d->ocd_tasks ?? '-' }}</td>
<td>@if($d->ocd_pm_reviewed)<span class="ui green label">Reviewed</span>@else<span class="ui orange label">Pending</span>@endif</td>
<td>
@php $isNoProject = ($d->fk_lkp_project == 110); @endphp
@if($isNoProject)
<span class="ui tiny blue label">Auto</span>
@else
@if($d->ocd_pm_reviewed)
<span class="ui green label">Reviewed</span>
@else
<span class="ui orange label">Pending</span>
@endif
@endif
</td>
<td><strong>{{ number_format($d->ocd_total_hours ?? 0, 1) }}</strong></td>
<td><strong>{{ number_format($d->ocd_effective_hours ?? 0, 1) }}</strong></td>
</tr>
......@@ -142,8 +153,9 @@
<tr>
<th style="width:180px;">From</th>
<th>Query Notes</th>
<th style="width:150px;">Query Date</th>
<th>Response</th>
<th style="width:150px;">Date</th>
<th style="width:150px;">Respond Date</th>
</tr>
</thead>
<tbody>
......@@ -151,11 +163,12 @@
<tr>
<td>{{ \DB::table('users')->where('id', $q->fk_user_kueri)->value('name') ?? '-' }}</td>
<td>{{ $q->remarks ?: '-' }}</td>
<td>{{ $q->respond ?: '-' }}</td>
<td>{{ $q->tarikh ? \Carbon\Carbon::parse($q->tarikh)->format('d/m/Y H:i') : ($q->created_at ? $q->created_at->format('d/m/Y H:i') : '-') }}</td>
<td>{{ $q->respond ?: '-' }}</td>
<td>{{ $q->updated_at ? $q->updated_at->format('d/m/Y H:i') : '-' }}</td>
</tr>
@empty
<tr><td colspan="4" style="color:#999;font-style:italic;text-align:center;padding:1rem;">No query history found.</td></tr>
<tr><td colspan="5" style="color:#999;font-style:italic;text-align:center;padding:1rem;">No query history found.</td></tr>
@endforelse
</tbody>
</table>
......
......@@ -73,8 +73,8 @@
<i class='eye icon'></i> View
</button>";
// Editable only for Draf (1) or Dikueri oleh PM (6)
$canEdit = in_array($row->ocm_status, [1, 6]);
// Editable only for Draf (1) or queried statuses by PM/HOD/PD (6/8/10)
$canEdit = in_array($row->ocm_status, [1, 6, 8, 10]);
$edit = $canEdit
? "<a href='" . route('overtime::overtime.editovertimeclaim', $row->id) . "'
......@@ -83,8 +83,8 @@
</a>"
: "";
// Batal allowed only from Draf (1) or Dikueri oleh PM (6)
$canBatal = in_array($row->ocm_status, [1, 6]);
// Cancel allowed only from Draf (1) or queried statuses by PM/HOD/PD (6/8/10)
$canBatal = in_array($row->ocm_status, [1, 6, 8, 10]);
$batal = $canBatal
? "<button
......
......@@ -67,7 +67,18 @@
<td>{{ $d->ocd_overtime_to ?? '-' }}</td>
<td>{{ $d->fk_lkp_project ? (\DB::table('lkp_project')->where('id', $d->fk_lkp_project)->value('p_project_description') ?? '-') : '-' }}</td>
<td class="td-left">{{ $d->ocd_tasks ?? '-' }}</td>
<td>@if($d->ocd_pm_reviewed)<span class="ui green label">Reviewed</span>@else<span class="ui orange label">Pending</span>@endif</td>
<td>
@php $isNoProject = ($d->fk_lkp_project == 110); @endphp
@if($isNoProject)
<span class="ui tiny blue label">Auto</span>
@else
@if($d->ocd_pm_reviewed)
<span class="ui green label">Reviewed</span>
@else
<span class="ui orange label">Pending</span>
@endif
@endif
</td>
<td><strong>{{ number_format($d->ocd_total_hours ?? 0, 1) }}</strong></td>
<td><strong>{{ number_format($d->ocd_effective_hours ?? 0, 1) }}</strong></td>
</tr>
......@@ -133,19 +144,21 @@
<tr>
<th style="width:180px;">From</th>
<th>Query Notes</th>
<th style="width:150px;">Query Date</th>
<th>Response</th>
<th style="width:150px;">Date</th>
<th style="width:150px;">Respond Date</th>
</thead>
<tbody>
@forelse($queryHistory ?? collect() as $q)
<tr>
<td>{{ \DB::table('users')->where('id', $q->fk_user_kueri)->value('name') ?? '-' }}</td>
<td>{{ $q->remarks ?: '-' }}</td>
<td>{{ $q->respond ?: '-' }}</td>
<td>{{ $q->tarikh ? \Carbon\Carbon::parse($q->tarikh)->format('d/m/Y H:i') : ($q->created_at ? $q->created_at->format('d/m/Y H:i') : '-') }}</td>
<td>{{ $q->respond ?: '-' }}</td>
<td>{{ $q->updated_at ? $q->updated_at->format('d/m/Y H:i') : '-' }}</td>
</tr>
@empty
<tr><td colspan="4" style="color:#999;font-style:italic;text-align:center;padding:1rem;">No query history found.</td></tr>
<tr><td colspan="5" style="color:#999;font-style:italic;text-align:center;padding:1rem;">No query history found.</td></tr>
@endforelse
</tbody>
</table>
......
......@@ -126,14 +126,24 @@
<td class="td-project {{ $d->pm_owned ? '' : 'td-disabled' }}">{{ $d->fk_lkp_project ? ($projectNames[$d->fk_lkp_project] ?? '-') : '-' }}</td>
<td class="td-tasks {{ $d->pm_owned ? '' : 'td-disabled' }}">{{ $d->ocd_tasks ?: '-' }}</td>
<td class="{{ $d->pm_owned ? '' : 'td-disabled' }}">
@if($d->pm_owned)
@if($d->ocd_pm_reviewed)
<span class="ui green label">Reviewed</span>
@php $isNoProject = ($d->fk_lkp_project == 110); @endphp
@if($isNoProject)
<span class="ui tiny blue label">Auto</span>
@else
@if($d->pm_owned)
@if($d->ocd_pm_reviewed)
<span class="ui green label">Reviewed</span>
@else
<span class="ui orange label">Pending</span>
@endif
@else
<span class="ui orange label">Pending</span>
{{-- Non-owned rows remain greyed out, but show Pending or Reviewed based on actual review flag --}}
@if($d->ocd_pm_reviewed)
<span class="ui green label">Reviewed</span>
@else
<span class="ui grey label">Pending</span>
@endif
@endif
@else
<span class="ui grey label">Restricted</span>
@endif
</td>
<td><strong>{{ number_format($d->ocd_total_hours ?? 0, 1) }}</strong></td>
......@@ -226,8 +236,8 @@
@endif
</div>
<div style="display: flex; justify-content: flex-end; margin-top: 1rem;">
<button type="button" class="ui teal button" id="btn-sokong" {{ $forms->isEmpty() ? 'disabled' : '' }}>
<div style="display: flex; justify-content: flex-end; margin-top: 1rem;">
<button type="button" class="ui teal button" id="btn-sokong" {{ $forms->isEmpty() || ($pmPendingCount ?? 0) === 0 ? 'disabled' : '' }}>
<i class="check icon"></i> Mark Reviewed
</button>
</div>
......@@ -261,8 +271,9 @@
<tr>
<th style="width:180px;">From</th>
<th>Query Notes</th>
<th style="width:150px;">Query Date</th>
<th>Response</th>
<th style="width:150px;">Date</th>
<th style="width:150px;">Respond Date</th>
</tr>
</thead>
<tbody>
......@@ -270,11 +281,12 @@
<tr>
<td>{{ \DB::table('users')->where('id', $q->fk_user_kueri)->value('name') ?? '-' }}</td>
<td>{{ $q->remarks ?: '-' }}</td>
<td>{{ $q->respond ?: '-' }}</td>
<td>{{ $q->tarikh ? \Carbon\Carbon::parse($q->tarikh)->format('d/m/Y H:i') : ($q->created_at ? $q->created_at->format('d/m/Y H:i') : '-') }}</td>
<td>{{ $q->respond ?: '-' }}</td>
<td>{{ $q->updated_at ? $q->updated_at->format('d/m/Y H:i') : '-' }}</td>
</tr>
@empty
<tr><td colspan="4" style="color:#999;font-style:italic;text-align:center;padding:1rem;">No query history found.</td></tr>
<tr><td colspan="5" style="color:#999;font-style:italic;text-align:center;padding:1rem;">No query history found.</td></tr>
@endforelse
</tbody>
</table>
......
......@@ -164,9 +164,12 @@ function vcmBuildHtml(main, details) {
+ '<td>' + vcmEsc(d.ocd_overtime_to || '-') + '</td>'
+ '<td>' + vcmEsc(d.project_name || '-') + '</td>'
+ '<td class="vm-left">' + vcmEsc(d.ocd_tasks || '-') + '</td>'
+ '<td>' + (d.ocd_pm_reviewed
? '<span class="ui green label">Reviewed</span>'
: '<span class="ui orange label">Pending</span>')
+ '<td>'
+ ((d.fk_lkp_project && String(d.fk_lkp_project) === '110') || (d.project_id && String(d.project_id) === '110')
? '<span class="ui tiny blue label">Auto</span>'
: (d.ocd_pm_reviewed
? '<span class="ui green label">Reviewed</span>'
: '<span class="ui orange label">Pending</span>'))
+ '</td>'
+ '<td><strong>' + totalHours.toFixed(1) + '</strong></td>'
+ '<td><strong>' + effectiveHours.toFixed(1) + '</strong></td>'
......
......@@ -93,10 +93,15 @@
<td>{{ $escape($detail['project_name'] ?? '-') }}</td>
<td class="vm-left">{{ $escape($detail['ocd_tasks'] ?? '-') }}</td>
<td>
@if (!empty($detail['ocd_pm_reviewed']))
<span class="ui green label">Reviewed</span>
@php $isNoProject = (!empty($detail['project_id']) && $detail['project_id'] == 110) || (!empty($detail['fk_lkp_project']) && $detail['fk_lkp_project'] == 110); @endphp
@if($isNoProject)
<span class="ui tiny blue label">Auto</span>
@else
<span class="ui orange label">Pending</span>
@if (!empty($detail['ocd_pm_reviewed']))
<span class="ui green label">Reviewed</span>
@else
<span class="ui orange label">Pending</span>
@endif
@endif
</td>
<td><strong>{{ number_format($totalHours, 1) }}</strong></td>
......
......@@ -155,8 +155,9 @@
<tr>
<th style="width:180px;">From</th>
<th>Query Notes</th>
<th style="width:150px;">Query Date</th>
<th>Response</th>
<th style="width:150px;">Date</th>
<th style="width:150px;">Respond Date</th>
</tr>
</thead>
<tbody>
......@@ -164,11 +165,12 @@
<tr>
<td>{{ \DB::table('users')->where('id', $q->fk_user_kueri)->value('name') ?? '-' }}</td>
<td>{{ $q->remarks ?: '-' }}</td>
<td>{{ $q->respond ?: '-' }}</td>
<td>{{ $q->tarikh ? \Carbon\Carbon::parse($q->tarikh)->format('d/m/Y H:i') : ($q->created_at ? $q->created_at->format('d/m/Y H:i') : '-') }}</td>
<td>{{ $q->respond ?: '-' }}</td>
<td>{{ $q->updated_at ? $q->updated_at->format('d/m/Y H:i') : '-' }}</td>
</tr>
@empty
<tr><td colspan="4" style="color:#999;font-style:italic;text-align:center;padding:1rem;">No query history found.</td></tr>
<tr><td colspan="5" style="color:#999;font-style:italic;text-align:center;padding:1rem;">No query history found.</td></tr>
@endforelse
</tbody>
</table>
......
......@@ -155,8 +155,9 @@
<tr>
<th style="width:180px;">From</th>
<th>Query Notes</th>
<th style="width:150px;">Query Date</th>
<th>Response</th>
<th style="width:150px;">Date</th>
<th style="width:150px;">Respond Date</th>
</tr>
</thead>
<tbody>
......@@ -164,11 +165,12 @@
<tr>
<td>{{ \DB::table('users')->where('id', $q->fk_user_kueri)->value('name') ?? '-' }}</td>
<td>{{ $q->remarks ?: '-' }}</td>
<td>{{ $q->respond ?: '-' }}</td>
<td>{{ $q->tarikh ? \Carbon\Carbon::parse($q->tarikh)->format('d/m/Y H:i') : ($q->created_at ? $q->created_at->format('d/m/Y H:i') : '-') }}</td>
<td>{{ $q->respond ?: '-' }}</td>
<td>{{ $q->updated_at ? $q->updated_at->format('d/m/Y H:i') : '-' }}</td>
</tr>
@empty
<tr><td colspan="4" style="color:#999;font-style:italic;text-align:center;padding:1rem;">No query history found.</td></tr>
<tr><td colspan="5" style="color:#999;font-style:italic;text-align:center;padding:1rem;">No query history found.</td></tr>
@endforelse
</tbody>
</table>
......
......@@ -33,6 +33,8 @@
$statusLabel = $statuses[$data->orm_status]->description ?? '-';
$queryType = in_array($data->orm_status, [8, 10]) ? ($data->orm_status == 8 ? 'HOD' : 'PD') : '';
$totalHours = $details->sum('ord_planned_ot_hour');
$requestMonth = $data->orm_date ? \Carbon\Carbon::parse($data->orm_date)->format('m') : '';
$requestYear = $data->orm_date ? \Carbon\Carbon::parse($data->orm_date)->format('Y') : '';
@endphp
<div class="rf-summary">
......@@ -61,6 +63,7 @@
<th>Planned OT Hours</th>
<th>Balance</th>
<th>Reason</th>
<th>Action</th>
</tr>
</thead>
<tbody id="rf-tbody">
......@@ -99,7 +102,7 @@
<select class="ui dropdown" id="ord_month">
<option value="">Month</option>
@foreach(['01'=>'January','02'=>'February','03'=>'March','04'=>'April','05'=>'May','06'=>'June','07'=>'July','08'=>'August','09'=>'September','10'=>'October','11'=>'November','12'=>'December'] as $monthValue => $monthLabel)
<option value="{{ $monthValue }}">{{ $monthLabel }}</option>
<option value="{{ $monthValue }}" {{ $requestMonth == $monthValue ? 'selected' : '' }}>{{ $monthLabel }}</option>
@endforeach
</select>
</div>
......@@ -107,7 +110,7 @@
<select class="ui dropdown" id="ord_year">
<option value="">Year</option>
@for($year = now()->year - 1; $year <= now()->year + 2; $year++)
<option value="{{ $year }}">{{ $year }}</option>
<option value="{{ $year }}" {{ $requestYear == $year ? 'selected' : '' }}>{{ $year }}</option>
@endfor
</select>
</div>
......@@ -140,8 +143,9 @@
<tr>
<th style="width:180px;">From</th>
<th>Query Notes</th>
<th style="width:150px;">Query Date</th>
<th>Response</th>
<th style="width:150px;">Date</th>
<th style="width:150px;">Respond Date</th>
</tr>
</thead>
<tbody>
......@@ -149,11 +153,12 @@
<tr>
<td>{{ \DB::table('users')->where('id', $q->fk_user_kueri)->value('name') ?? '-' }}</td>
<td>{{ $q->remarks ?: '-' }}</td>
<td>{{ $q->respond ?: '-' }}</td>
<td>{{ $q->tarikh ? \Carbon\Carbon::parse($q->tarikh)->format('d/m/Y H:i') : ($q->created_at ? $q->created_at->format('d/m/Y H:i') : '-') }}</td>
<td>{{ $q->respond ?: '-' }}</td>
<td>{{ $q->updated_at ? $q->updated_at->format('d/m/Y H:i') : '-' }}</td>
</tr>
@empty
<tr><td colspan="4" style="color:#999;font-style:italic;text-align:center;padding:1rem;">No query history found.</td></tr>
<tr><td colspan="5" style="color:#999;font-style:italic;text-align:center;padding:1rem;">No query history found.</td></tr>
@endforelse
</tbody>
</table>
......@@ -167,9 +172,9 @@
<div class="rf-footer">
<a href="{{ route('overtime::overtime.listovertimerequest') }}" class="ui grey button"><i class="arrow left icon"></i>Back</a>
<button type="button" class="ui grey button" onclick="saveDetails()"><i class="save icon"></i>Save Draft</button>
@if(in_array($data->orm_status, [0, 8, 10]))
<button type="button" class="ui teal button" onclick="submitRequestForm()"><i class="paper plane icon"></i>Submit</button>
<button type="button" class="ui grey button" id="btn-save-draft"><i class="save icon"></i>Save Draft</button>
@if(in_array($data->orm_status, [1, 8, 10]))
<button type="button" class="ui teal button" id="btn-submit"><i class="paper plane icon"></i>Submit</button>
@endif
</div>
</div>
......@@ -192,7 +197,9 @@ function bindEvents() {
$('#ord_balance').val((b - u).toFixed(2));
});
$('#btn-add-row').on('click', addRow);
$('#btn-reset').on('click', resetForm);
$('#btn-reset').on('click', resetRequestForm);
$('#btn-save-draft').on('click', saveRequestDetails);
$('#btn-submit').on('click', submitRequestForm);
}
function csrfToken() { return $('meta[name="csrf-token"]').attr('content'); }
......@@ -219,7 +226,7 @@ function renderTable() {
var keys = Object.keys(rows);
var tbody = $('#rf-tbody');
if (keys.length === 0) {
tbody.html('<tr class="empty-row"><td colspan="10">No entries yet. Use the form below to add one.</td></tr>');
tbody.html('<tr class="empty-row"><td colspan="9">No entries yet. Use the form below to add one.</td></tr>');
$('#grand-total').text('0.00');
return;
}
......@@ -276,7 +283,7 @@ function addRow() {
if (!res.success) { showError(res.message || 'Error while adding.'); return; }
rows[res.detail.id] = res.detail;
renderTable();
resetForm();
resetRequestForm();
showSuccess(res.message || 'Entry added.');
},
error: function (xhr) {
......@@ -304,13 +311,51 @@ function removeRow(id) {
});
}
function resetForm() {
function resetRequestForm() {
$('#ord_name, #ord_month, #ord_year').val('');
if ($.fn.dropdown) $('#ord_name, #ord_month, #ord_year').dropdown('clear');
$('#ord_budgeted, #ord_utilised_to_date, #ord_planned_ot_hour, #ord_balance').val('');
$('#ord_reason').val('');
}
function saveRequestDetails() {
var respondVal = $('#kueri_respond').val();
function doSave() {
$.ajax({
url: "{{ route('overtime::overtime.updateovertimerequest', $data->id) }}",
method: 'POST',
data: { _token: csrfToken() },
success: function (res) {
if (res.success) { showSuccess(res.message); setTimeout(function () { window.location.href = res.redirect || window.location.href; }, 1200); }
else { showError(res.message); }
},
error: function (xhr) {
var msg = 'Error while saving draft.';
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);
},
});
}
if ($('#kueri_respond').length && respondVal && respondVal.trim()) {
$.ajax({
url: "{{ route('overtime::overtime.savekueriresponddetail.request', $data->id) }}",
method: 'POST',
data: { _token: csrfToken(), respond: respondVal.trim() },
success: function () { doSave(); },
error: function (xhr) {
var msg = 'Error while saving response.';
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);
},
});
} else {
doSave();
}
}
function submitRequestForm() {
var respondVal = $('#kueri_respond').val();
function doSubmit() {
......
......@@ -58,8 +58,8 @@
<i class='eye icon'></i> View
</button>";
$canEdit = in_array($row->orm_status, [0, 8, 10]);
$canBatal = in_array($row->orm_status, [0, 8, 10]);
$canEdit = in_array($row->orm_status, [1, 8, 10]);
$canBatal = in_array($row->orm_status, [1, 8, 10]);
$edit = $canEdit
? "<a href='" . route('overtime::overtime.editovertimerequest', $row->id) . "'
......
......@@ -15,7 +15,7 @@ function () {
Route::get('index', ['uses' => 'OvertimeController@index', 'as' => 'overtime.index']);
// OT CLAIM - Staff
Route::middleware('can:' . Permission::APPLICATION_OT)->group(function () {
Route::middleware('can:' . Permission::CLAIM_OT)->group(function () {
Route::get('list', ['uses' => 'OvertimeClaimController@getListOvertimeClaim', 'as' => 'overtime.listovertime']);
Route::get('claim/create', ['uses' => 'OvertimeClaimController@createOvertimeClaim', 'as' => 'overtime.createovertimeclaim']);
Route::post('claim/store', ['uses' => 'OvertimeClaimController@storeOvertimeClaim', 'as' => 'overtime.storeovertimeclaim']);
......@@ -35,7 +35,7 @@ function () {
});
// OT CLAIM - Project Manager (PM)
Route::middleware('can:' . Permission::APPLICATION_OT_REVIEW)->group(function () {
Route::middleware('can:' . Permission::CLAIM_OT_PM)->group(function () {
Route::get('claim/{id}/pm-view', ['uses' => 'OvertimeProjectManagerController@viewClaim', 'as' => 'overtime.pmviewclaim']);
Route::post('claim/{id}/pm-mark-reviewed', ['uses' => 'OvertimeProjectManagerController@markReviewed', 'as' => 'overtime.pmmarkreviewed']);
Route::post('claim/{id}/sokong', ['uses' => 'OvertimeProjectManagerController@sokongClaim', 'as' => 'overtime.pmsokongclaim']);
......@@ -44,7 +44,7 @@ function () {
});
// OT CLAIM - Head of Department (HOD)
Route::middleware('can:' . Permission::APPLICATION_OT_SUPPORT)->group(function () {
Route::middleware('can:' . Permission::CLAIM_OT_HOD)->group(function () {
Route::get('claim/hod/list', ['uses' => 'OvertimeClaimHodController@getHodReviewList', 'as' => 'overtime.hodclaimreviewlist']);
Route::get('claim/hod/{id}/view', ['uses' => 'OvertimeClaimHodController@viewClaim', 'as' => 'overtime.hodviewclaim']);
Route::post('claim/hod/{id}/sokong', ['uses' => 'OvertimeClaimHodController@sokongClaim', 'as' => 'overtime.hodsokongclaim']);
......@@ -52,7 +52,7 @@ function () {
});
// OT CLAIM - Project Director (PD)
Route::middleware('can:' . Permission::APPLICATION_OT_APPROVE)->group(function () {
Route::middleware('can:' . Permission::CLAIM_OT_PD)->group(function () {
Route::get('claim/pd/list', ['uses' => 'OvertimeClaimPdController@getPdReviewList', 'as' => 'overtime.pdclaimreviewlist']);
Route::get('claim/pd/{id}/view', ['uses' => 'OvertimeClaimPdController@viewClaim', 'as' => 'overtime.pdviewclaim']);
Route::post('claim/pd/{id}/sokong', ['uses' => 'OvertimeClaimPdController@sokongClaim', 'as' => 'overtime.pdsokongclaim']);
......@@ -60,7 +60,7 @@ function () {
});
// OT REQUEST - Project Manager (PM)
Route::middleware('can:' . Permission::REQUEST_OT)->group(function () {
Route::middleware('can:' . Permission::REQUEST_OT_PM)->group(function () {
Route::get('request/list', ['uses' => 'OvertimeRequestController@getListOvertimeRequest', 'as' => 'overtime.listovertimerequest']);
Route::get('request/create', ['uses' => 'OvertimeRequestController@createOvertimeRequest', 'as' => 'overtime.createovertimerequest']);
Route::get('request/existing-projects', ['uses' => 'OvertimeRequestController@getExistingProjects', 'as' => 'overtime.existingprojects']);
......@@ -79,7 +79,7 @@ function () {
});
// OT REQUEST - Head of Department (HOD)
Route::middleware('can:' . Permission::APPLICATION_OT_HOD)->group(function () {
Route::middleware('can:' . Permission::REQUEST_OT_HOD)->group(function () {
Route::get('request/hod/list', ['uses' => 'OvertimeHodController@getReviewList', 'as' => 'overtime.hodreviewlist']);
Route::get('request/hod/{id}/view', ['uses' => 'OvertimeHodController@viewRequestForm', 'as' => 'overtime.hodviewrequest']);
Route::post('request/hod/{id}/approve', ['uses' => 'OvertimeHodController@approveRequestForm', 'as' => 'overtime.hodapproverequest']);
......@@ -88,7 +88,7 @@ function () {
});
// OT REQUEST - Project Director (PD)
Route::middleware('can:' . Permission::APPLICATION_OT_PD)->group(function () {
Route::middleware('can:' . Permission::REQUEST_OT_PD)->group(function () {
Route::get('request/pd/list', ['uses' => 'OvertimePdController@getReviewList', 'as' => 'overtime.pdreviewlist']);
Route::get('request/pd/{id}/view', ['uses' => 'OvertimePdController@viewRequestForm', 'as' => 'overtime.pdviewrequest']);
Route::post('request/pd/{id}/approve', ['uses' => 'OvertimePdController@approveRequestForm', 'as' => 'overtime.pdapproverequest']);
......
......@@ -12,6 +12,8 @@
class OvertimeClaimHodRepo
{
private const NO_PROJECT_ID = 110;
// =========================================================================
// STATUSES
// =========================================================================
......@@ -33,6 +35,11 @@ private function currentHodDepartmentId(): ?int
->value('fk_lkp_department');
}
private function currentHodUserId(): ?int
{
return (int) Auth::id();
}
// =========================================================================
// HOD REVIEW LIST — status 7 is set by HOD itself, so the inbox is
......@@ -41,17 +48,25 @@ private function currentHodDepartmentId(): ?int
public function getHodReviewList($request)
{
$search = $request->get('search');
$currentHod = $this->currentHodUserId();
return OvertimeClaimMain::where('ocm_status', 5)
// Only show claims that are in HOD queue and belong to applicants
// whose staff_info.penyokong matches the current HOD.
$query = OvertimeClaimMain::where('ocm_status', 5)
->whereNull('deleted_at')
->where(function ($q) use ($search) {
$q->where('ocm_apply_no', 'like', "%{$search}%")
->orWhere('ocm_staff_name', 'like', "%{$search}%");
})
->orderBy('created_at', 'desc')
->paginate(10);
->whereIn('fk_lkp_staff_info', function ($sub) use ($currentHod) {
$sub->select('id')
->from('staff_info')
->where('penyokong', $currentHod);
});
return $query->orderBy('created_at', 'desc')->paginate(10);
}
// =========================================================================
......@@ -66,6 +81,15 @@ public function findClaim(int $id): OvertimeClaimMain
throw new AuthorizationException('Unauthorized claim access.');
}
// Ensure this HOD is the applicant's penyokong
$penyokong = DB::table('staff_info')
->where('id', $claim->fk_lkp_staff_info)
->value('penyokong');
if ($penyokong === null || (int) $penyokong !== $this->currentHodUserId()) {
throw new AuthorizationException('Unauthorized claim access.');
}
return $claim;
}
......@@ -81,6 +105,10 @@ public function countPendingPmReviews(int $claimId): int
{
return OvertimeClaimDetail::where('fk_overtime_claim_main', $claimId)
->where('ocd_pm_reviewed', 0)
->where(function ($q) {
$q->whereNull('fk_lkp_project')
->orWhere('fk_lkp_project', '!=', self::NO_PROJECT_ID);
})
->count();
}
......@@ -138,7 +166,7 @@ public function kueriClaim($request, int $claimId): OvertimeClaimMain
$claim->update([
'ocm_status' => 8, // Dikueri Oleh HOD
'kueri_status' => 1,
'ocm_query_status' => 1,
'updated_by' => Auth::id(),
]);
......@@ -151,7 +179,7 @@ public function kueriClaim($request, int $claimId): OvertimeClaimMain
'tarikh' => now(),
]);
$this->logAudit('UPDATE', $claim->id, null,
$this->logAudit('QUERY', $claim->id, null,
"queried claim {$claim->ocm_apply_no} and sent it back to the applicant.");
return $claim;
......
......@@ -4,6 +4,7 @@
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Auth\Access\AuthorizationException;
use Portal\Overtime\Model\OvertimeAuditQuery;
use Portal\Overtime\Model\OvertimeAuditTrail;
......@@ -12,6 +13,8 @@
class OvertimeClaimPdRepo
{
private const NO_PROJECT_ID = 110;
// =========================================================================
// STATUSES
// =========================================================================
......@@ -26,6 +29,67 @@ public function getOtStatuses(): \Illuminate\Support\Collection
->keyBy('ref_id');
}
// Helpers to determine current PD's projects (ids and names)
private function currentStaffId(): ?string
{
return DB::table('staff_info')
->where('fk_users', Auth::id())
->value('staff_id');
}
private function currentPdUserId(): int
{
return (int) Auth::id();
}
private function projectTeamProjectColumn(): string
{
if (Schema::hasColumn('project_team', 'pt_project_id')) {
return 'pt_project_id';
}
return 'fk_project_id';
}
private function currentPdProjectIds(): \Illuminate\Support\Collection
{
$staffId = $this->currentStaffId();
if (! $staffId) {
return collect();
}
$projectColumn = $this->projectTeamProjectColumn();
return DB::table('project_team')
->where('pt_staff_id', $staffId)
->where('role_id', 7)
->pluck($projectColumn)
->filter()
->unique()
->values();
}
private function currentPdProjectNames(): \Illuminate\Support\Collection
{
$staffId = $this->currentStaffId();
if (! $staffId || ! Schema::hasColumn('project_team', 'pt_project_description')) {
return collect();
}
return DB::table('project_team')
->where('pt_staff_id', $staffId)
->where('role_id', 7)
->pluck('pt_project_description')
->filter(function ($name) {
return trim((string) $name) !== '';
})
->map(function ($name) {
return trim((string) $name);
})
->unique()
->values();
}
// =========================================================================
// PD REVIEW LIST — claims sokong'd by HOD (status 7) waiting for PD action
// =========================================================================
......@@ -33,11 +97,61 @@ public function getOtStatuses(): \Illuminate\Support\Collection
public function getPdReviewList($request)
{
$search = $request->get('search');
$pdProjectIds = $this->currentPdProjectIds();
$pdProjectNames = $this->currentPdProjectNames();
$currentPdUserId = $this->currentPdUserId();
return OvertimeClaimMain::where('ocm_status', 7)
->where(function ($q) use ($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) {
// Primary path: claim has at least one detail row in PD's project scope.
if (!$pdProjectIds->isEmpty() || !$pdProjectNames->isEmpty()) {
$q->whereExists(function ($sub) use ($pdProjectIds, $pdProjectNames) {
$sub->select(DB::raw('1'))
->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')
->paginate(10);
......@@ -55,7 +169,57 @@ public function findClaim(int $id): OvertimeClaimMain
throw new AuthorizationException('Unauthorized claim access.');
}
return $claim;
// Ensure claim's projects match current PD's ownership/membership by
// 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('pelulus', $this->currentPdUserId())
->exists();
if ($fallbackEligible) {
$hasNoProject = DB::table('overtime_claim_detail')
->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.');
}
public function findClaimDetails(int $id)
......@@ -116,7 +280,7 @@ public function kueriClaim($request, int $claimId): OvertimeClaimMain
$claim->update([
'ocm_status' => 10, // Dikueri Oleh BOD/PD
'kueri_status' => 1,
'ocm_query_status' => 1,
'updated_by' => Auth::id(),
]);
......@@ -129,7 +293,7 @@ public function kueriClaim($request, int $claimId): OvertimeClaimMain
'tarikh' => now(),
]);
$this->logAudit('UPDATE', $claim->id, null,
$this->logAudit('QUERY', $claim->id, null,
"queried claim {$claim->ocm_apply_no} and sent it back to the applicant.");
return $claim;
......
......@@ -36,18 +36,52 @@ private function mapAttendanceDayType(?int $attendanceDayType): ?string
{
return match ($attendanceDayType) {
1 => 'Hari Bekerja',
2 => 'Hari Rehat',
3 => 'Cuti Umum',
2 => 'Hari Minggu',
3 => 'Hari Cuti Umum',
4 => 'Hari Cuti Selain Cuti Umum',
default => null,
};
}
private function mapAttendanceStatus(?int $attendanceStatus): ?string
{
return match ($attendanceStatus) {
1 => 'Hadir',
2 => 'Cuti',
3 => 'Latihan',
4 => 'Public Holiday',
5 => 'Hari Minggu',
6 => 'Urusan Rasmi',
default => null,
};
}
private function buildAttendanceDayTypeLabel(?int $attendanceDayType, ?int $attendanceStatus): ?string
{
$dayTypeLabel = $this->mapAttendanceDayType($attendanceDayType);
if ($dayTypeLabel === null) {
return null;
}
$statusLabel = $this->mapAttendanceStatus($attendanceStatus);
if ($statusLabel === null) {
return $dayTypeLabel;
}
if ($statusLabel === $dayTypeLabel) {
return $dayTypeLabel;
}
return $dayTypeLabel . ' (' . $statusLabel . ')';
}
private function mapDayTypeCodeToLabel($dayTypeCode): ?string
{
return match ((string) $dayTypeCode) {
'1' => 'Hari Bekerja',
'2' => 'Hari Rehat',
'3' => 'Cuti Umum',
'2' => 'Hari Minggu',
'3' => 'Hari Cuti Umum',
'4' => 'Hari Cuti Selain Cuti Umum',
default => null,
};
}
......@@ -69,15 +103,20 @@ public function getAttendanceByDate(string $date): ?array
return null;
}
$dayType = $this->mapAttendanceDayType(
isset($attendance->fk_lkp_day_type) ? (int) $attendance->fk_lkp_day_type : null
$attendanceDayType = isset($attendance->fk_lkp_day_type) ? (int) $attendance->fk_lkp_day_type : null;
$attendanceStatus = isset($attendance->attendance_status) ? (int) $attendance->attendance_status : null;
$dayType = $this->buildAttendanceDayTypeLabel(
$attendanceDayType,
$attendanceStatus
);
return [
'time_in' => $attendance->time_in,
'time_out_flexi' => $attendance->time_out_flexi,
'time_out' => $attendance->time_out,
'fk_lkp_day_type' => isset($attendance->fk_lkp_day_type) ? (int) $attendance->fk_lkp_day_type : null,
'fk_lkp_day_type' => $attendanceDayType,
'attendance_status' => $attendanceStatus,
'day_type' => $dayType,
];
}
......@@ -177,13 +216,21 @@ public function addOvertimeClaimDetail(int $id, $request): OvertimeClaimDetail
? $request->ocd_office_start . ' – ' . ($request->ocd_office_end ?? '?')
: null;
$attendanceDayType = DB::table('attendance')
$attendance = DB::table('attendance')
->where('fk_staff_info', $this->currentStaffInfoId())
->whereDate('date', $request->ocd_date)
->value('fk_lkp_day_type');
->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->mapAttendanceDayType(
$attendanceDayType !== null ? (int) $attendanceDayType : null
$resolvedDayType = $this->buildAttendanceDayTypeLabel(
$attendanceDayType,
$attendanceStatus
) ?? $this->mapDayTypeCodeToLabel($request->ocd_day_type) ?? $request->ocd_day_type;
$payload = [
......@@ -279,15 +326,55 @@ public function submitOvertimeClaim($request, int $id): OvertimeClaimMain
throw new \Exception('Please add at least one overtime claim day.');
}
$isResubmission = $record->ocm_status == 6 && $record->ocm_query_status == 1;
$isResubmission = in_array((int) $record->ocm_status, [6, 8, 10], true) && (int) $record->ocm_query_status === 1;
$newStatus = $isResubmission ? 3 : 2;
OvertimeClaimDetail::where('fk_overtime_claim_main', $id)
->update([
'ocd_pm_reviewed' => 0,
'ocd_pm_reviewed_by' => null,
'ocd_pm_reviewed_at' => null,
]);
// If all detail rows belong to the dedicated "No Project" entry,
// bypass PM review and route directly to HOD. The No Project id
// has been created already (id = 110) and we use that literal
// here per the user's request (no new seeder/files).
$NO_PROJECT_ID = 110;
$detailProjects = OvertimeClaimDetail::where('fk_overtime_claim_main', $id)
->pluck('fk_lkp_project')
->map(fn ($v) => $v === null ? null : (int) $v)
->toArray();
$allNoProject = true;
foreach ($detailProjects as $p) {
if ($p !== $NO_PROJECT_ID) {
$allNoProject = false;
break;
}
}
// 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
// and send straight to HOD (status 5).
if (!$isResubmission) {
if ($allNoProject) {
OvertimeClaimDetail::where('fk_overtime_claim_main', $id)
->update([
'ocd_pm_reviewed' => 1,
'ocd_pm_reviewed_by' => Auth::id(),
'ocd_pm_reviewed_at' => now(),
]);
$newStatus = 5; // Disemak oleh PM (treated as already reviewed -> HOD inbox)
} else {
OvertimeClaimDetail::where('fk_overtime_claim_main', $id)
->update([
'ocd_pm_reviewed' => 0,
'ocd_pm_reviewed_by' => null,
'ocd_pm_reviewed_at' => null,
]);
}
} else {
// Resubmission: if all details are No Project, ensure routing goes to HOD
if ($allNoProject) {
$newStatus = 5;
}
}
$record->update([
'ocm_status' => $newStatus,
......@@ -344,54 +431,18 @@ public function getAuditTrail(string $taskCode, int $claimId, ?int $detailId = n
]);
}
// AUDIT TRAIL LIST (for viewing)
public function getAuditTrailList($request)
{
$search = $request->get('search');
return \Portal\Overtime\Model\OvertimeAuditTrail::with(['claim', 'task'])
->when($search, function ($q) use ($search) {
$q->whereHas('claim', function ($q2) use ($search) {
$q2->where('ocm_apply_no', 'like', "%{$search}%");
});
})
->orderBy('created_at', 'desc')
->paginate(15);
}
// =========================================================================
// BATAL (cancel - allowed only from Draft=1 or Queried by PM=6)
// =========================================================================
public function batalOvertimeClaim(int $id): OvertimeClaimMain
{
$record = $this->findOvertimeClaim($id);
if (!in_array($record->ocm_status, [1, 6])) {
throw new \Exception('The claim cannot be cancelled in its current status.');
}
$record->update([
'ocm_status' => 4, // Cancelled claim
'updated_by' => Auth::id(),
]);
$this->getAuditTrail('UPDATE', $id, null, 'Claim cancelled by the applicant.');
return $record;
}
// =========================================================================
// SAVE QUERY RESPONSE (applicant responding to PM's query remark)
// SAVE QUERY RESPONSE (applicant responding to PM/HOD/PD query remark)
// =========================================================================
public function saveKueriRespond(int $claimId, string $respond): void
{
$record = $this->findOvertimeClaim($claimId);
if (!in_array((int) $record->ocm_status, [6, 8, 10], true)) {
throw new \Exception('This claim is not in query status.');
}
$query = \Portal\Overtime\Model\OvertimeAuditQuery::where('fk_main', $record->id)
->where('no_permohonan', $record->ocm_apply_no)
->orderBy('created_at', 'desc')
......
......@@ -5,7 +5,6 @@
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Portal\Overtime\Model\OvertimeAuditQuery;
use Portal\Overtime\Model\OvertimeAuditTrail;
use Portal\Overtime\Model\OvertimeRequestMain;
......@@ -13,53 +12,52 @@
class OvertimeHodRepo
{
private function currentStaffId(): ?string
private function currentHodUserId(): int
{
return DB::table('staff_info')
->where('fk_users', Auth::id())
->value('staff_id');
return (int) Auth::id();
}
private function currentHodDepartmentId(): ?int
private function resolveApplicantUserId(OvertimeRequestMain $record): ?int
{
$staffId = $this->currentStaffId();
if (!$staffId) {
return null;
if (!empty($record->orm_name) && is_numeric((string) $record->orm_name)) {
return (int) $record->orm_name;
}
return DB::table('staff_info')
->where('staff_id', $staffId)
->value('fk_lkp_department');
}
if (!empty($record->orm_requested_by_id)) {
$staffId = DB::table('project_team')
->where('id', $record->orm_requested_by_id)
->value('pt_staff_id');
private function projectTeamProjectColumn(): string
{
if (Schema::hasColumn('project_team', 'pt_project_id')) {
return 'pt_project_id';
if ($staffId) {
$applicantUserId = DB::table('staff_info')
->where('staff_id', $staffId)
->value('fk_users');
if ($applicantUserId && is_numeric((string) $applicantUserId)) {
return (int) $applicantUserId;
}
}
}
return 'fk_project_id';
return null;
}
private function currentHodProjectIds(): \Illuminate\Support\Collection
private function resolveApplicantHodUserId(OvertimeRequestMain $record): ?int
{
$departmentId = $this->currentHodDepartmentId();
if (!$departmentId) {
return collect();
$applicantUserId = $this->resolveApplicantUserId($record);
if (!$applicantUserId) {
return null;
}
$projectColumn = $this->projectTeamProjectColumn();
$hodUserId = DB::table('staff_info')
->where('fk_users', $applicantUserId)
->value('penyokong');
return DB::table('project_team as pt')
->join('staff_info as si', 'si.staff_id', '=', 'pt.pt_staff_id')
->where('si.fk_lkp_department', $departmentId)
->whereNotNull("pt.{$projectColumn}")
->select("pt.{$projectColumn} as project_id")
->distinct()
->pluck('project_id')
->filter()
->unique()
->values();
if ($hodUserId === null || $hodUserId === '' || !is_numeric((string) $hodUserId)) {
return null;
}
return (int) $hodUserId;
}
public function getOtStatuses(): \Illuminate\Support\Collection
......@@ -74,9 +72,8 @@ public function getOtStatuses(): \Illuminate\Support\Collection
private function authorizeHodRequestAccess(OvertimeRequestMain $record, ?array $allowedStatuses = null): void
{
$projectIds = $this->currentHodProjectIds();
if ($projectIds->isEmpty() || !$projectIds->contains($record->orm_project)) {
$hodUserId = $this->resolveApplicantHodUserId($record);
if ($hodUserId === null || $hodUserId !== $this->currentHodUserId()) {
throw new AuthorizationException('Unauthorized request access.');
}
......@@ -92,18 +89,29 @@ private function authorizeHodRequestAccess(OvertimeRequestMain $record, ?array $
public function getReviewList($request)
{
$search = $request->get('search', '');
$projectIds = $this->currentHodProjectIds();
$query = OvertimeRequestMain::where('orm_status', 2)
->whereNull('deleted_at')
->when($search, fn ($q) => $q->where('orm_apply_no', 'like', "%{$search}%"));
if ($projectIds->isEmpty()) {
return $query->whereRaw('0 = 1')->orderBy('created_at', 'desc')->paginate(10);
}
return $query->whereIn('orm_project', $projectIds)
->orderBy('created_at', 'desc')
return OvertimeRequestMain::query()
->from('overtime_request_main as orm')
->leftJoin('project_team as pt', 'pt.id', '=', 'orm.orm_requested_by_id')
->leftJoin('staff_info as si', 'si.staff_id', '=', 'pt.pt_staff_id')
->where('orm.orm_status', 2)
->whereNull('orm.deleted_at')
->where(function ($q) {
$q->where('si.penyokong', $this->currentHodUserId())
->orWhere(function ($fallback) {
$fallback->whereNull('orm.orm_requested_by_id')
->whereIn('orm.orm_name', function ($sub) {
$sub->select('fk_users')
->from('staff_info')
->whereNotNull('fk_users')
->where('penyokong', $this->currentHodUserId());
});
});
})
->when($search, fn ($q) => $q->where('orm.orm_apply_no', 'like', "%{$search}%"))
->select('orm.*')
->distinct()
->orderBy('orm.created_at', 'desc')
->paginate(10);
}
......@@ -193,7 +201,7 @@ public function kueriRequestForm(int $id, string $remark): OvertimeRequestMain
]);
// Audit trail: HOD kueri
$this->logAuditTrail('KUERI', $record->id, null, 'Request form queried by HOD.');
$this->logAuditTrail('QUERY', $record->id, null, 'Request form queried by HOD.');
return $record;
}
......@@ -241,6 +249,8 @@ private function logAuditTrail(string $taskCode, int $requestId, ?int $detailId
OvertimeAuditTrail::create([
'fk_overtime_claim_main' => null,
'fk_overtime_claim_detail' => null,
'fk_overtime_request_main' => $requestId,
'fk_overtime_request_detail' => $detailId,
'fk_lkp_overtime_task' => $taskId,
'user' => Auth::id(),
'description' => $description,
......
......@@ -5,6 +5,7 @@
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Portal\Overtime\Model\OvertimeAuditQuery;
use Portal\Overtime\Model\OvertimeAuditTrail;
use Portal\Overtime\Model\OvertimeRequestMain;
......@@ -12,6 +13,80 @@
class OvertimePdRepo
{
private function currentStaffId(): ?string
{
return DB::table('staff_info')
->where('fk_users', Auth::id())
->value('staff_id');
}
private function projectTeamProjectColumn(): string
{
if (Schema::hasColumn('project_team', 'pt_project_id')) {
return 'pt_project_id';
}
return 'fk_project_id';
}
private function currentPdProjectIds(): \Illuminate\Support\Collection
{
$staffId = $this->currentStaffId();
if (!$staffId) {
return collect();
}
$projectColumn = $this->projectTeamProjectColumn();
return DB::table('project_team')
->where('pt_staff_id', $staffId)
->where('role_id', 7)
->pluck($projectColumn)
->filter()
->unique()
->values();
}
private function currentPdProjectNames(): \Illuminate\Support\Collection
{
$staffId = $this->currentStaffId();
if (!$staffId || !Schema::hasColumn('project_team', 'pt_project_description')) {
return collect();
}
return DB::table('project_team')
->where('pt_staff_id', $staffId)
->where('role_id', 7)
->pluck('pt_project_description')
->filter(function ($name) {
return trim((string) $name) !== '';
})
->map(function ($name) {
return trim((string) $name);
})
->unique()
->values();
}
private function requestBelongsToCurrentPd(OvertimeRequestMain $record): bool
{
$pdProjectIds = $this->currentPdProjectIds();
if (!$pdProjectIds->isEmpty() && $pdProjectIds->contains((int) $record->orm_project)) {
return true;
}
$projectName = DB::table('lkp_project')
->where('id', $record->orm_project)
->value('p_project_description');
if (!$projectName) {
return false;
}
$pdProjectNames = $this->currentPdProjectNames();
return $pdProjectNames->contains(trim((string) $projectName));
}
public function getOtStatuses(): \Illuminate\Support\Collection
{
return DB::table('lkp_status')
......@@ -24,6 +99,10 @@ public function getOtStatuses(): \Illuminate\Support\Collection
private function authorizePdRequestAccess(OvertimeRequestMain $record, ?array $allowedStatuses = null): void
{
if (!$this->requestBelongsToCurrentPd($record)) {
throw new AuthorizationException('Unauthorized request access.');
}
if (!in_array((int) $record->orm_status, [7, 9, 10, 11], true)) {
throw new AuthorizationException('Unauthorized request access.');
}
......@@ -41,8 +120,28 @@ public function getReviewList($request)
{
$search = $request->get('search', '');
$pdProjectIds = $this->currentPdProjectIds();
$pdProjectNames = $this->currentPdProjectNames();
if ($pdProjectIds->isEmpty() && $pdProjectNames->isEmpty()) {
return OvertimeRequestMain::whereRaw('0 = 1')->paginate(10);
}
return OvertimeRequestMain::whereIn('orm_status', [7, 11])
->whereNull('deleted_at')
->where(function ($q) use ($pdProjectIds, $pdProjectNames) {
if (!$pdProjectIds->isEmpty()) {
$q->whereIn('orm_project', $pdProjectIds->all());
}
if (!$pdProjectNames->isEmpty()) {
$q->orWhereIn('orm_project', function ($sub) use ($pdProjectNames) {
$sub->select('id')
->from('lkp_project')
->whereIn('p_project_description', $pdProjectNames->all());
});
}
})
->when($search, fn ($q) => $q->where('orm_apply_no', 'like', "%{$search}%"))
->orderBy('created_at', 'desc')
->paginate(10);
......@@ -78,11 +177,6 @@ public function findQueryHistory(int $id)
->orderBy('created_at', 'desc')
->get();
}
// =========================================================================
// APPROVE → status 11 (Permohonan Diluluskan — stays in PD list, visible in Sokong picker)
// =========================================================================
public function approveRequestForm(int $id): OvertimeRequestMain
{
$record = $this->findRequestForm($id);
......@@ -136,7 +230,7 @@ public function kueriRequestForm(int $id, string $remark): OvertimeRequestMain
]);
// Audit trail: PD kueri
$this->logAuditTrail('KUERI', $record->id, null, 'Request form queried by PD.');
$this->logAuditTrail('QUERY', $record->id, null, 'Request form queried by PD.');
return $record;
}
......@@ -188,6 +282,8 @@ private function logAuditTrail(string $taskCode, int $requestId, ?int $detailId
OvertimeAuditTrail::create([
'fk_overtime_claim_main' => null,
'fk_overtime_claim_detail' => null,
'fk_overtime_request_main' => $requestId,
'fk_overtime_request_detail' => $detailId,
'fk_lkp_overtime_task' => $taskId,
'user' => Auth::id(),
'description' => $description,
......
......@@ -13,6 +13,8 @@
class OvertimeProjectManagerRepo
{
private const NO_PROJECT_ID = 110;
// =========================================================================
// HELPERS
// =========================================================================
......@@ -99,11 +101,13 @@ public function getProjectManagerReviewList($request)
{
$search = $request->get('search');
// Return all pending claims (status 2 or 3) that have details
// requiring PM review. Do NOT filter by PM-owned projects here;
// the view will decide which actions are enabled or disabled.
$projectIds = $this->currentPmProjectIds();
$query = OvertimeClaimMain::with('details')
->whereIn('ocm_status', [2, 3]);
->whereIn('ocm_status', [2, 3])
->whereHas('details', function ($q) use ($projectIds) {
$q->where('ocd_pm_reviewed', 0)
->whereIn('fk_lkp_project', $projectIds->all());
});
if ($search) {
$query->where(function ($q) use ($search) {
......@@ -185,10 +189,11 @@ public function getApprovedRequestFormsForCurrentPm(?OvertimeClaimMain $claim =
$form->request_staff_names = $this->getRequestFormStaffNames((int) $form->id);
$form->request_staff_name = $form->request_staff_names->first();
$form->is_pm_project = $projectIds->contains($form->orm_project);
$form->display_label = implode(' - ', array_filter([
$form->project_name,
$form->orm_apply_no,
], static fn ($value) => $value !== null && $value !== ''));
$form->display_label = trim(implode(' - ', array_filter([
// Desired format: "project name (request form number) - month/year"
($form->project_name ? ($form->project_name . ' (' . $form->orm_apply_no . ')') : $form->orm_apply_no),
$form->request_month_year,
], static fn ($value) => $value !== null && $value !== '')));
}
return $forms;
......@@ -348,20 +353,32 @@ public function markClaimReviewed(int $id, int $requestFormId): OvertimeClaimMai
}
}
$updatedRows = OvertimeClaimDetail::where('fk_overtime_claim_main', $id)
$projectRowsCount = OvertimeClaimDetail::where('fk_overtime_claim_main', $id)
->where('fk_lkp_project', $requestForm->orm_project)
->count();
if ($projectRowsCount === 0) {
throw new \Exception('Tiada baris tuntutan untuk projek anda dijumpai pada permohonan ini.');
}
// Only update rows that are not yet marked reviewed. Make this
// operation idempotent so calling it when all rows are already
// reviewed does not result in an error.
OvertimeClaimDetail::where('fk_overtime_claim_main', $id)
->where('fk_lkp_project', $requestForm->orm_project)
->where('ocd_pm_reviewed', 0)
->update([
'ocd_pm_reviewed' => 1,
'ocd_pm_reviewed_by' => Auth::id(),
'ocd_pm_reviewed_at' => now(),
]);
if ($updatedRows === 0) {
throw new \Exception('Tiada baris tuntutan untuk projek anda dijumpai pada permohonan ini.');
}
$pendingCount = OvertimeClaimDetail::where('fk_overtime_claim_main', $id)
->where('ocd_pm_reviewed', 0)
->where(function ($q) {
$q->whereNull('fk_lkp_project')
->orWhere('fk_lkp_project', '!=', self::NO_PROJECT_ID);
})
->count();
if ($pendingCount === 0) {
......@@ -402,7 +419,7 @@ public function kueriClaim(int $id, string $remarks): OvertimeClaimMain
'tarikh' => now(),
]);
$this->logAuditTrail('KUERI', $id, null, 'Permohonan dikueri balik kepada pemohon.');
$this->logAuditTrail('QUERY', $id, null, 'Permohonan dikueri balik kepada pemohon.');
return $record;
}
......
......@@ -27,10 +27,10 @@ public function getOtStatuses(): \Illuminate\Support\Collection
->get()
->keyBy('ref_id');
if (!$statuses->has(0)) {
$statuses->put(0, (object) [
if (!$statuses->has(1)) {
$statuses->put(1, (object) [
'module' => 'ot',
'ref_id' => 0,
'ref_id' => 1,
'description' => 'Draf',
'status' => 1,
]);
......@@ -303,7 +303,7 @@ public function storeRequestForm($request): OvertimeRequestMain
'orm_position' => $team->role_id ?? null,
'orm_project' => $request->orm_project,
'orm_department' => $staffInfo->fk_lkp_department ?? null,
'orm_status' => 0, // pending HR approval
'orm_status' => 1, // Draf
'orm_requested_by_id' => $teamId,
'orm_requested_date' => now(),
'updated_by' => Auth::id(),
......@@ -325,7 +325,7 @@ public function storeRequestForm($request): OvertimeRequestMain
public function updateRequestForm($request, int $id): OvertimeRequestMain
{
$record = $this->findRequestForm($id);
$this->authorizePmRequestAccess($record, [0, 8, 10]);
$this->authorizePmRequestAccess($record, [1, 8, 10]);
$staffInfo = $this->currentStaffInfo();
$teamId = $this->currentProjectTeamId((int) $record->orm_project);
$team = $teamId ? DB::table('project_team')->where('id', $teamId)->first() : null;
......@@ -351,9 +351,9 @@ public function updateRequestForm($request, int $id): OvertimeRequestMain
public function batalRequestForm(int $id): OvertimeRequestMain
{
$record = $this->findRequestForm($id);
$this->authorizePmRequestAccess($record, [0]);
$this->authorizePmRequestAccess($record, [1]);
if ($record->orm_status != 0) {
if ($record->orm_status != 1) {
throw new \Exception('The request form cannot be cancelled in its current status.');
}
......@@ -375,7 +375,7 @@ public function batalRequestForm(int $id): OvertimeRequestMain
public function deleteRequestForm(int $id): void
{
$record = $this->findRequestForm($id);
$this->authorizePmRequestAccess($record, [0]);
$this->authorizePmRequestAccess($record, [1]);
OvertimeRequestDetail::where('fk_overtime_request_main', $id)->delete();
$record->update(['deleted_at' => now()]);
......@@ -391,7 +391,7 @@ public function deleteRequestForm(int $id): void
public function addRequestFormDetail(int $mainId, $request): OvertimeRequestDetail
{
$record = $this->findRequestForm($mainId);
$this->authorizePmRequestAccess($record, [0, 8, 10]);
$this->authorizePmRequestAccess($record, [1, 8, 10]);
$staffUserId = $this->resolveProjectStaffIdByName((int) $record->orm_project, (string) $request->ord_name);
if (!$staffUserId) {
......@@ -425,7 +425,7 @@ public function updateRequestFormDetail(int $detailId, $request): OvertimeReques
{
$detail = OvertimeRequestDetail::findOrFail($detailId);
$record = $this->findRequestForm((int) $detail->fk_overtime_request_main);
$this->authorizePmRequestAccess($record, [0, 8, 10]);
$this->authorizePmRequestAccess($record, [1, 8, 10]);
$staffUserId = $this->resolveProjectStaffIdByName((int) $record->orm_project, (string) $request->ord_name);
if (!$staffUserId) {
......@@ -458,7 +458,7 @@ public function removeRequestFormDetail(int $detailId): void
{
$detail = OvertimeRequestDetail::findOrFail($detailId);
$record = $this->findRequestForm((int) $detail->fk_overtime_request_main);
$this->authorizePmRequestAccess($record, [0, 8, 10]);
$this->authorizePmRequestAccess($record, [1, 8, 10]);
$mainId = $detail->fk_overtime_request_main;
$detail->delete();
......@@ -468,7 +468,7 @@ public function removeRequestFormDetail(int $detailId): void
// =========================================================================
// AUDIT TRAIL (helper for request repo)
// Mirrors logger used in claim repos
private function logAuditTrail(string $taskCode, int $claimId, ?int $detailId = null, string $extra = ''): void
private function logAuditTrail(string $taskCode, int $requestId, ?int $detailId = null, string $extra = ''): void
{
$taskId = DB::table('lkp_overtime_task')
->where('task_code', $taskCode)
......@@ -480,7 +480,7 @@ private function logAuditTrail(string $taskCode, int $claimId, ?int $detailId =
->value('task_name') ?? $taskCode;
$userName = Auth::user()->name ?? 'Unknown';
$applyNo = OvertimeRequestMain::where('id', $claimId)->value('orm_apply_no') ?? '-';
$applyNo = OvertimeRequestMain::where('id', $requestId)->value('orm_apply_no') ?? '-';
$description = "{$userName} performed {$taskName} on request {$applyNo}.";
if ($extra) {
......@@ -490,6 +490,8 @@ private function logAuditTrail(string $taskCode, int $claimId, ?int $detailId =
OvertimeAuditTrail::create([
'fk_overtime_claim_main' => null,
'fk_overtime_claim_detail' => null,
'fk_overtime_request_main' => $requestId,
'fk_overtime_request_detail' => $detailId,
'fk_lkp_overtime_task' => $taskId,
'user' => Auth::id(),
'description' => $description,
......@@ -502,7 +504,7 @@ private function logAuditTrail(string $taskCode, int $claimId, ?int $detailId =
public function submitRequestForm(int $id): OvertimeRequestMain
{
$record = $this->findRequestForm($id);
$this->authorizePmRequestAccess($record, [0, 8, 10]);
$this->authorizePmRequestAccess($record, [1, 8, 10]);
$detailCount = OvertimeRequestDetail::where('fk_overtime_request_main', $id)->count();
if ($detailCount === 0) {
......
......@@ -36,17 +36,26 @@ public function viewClaim(Request $request, int $id)
$data = $this->repos->findClaimWithDetails($id);
$statuses = $this->repos->getOtStatuses();
$selectionData = $this->repos->getRequestFormSelectionData($data['main']);
$NO_PROJECT_ID = 110;
$pmPendingCount = $data['details']
->where('pm_owned', true)
->where('ocd_pm_reviewed', 0)
->filter(function ($d) use ($NO_PROJECT_ID) {
return empty($d->fk_lkp_project) || $d->fk_lkp_project != $NO_PROJECT_ID;
})
->count();
return view('overtime::overtime.overtimeclaim.projectmanager.view', [
'main' => $data['main'],
'details' => $data['details'],
'projectNames' => $data['projectNames'],
'latestQuery' => $data['latestQuery'],
'queryHistory' => $data['queryHistory'],
'statuses' => $statuses,
'forms' => $selectionData['forms'],
'months' => $selectionData['months'],
'staffNames' => $selectionData['staffNames'],
'main' => $data['main'],
'details' => $data['details'],
'projectNames' => $data['projectNames'],
'latestQuery' => $data['latestQuery'],
'queryHistory' => $data['queryHistory'],
'statuses' => $statuses,
'forms' => $selectionData['forms'],
'months' => $selectionData['months'],
'staffNames' => $selectionData['staffNames'],
'pmPendingCount' => $pmPendingCount,
]);
}
......
......@@ -246,7 +246,7 @@ public function viewOvertimeRequest(Request $request, int $id): JsonResponse
->where('ref_id', $main->orm_status)
->first();
$main->orm_status_label = $status->description ?? ($main->orm_status == 0 ? 'Draf' : '-');
$main->orm_status_label = $status->description ?? ($main->orm_status == 1 ? 'Draf' : '-');
$main->orm_requested_by_name = $main->orm_requested_by_id
? (DB::table('project_team')->where('id', $main->orm_requested_by_id)->value('pt_team')
?: ($this->repos->resolveApplicantName($main->orm_name) ?: '-'))
......
......@@ -92,38 +92,38 @@ protected function menu()
$menu->add(__('List of Request Forms (PM)'), url('/overtime/request/list'))
->data('icon', 'file alternate')
->active('overtime/request/*')
->data('permission', Permission::REQUEST_OT);
->data('permission', Permission::REQUEST_OT_PM);
$menu->add(__('Support Request Forms (HOD)'), url('/overtime/request/hod/list'))
->data('icon', 'check circle')
->active('overtime/request/hod/*')
->data('permission', Permission::APPLICATION_OT_HOD);
->data('permission', Permission::REQUEST_OT_HOD);
$menu->add(__('Approve Request Forms (PD)'), url('/overtime/request/pd/list'))
->data('icon', 'check circle outline')
->active('overtime/request/pd/*')
->data('permission', Permission::APPLICATION_OT_PD);
->data('permission', Permission::REQUEST_OT_PD);
$menu = $menus->add(__('OT CLAIM'))->data('icon', 'align justify');
$menu->add(__('List of Claim Forms '), url('/overtime/list'))
->data('icon', 'file alternate')
->active('overtime/*')
->data('permission', Permission::APPLICATION_OT);
->data('permission', Permission::CLAIM_OT);
$menu->add(__('Review Claim Forms (PM)'), url('/overtime/projectmanager/list'))
->data('icon', 'check')
->active('overtime/*')
->data('permission', Permission::APPLICATION_OT_REVIEW);
->data('permission', Permission::CLAIM_OT_PM);
$menu->add(__('Support Claim Forms (HOD)'), url('/overtime/claim/hod/list'))
->data('icon', 'check circle')
->active('overtime/*')
->data('permission', Permission::APPLICATION_OT_SUPPORT);
->data('permission', Permission::CLAIM_OT_HOD);
$menu->add(__('Approve Claim Forms (PD)'), url('/overtime/claim/pd/list'))
->data('icon', 'check circle outline')
->active('overtime/*')
->data('permission', Permission::APPLICATION_OT_APPROVE);
->data('permission', Permission::CLAIM_OT_PD);
});
......
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