commit

parent 7e89f00e
......@@ -30,6 +30,22 @@ final class Permission extends Enum
const FINANCE = "FINANCE";
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";
// end overtime menu
// start mileage menu
const APPLICATION_MILEAGE = "APPLICATION_MILEAGE";
// end mileage menu
//should added to in table:acl_permission
}
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('overtime_claim_main', function (Blueprint $table) {
$table->tinyInteger('ocm_query_status')->nullable()->after('ocm_status');
if (!Schema::hasColumn('overtime_claim_main', 'ocm_approved_by')) {
$table->integer('ocm_approved_by')->nullable()->after('ocm_query_status');
}
});
}
public function down(): void
{
Schema::table('overtime_claim_main', function (Blueprint $table) {
$table->dropColumn(['ocm_query_status', 'ocm_approved_by']);
});
}
};
\ No newline at end of file
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up(): void
{
Schema::create('overtime_audit_query', function (Blueprint $table) {
$table->increments('id');
$table->integer('fk_main');
$table->string('no_permohonan');
$table->integer('fk_user_kueri');
$table->text('remarks')->nullable();
$table->text('respond')->nullable();
$table->timestamp('tarikh')->nullable();
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('overtime_audit_query');
}
};
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up(): void
{
Schema::table('overtime_request_main', function (Blueprint $table) {
$table->text('orm_query_remark')->nullable()->after('orm_status');
$table->integer('orm_query_by')->nullable()->after('orm_query_remark');
$table->text('orm_query_respond')->nullable()->after('orm_query_by');
});
}
public function down(): void
{
Schema::table('overtime_request_main', function (Blueprint $table) {
$table->dropColumn(['orm_query_remark', 'orm_query_by', 'orm_query_respond']);
});
}
};
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('overtime_claim_detail', function (Blueprint $table) {
$table->boolean('ocd_pm_reviewed')->default(0);
$table->integer('ocd_pm_reviewed_by')->nullable();
$table->timestamp('ocd_pm_reviewed_at')->nullable();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('overtime_claim_detail', function (Blueprint $table) {
$table->dropColumn([
'ocd_pm_reviewed',
'ocd_pm_reviewed_by',
'ocd_pm_reviewed_at',
]);
});
}
};
<?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_request_main', function (Blueprint $table) {
$table->string('orm_name')->nullable()->change();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('overtime_request_main', function (Blueprint $table) {
$table->integer('orm_name')->nullable()->change();
});
}
};
......@@ -11,7 +11,7 @@
<div class="ui small modal" id="modalTuntutanBaharu">
<div class="header">
<i class="file alternate outline icon"></i>
Tuntutan Baharu
New Claim
</div>
<div class="content">
......@@ -28,15 +28,15 @@
<p style="color:#888; margin-bottom:1.2rem;">
<i class="info circle icon"></i>
Pilih bulan dan tahun untuk tuntutan baharu.
Butiran lanjut boleh dilengkapkan selepas ini.
Select the month and year for the new claim.
Further details can be completed later.
</p>
@php
$monthNames = [
1 => 'Januari', 2 => 'Februari', 3 => 'Mac', 4 => 'April',
5 => 'Mei', 6 => 'Jun', 7 => 'Julai', 8 => 'Ogos',
9 => 'September', 10 => 'Oktober', 11 => 'November', 12 => 'Disember',
1 => 'January', 2 => 'February', 3 => 'March', 4 => 'April',
5 => 'May', 6 => 'June', 7 => 'July', 8 => 'August',
9 => 'September', 10 => 'October', 11 => 'November', 12 => 'December',
];
$currentYear = now()->year;
@endphp
......@@ -44,10 +44,10 @@
<div class="two fields">
<div class="required field" id="field-ocm_month">
<label>Bulan</label>
<label>Month</label>
<select name="ocm_month" id="ocm_month"
style="width:100%; padding:8px; border:1px solid rgba(34,36,38,.15); border-radius:4px;">
<option value="">-- Pilih Bulan --</option>
<option value="">-- Choose Month --</option>
@foreach($monthNames as $monthNum => $monthName)
<option value="{{ $monthNum }}">{{ $monthName }}</option>
@endforeach
......@@ -55,10 +55,10 @@
</div>
<div class="required field" id="field-ocm_year">
<label>Tahun</label>
<label>Year</label>
<select name="ocm_year" id="ocm_year"
style="width:100%; padding:8px; border:1px solid rgba(34,36,38,.15); border-radius:4px;">
<option value="">-- Pilih Tahun --</option>
<option value="">-- Choose Year --</option>
@for($y = now()->year; $y >= now()->year - 3; $y--)
<option value="{{ $y }}" {{ $y === now()->year ? 'selected' : '' }}>
{{ $y }}
......@@ -74,10 +74,10 @@
<div class="actions">
<button type="button" class="ui teal button" id="btn-modal-claim-submit">
Cipta Tuntutan
Create New Claim
</button>
<button type="button" class="ui deny button">
<i class="times icon"></i> Batal
<i class="times icon"></i> Cancel
</button>
</div>
</div>
......@@ -93,7 +93,7 @@
9: 'September', 10: 'Oktober', 11: 'November', 12: 'Disember',
};
// ONE PERMOHONAN PER MONTH
// REFRESH MONTH
function refreshMonthOptions() {
var year = $('#ocm_year').val();
if (!year) return;
......@@ -102,28 +102,27 @@ function refreshMonthOptions() {
url : EXISTING_MONTHS_URL,
method : 'GET',
success: function (res) {
var occupied = (res.success && res.existingMonths) ? res.existingMonths : [];
buildMonthOptions(year, occupied);
var claimed = (res.success && res.existingMonths) ? res.existingMonths : [];
buildMonthOptions(year, claimed);
},
error: function (xhr) {
console.warn('Gagal memuat bulan sedia ada.', xhr.status, xhr.statusText);
console.warn('Error fetching existing months.', xhr.status, xhr.statusText);
buildMonthOptions(year, []);
}
});
}
function buildMonthOptions(year, occupied) {
function buildMonthOptions(year, claimed) {
var current = $('#ocm_month').val();
var html = '<option value="">-- Pilih Bulan --</option>';
var html = '<option value="">-- Choose Month --</option>';
var claimedYear = claimed.filter(function (m) { return String(m).startsWith(String(year)); });
for (var m = 1; m <= 12; m++) {
var key = String(year) + String(m).padStart(2, '0');
var isTaken = occupied.indexOf(key) !== -1;
var label = isTaken
? MONTH_NAMES[m] + ' (Telah ada permohonan)'
: MONTH_NAMES[m];
var disabled = isTaken ? ' disabled' : '';
var selected = (!isTaken && String(current) === String(m)) ? ' selected' : '';
var isClaimed = claimedYear.indexOf(key) !== -1;
var label = MONTH_NAMES[m] + (isClaimed ? ' (Already submitted claim)' : '');
var disabled = isClaimed ? ' disabled' : '';
var selected = (!disabled && String(current) === String(m)) ? ' selected' : '';
html += '<option value="' + m + '"' + disabled + selected + '>' + label + '</option>';
}
......@@ -134,7 +133,6 @@ function buildMonthOptions(year, occupied) {
$('#ocm_year').on('change', refreshMonthOptions);
refreshMonthOptions();
// REFRESH LIST EVERY TIME MODAL OPENS
$('#modalTuntutanBaharu').on('show', function () {
$('#modal-success-msg, #modal-error-msg').hide();
$('#field-ocm_month, #field-ocm_year').removeClass('error');
......@@ -156,7 +154,7 @@ function buildMonthOptions(year, occupied) {
if (!month) { $('#field-ocm_month').addClass('error'); hasError = true; }
if (!year) { $('#field-ocm_year').addClass('error'); hasError = true; }
if (hasError) {
$('#modal-error-text').text('Sila pilih bulan dan tahun.');
$('#modal-error-text').text('Choose month and year.');
$('#modal-error-msg').show();
return;
}
......@@ -176,14 +174,14 @@ function buildMonthOptions(year, occupied) {
$('#modal-success-msg').show();
setTimeout(function () { window.location.href = res.redirect; }, 800);
} else {
$('#modal-error-text').text(res.message || 'Ralat tidak diketahui.');
$('#modal-error-text').text(res.message || 'Unknown error.');
$('#modal-error-msg').show();
refreshMonthOptions();
}
},
error: function (xhr) {
btn.removeClass('loading disabled');
var msg = 'Ralat rangkaian. Sila cuba lagi.';
var msg = 'Network error. Please try again';
if (xhr.status === 422 && xhr.responseJSON && xhr.responseJSON.errors) {
var errors = xhr.responseJSON.errors;
msg = Object.values(errors).flat().join(' ');
......
@extends('ui::layouts.app')
@section('content')
@include('overtime::overtime.modal.view_modal')
<style>
/* ─── SUMMARY BOX ──────────────────────────────────────────────────────── */
.ot-summary {
background: #ddeeff; border-radius: 6px;
padding: .9rem 1.2rem; margin-bottom: 1.2rem; line-height: 1.7;
}
.ot-summary .apply-no { font-size: 1.05rem; font-weight: 700; color: #1a56a0; }
.ot-summary .meta-line { font-size: .92rem; color: #333; }
/* ─── CARD PANELS ──────────────────────────────────────────────────────── */
.ot-card {
background: #fff; border: 1px solid #dde3ea;
border-radius: 8px; padding: 1.2rem 1.4rem; margin-bottom: 1.3rem;
}
.ot-card .card-title {
font-size: 1rem; font-weight: 700; color: #222;
display: flex; align-items: center; gap: .45rem; margin-bottom: .2rem;
}
.ot-card .card-sub { font-size: .8rem; color: #999; margin-bottom: .95rem; }
/* ─── OT TABLE ─────────────────────────────────────────────────────────── */
.ot-tbl { width: 100%; border-collapse: collapse; font-size: .85rem; }
.ot-tbl th, .ot-tbl td {
border: 1px solid #cfd8e3; padding: 6px 10px;
text-align: center; vertical-align: middle;
}
.ot-tbl thead .row-grp th { background: #e8f0fa; color: #444; font-size: .8rem; font-weight: 600; padding: 5px 10px; }
.ot-tbl thead .row-grp th.grp-blue { background: #2185d0; color: #fff; }
.ot-tbl thead .row-cols th { background: #2185d0; color: #fff; font-size: .83rem; font-weight: 600; }
.ot-tbl thead .row-cols th.col-light { background: #5aace8; }
.ot-tbl tbody td.td-shade { background: #f0f7ff; }
.ot-tbl tbody td.td-tasks { text-align: left; }
.ot-tbl tbody td.td-project { text-align: left; }
.ot-tbl tbody tr:hover td { filter: brightness(.97); }
.ot-tbl .empty-row td { color: #bbb; font-style: italic; padding: 1.8rem; }
.ot-tbl tfoot td {
background: #ddeeff; font-weight: 700; color: #1a56a0;
border-top: 2px solid #2185d0;
}
.ot-tbl tfoot .lbl { text-align: right; letter-spacing: .04em; font-size: .82rem; }
/* ─── DELETE BUTTON ─────────────────────────────────────────────────────── */
.btn-del {
border: 1px solid #e53935; background: transparent; color: #e53935;
border-radius: 4px; padding: 2px 9px; font-size: .78rem;
cursor: pointer; transition: all .15s; line-height: 1.6;
}
.btn-del:hover { background: #e53935; color: #fff; }
/* ─── ENTRY FORM CARD ──────────────────────────────────────────────────── */
.ot-form-card {
background: #fff; border: 1px solid #dde3ea;
border-left: 4px solid #2185d0; border-radius: 8px;
padding: 1.3rem 1.5rem 1.1rem; margin-bottom: 1.3rem;
}
.ot-form-card .form-title {
font-size: 1rem; font-weight: 700; color: #222;
display: flex; align-items: center; gap: .45rem; margin-bottom: 1.1rem;
}
.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; vertical-align: middle;
}
.field-hint { font-size: .76rem; color: #999; margin-top: .3rem; display: flex; align-items: center; gap: .3rem; }
/* ─── FOOTER ───────────────────────────────────────────────────────────── */
.ot-footer {
display: flex; justify-content: flex-end; gap: .55rem;
padding-top: .9rem; border-top: 1px solid #e5e8ee;
}
.ot-summary,.ot-card,.ot-form-card,.ot-query-card{background:#fff;border:1px solid #dde3ea;border-radius:8px}
.ot-summary{background:#ddeeff;padding:.9rem 1.2rem;margin-bottom:1.2rem;line-height:1.7}
.ot-summary .apply-no{font-size:1.05rem;font-weight:700;color:#1a56a0}
.ot-summary .meta-line{font-size:.92rem;color:#333}
.ot-card,.ot-form-card,.ot-query-card{padding:1.2rem 1.4rem;margin-bottom:1.3rem}
.ot-card .card-title,.ot-form-card .form-title,.ot-query-card .form-title{font-size:1rem;font-weight:700;color:#222;display:flex;align-items:center;gap:.45rem;margin-bottom:.9rem}
.ot-tbl{width:100%;border-collapse:collapse;font-size:.85rem}
.ot-tbl th,.ot-tbl td{border:1px solid #cfd8e3;padding:6px 10px;text-align:center;vertical-align:middle}
.ot-tbl thead .row-grp th,.ot-tbl thead .row-cols th{background:#2185d0;color:#fff}
.ot-tbl tbody td.td-shade{background:#f0f7ff}
.ot-tbl tbody td.td-tasks,.ot-tbl tbody td.td-project{text-align:left}
.ot-tbl tfoot td{background:#ddeeff;font-weight:700;color:#1a56a0;border-top:2px solid #2185d0}
.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:hover{background:#e53935;color:#fff}
.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}
.field-hint{font-size:.76rem;color:#999;margin-top:.3rem;display:flex;align-items:center;gap:.3rem}
.ot-footer{display:flex;justify-content:flex-end;gap:.55rem;padding-top:.9rem;border-top:1px solid #e5e8ee}
.query-history{width:100%;border-collapse:collapse;font-size:.85rem}
.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-radio{display:flex;justify-content:flex-end;gap:1rem;flex-wrap:wrap}
</style>
<div class="ui segment" style="padding-bottom: 2rem;">
<div id="success-msg" class="ui positive message" style="display:none; margin-bottom:.75rem;">
<p id="success-text"></p>
</div>
<div id="error-msg" class="ui negative message" style="display:none; margin-bottom:.75rem;">
<p id="error-text"></p>
</div>
<div class="ui segment" style="padding-bottom:2rem;">
<div id="success-msg" class="ui positive message" style="display:none;margin-bottom:.75rem;"><p id="success-text"></p></div>
<div id="error-msg" class="ui negative message" style="display:none;margin-bottom:.75rem;"><p id="error-text"></p></div>
@php
$s = isset($statuses[$data->ocm_status])
? ['label' => $statuses[$data->ocm_status]->description]
: ['label' => '-'];
$colours = [
1=>'grey', 2=>'blue', 3=>'blue', 4=>'red',
5=>'yellow', 6=>'orange', 7=>'yellow', 8=>'orange',
9=>'yellow', 10=>'orange', 11=>'green', 12=>'red',
];
$sColour = $colours[$data->ocm_status] ?? 'grey';
$msMonths = [
1=>'Januari',2=>'Februari',3=>'Mac',4=>'April',5=>'Mei',6=>'Jun',
7=>'Julai',8=>'Ogos',9=>'September',10=>'Oktober',11=>'November',12=>'Disember',
];
$monthLabel = ($data->ocm_month && $data->ocm_year)
? ($msMonths[$data->ocm_month] ?? '-') . ' ' . $data->ocm_year
$monthLabel = $data->ocm_month && $data->ocm_year
? \Carbon\Carbon::createFromDate($data->ocm_year, $data->ocm_month, 1)->format('F Y')
: '-';
$statusLabel = $statuses[$data->ocm_status]->description ?? '-';
$queryHistory = $queryHistory ?? collect();
@endphp
{{-- ══ SUMMARY ════════════════════════════════════════════════════════ --}}
<div class="ot-summary">
<div class="apply-no">{{ $data->ocm_apply_no }}</div>
<div class="meta-line">
Bulan: <strong>{{ $monthLabel }}</strong>
</div>
<div class="meta-line">
Status: <span class="ui {{ $sColour }} label" style="font-size:.78rem;">{{ $s['label'] }}</span>
</div>
<div class="meta-line">Request by: <strong>{{ $data->ocm_staff_name ?? '-' }}</strong></div>
<div class="meta-line">Department: <strong>{{ $data->ocm_division_label ?? '-' }}</strong></div>
<div class="meta-line">Month/Year: <strong>{{ $monthLabel }}</strong></div>
<div class="meta-line">Status: <strong>{{ $statusLabel }}</strong></div>
<div class="meta-line">Claim Date: <strong>{{ $data->ocm_submit_date ? \Carbon\Carbon::parse($data->ocm_submit_date)->format('d/m/Y') : '-' }}</strong></div>
<div class="meta-line">Approved by: <strong>{{ $data->ocm_approved_by_name ?? '-' }}</strong></div>
<div class="meta-line">Approved Date: <strong>{{ $data->ocm_approved_date ? \Carbon\Carbon::parse($data->ocm_approved_date)->format('d/m/Y') : '-' }}</strong></div>
</div>
{{-- ══ JADUAL TABLE ════════════════════════════════════════════════════ --}}
<div class="ot-card">
<div class="card-title">
<i class="table icon" style="color:#2185d0;"></i>
Jadual Tuntutan Lebih Masa
</div>
<div class="card-sub">{{ $monthLabel }}</div>
<div class="card-title"><i class="table icon" style="color:#2185d0;"></i>OT Claim Details</div>
<div style="overflow-x:auto;">
<table class="ot-tbl" id="ot-table">
<thead>
<tr class="row-grp">
<th rowspan="2" style="vertical-align:middle; min-width:100px;">Date</th>
<th rowspan="2" style="vertical-align:middle; min-width:110px;">
Day Type<br><span style="font-weight:400; font-size:.73rem;">(Office Use Only)</span>
</th>
<th rowspan="2" style="vertical-align:middle; min-width:110px;">Office Hour</th>
<th colspan="2" class="grp-blue" style="min-width:190px;">Overtime</th>
<th rowspan="2" class="grp-blue" style="vertical-align:middle; min-width:200px;">Projek</th>
<th rowspan="2" class="grp-blue" style="vertical-align:middle; min-width:300px;">Tasks</th>
<th rowspan="2" class="grp-blue" style="vertical-align:middle; min-width:90px;">
Effective<br>Hours
</th>
<th rowspan="2" style="vertical-align:middle; min-width:55px;"></th>
<th rowspan="2" style="vertical-align:middle;min-width:100px;">Date</th>
<th rowspan="2" style="vertical-align:middle;min-width:110px;">Day Type</th>
<th rowspan="2" style="vertical-align:middle;min-width:110px;">Office Hour</th>
<th colspan="2">Overtime</th>
<th rowspan="2" style="vertical-align:middle;min-width:200px;">Project</th>
<th rowspan="2" style="vertical-align:middle;min-width:300px;">Tasks</th>
<th rowspan="2" style="vertical-align:middle;min-width:90px;">PM Review</th>
<th rowspan="2" style="vertical-align:middle;min-width:90px;">Total Hours</th>
<th rowspan="2" style="vertical-align:middle;min-width:90px;">Effective Hours</th>
<th rowspan="2" style="vertical-align:middle;min-width:55px;"></th>
</tr>
<tr class="row-cols">
<th class="col-light" style="min-width:90px;">From</th>
<th class="col-light" style="min-width:90px;">To</th>
<th>From</th>
<th>To</th>
</tr>
</thead>
<tbody id="ot-tbody">
<tr class="empty-row">
<td colspan="9">Memuatkan entri…</td>
</tr>
</tbody>
<tbody id="ot-tbody"><tr class="empty-row"><td colspan="10">Loading entries...</td></tr></tbody>
<tfoot>
<tr>
<td colspan="7" class="lbl">GRAND TOTAL HOURS</td>
<td id="grand-total" style="text-align:center;">0.0</td>
<td colspan="8" class="lbl">GRAND TOTAL HOURS</td>
<td id="grand-total-total" style="text-align:center;">0.0</td>
<td id="grand-total-effective" style="text-align:center;">0.0</td>
<td></td>
</tr>
</tfoot>
......@@ -167,277 +85,315 @@
</div>
</div>
{{-- ══ ENTRY FORM ══════════════════════════════════════════════════════ --}}
<div class="ot-form-card">
<div class="form-title">
<i class="plus circle icon" style="color:#2185d0; font-size:1.1em;"></i>
Tambah Entri Tuntutan
</div>
<div class="ui form" id="form-add-detail">
@csrf
{{-- Row 1 — Tarikh | Jenis Hari --}}
<div class="form-title"><i class="plus circle icon" style="color:#2185d0;font-size:1.1em;"></i>Add Entry</div>
<div class="ui form" id="form-add-detail">@csrf
<div class="two fields">
<div class="required field" id="field-tarikh">
<label>Tarikh <span style="color:#e53935;">*</span></label>
<div class="required field">
<label>Date <span style="color:#e53935;"></span></label>
<input type="date" id="ocd_date_input" name="ocd_date_input"
@if($data->ocm_month && $data->ocm_year)
min="{{ \Carbon\Carbon::createFromDate($data->ocm_year, $data->ocm_month, 1)->format('Y-m-d') }}"
max="{{ \Carbon\Carbon::createFromDate($data->ocm_year, $data->ocm_month, 1)->endOfMonth()->format('Y-m-d') }}"
@endif>
<div class="field-hint">
<i class="info circle icon"></i>
Hanya tarikh dalam bulan {{ $monthLabel }} dibenarkan.
</div>
<div class="field-hint"><i class="info circle icon"></i>Only dates within {{ $monthLabel }} are allowed.</div>
</div>
<div class="required field" id="field-jenis-hari">
<label>Jenis Hari <span style="color:#e53935;">*</span></label>
<div class="required field">
<label>Day Type <span style="color:#e53935;"></span></label>
<select id="ocd_day_type" name="ocd_day_type">
<option value="">-- Pilih --</option>
<option value="Hari Bekerja">Hari Bekerja</option>
<option value="Hari Rehat">Hari Rehat</option>
<option value="Cuti Umum">Cuti Umum</option>
<option value="">-- Select --</option>
<option value="Hari Bekerja">Working Day</option>
<option value="Hari Rehat">Rest Day</option>
<option value="Cuti Umum">Public Holiday</option>
</select>
<div class="field-hint">
<i class="magic icon"></i>
Auto-detect apabila tarikh dipilih.
<div class="field-hint"><i class="magic icon"></i>Auto-detect when date is selected.</div>
</div>
</div>
</div>
{{-- Row 2 — Office Hour Mula | Office Hour Tamat (auto) | OT From | OT To --}}
<div class="four fields">
<div class="required field">
<label>Office Hour — Mula <span style="color:#e53935;">*</span></label>
<input type="time" id="ocd_office_start" name="ocd_office_start">
<div class="field-hint"><i class="info circle icon"></i> Tamat auto +9 jam.</div>
</div>
<div class="field">
<label>Office Hour — Tamat <span class="badge-auto">auto</span></label>
<input type="time" id="ocd_office_end" name="ocd_office_end" readonly class="auto-field">
</div>
<div class="required field">
<label>Overtime From <span style="color:#e53935;">*</span></label>
<input type="time" id="ocd_overtime_from" name="ocd_overtime_from">
<div class="required field"><label>Office Hour Start <span style="color:#e53935;"></span></label><input type="time" id="ocd_office_start" name="ocd_office_start"><div class="field-hint"><i class="info circle icon"></i>End auto +9 hours.</div></div>
<div class="field"><label>Office Hour End <span class="badge-auto">auto</span></label><input type="time" id="ocd_office_end" name="ocd_office_end" readonly class="auto-field"></div>
<div class="required field"><label>OT From <span style="color:#e53935;"></span></label><input type="time" id="ocd_overtime_from" name="ocd_overtime_from"></div>
<div class="required field"><label>OT To <span style="color:#e53935;"></span></label><input type="time" id="ocd_overtime_to" name="ocd_overtime_to"></div>
</div>
<div class="required field">
<label>Overtime To <span style="color:#e53935;">*</span></label>
<input type="time" id="ocd_overtime_to" name="ocd_overtime_to">
</div>
</div>
{{-- Row 3 — Projek --}}
<div class="one field">
<div class="field">
<label>Projek</label>
<label>Project</label>
<select id="fk_lkp_project" name="fk_lkp_project">
<option value="">-- Tiada / Tidak Berkaitan --</option>
<option value="">-- None / Not Applicable --</option>
@foreach($projects as $proj)
<option value="{{ $proj->id }}">{{ $proj->p_project_description }}</option>
@endforeach
</select>
</div>
</div>
{{-- Row 4 — Effective Hours (auto) | Tasks --}}
<div class="two fields">
<div class="three fields">
<div class="required field">
<label>Total Hours <span class="badge-auto">auto</span></label>
<input type="number" id="ocd_total_hours" name="ocd_total_hours" step="0.5" min="0.0" placeholder="0.0" readonly class="auto-field">
</div>
<div class="required field">
<label>
Effective Hours
<span class="badge-auto">auto dari OT From — To</span>
<span style="color:#e53935;">*</span>
</label>
<input type="number"
id="ocd_effective_hours" name="ocd_effective_hours"
step="0.5" min="0.5"
placeholder="Auto-kira atau isi manual"
class="auto-field" readonly>
<label>Effective Hours <span style="color:#e53935;"></span></label>
<input type="number" id="ocd_effective_hours" name="ocd_effective_hours" step="0.5" min="0.5" placeholder="0.0">
</div>
<div class="required field">
<label>Tasks <span style="color:#e53935;">*</span></label>
<textarea id="ocd_tasks" name="ocd_tasks" rows="3"
placeholder="Huraikan tugasan yang dilakukan semasa lebih masa…"></textarea>
<label>Tasks <span style="color:#e53935;"></span></label>
<textarea id="ocd_tasks" name="ocd_tasks" rows="3" placeholder="Describe the overtime tasks..."></textarea>
</div>
</div>
<div class="button-row" style="display:flex;justify-content:flex-end;gap:.55rem;">
<button type="button" class="ui teal button" id="btn-add-day"><i class="plus icon"></i>Add to Table</button>
<button type="button" class="ui grey button" id="btn-reset"><i class="redo icon"></i>Clear</button>
</div>
</div>
</div>
<div style="display:flex; gap:.55rem; margin-top:.6rem;">
<button type="button" class="ui teal button" id="btn-add-day">
<i class="plus icon"></i> Tambah ke Jadual
</button>
<button type="button" class="ui grey button" id="btn-reset">
<i class="redo icon"></i> Kosongkan
</button>
@if($queryHistory->isNotEmpty() || in_array($data->ocm_status, [6]))
<div class="ot-query-card">
<div class="form-title"><i class="comment alternate outline icon"></i>Query History</div>
<div style="overflow-x:auto;">
<table class="query-history">
<thead>
<tr>
<th style="width:180px;">From</th>
<th>Query Notes</th>
<th>Response</th>
<th style="width:150px;">Date</th>
</tr>
</thead>
<tbody>
@forelse($queryHistory as $q)
<tr>
<td>{{ $q->queriedBy->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>
</tr>
@empty
<tr><td colspan="4" style="color:#999;font-style:italic;text-align:center;padding:1rem;">No query history found.</td></tr>
@endforelse
</tbody>
</table>
</div>
</div>
@if(in_array($data->ocm_status, [6]))
<div class="ot-query-card">
<div class="form-title"><i class="write icon"></i>Your Response</div>
<div class="field">
<label style="font-weight:600;display:block;margin-bottom:.4rem;">Response <span style="color:#e53935;"></span></label>
<textarea id="kueri_respond" rows="4" placeholder="Write your response to the query..." style="width:100%;min-height:100px;padding:.75rem 1rem;font-size:.92rem;border:1px solid #d4d8dd;border-radius:6px;resize:vertical;font-family:inherit;line-height:1.5;">{{ $data->ocm_query_respond }}</textarea>
</div>
</div>
@endif
@endif
{{-- ══ FOOTER BUTTONS ══════════════════════════════════════════════════ --}}
<div class="ot-footer">
<a href="{{ route('overtime::overtime.listovertime') }}" class="ui grey button">
<i class="arrow left icon"></i> Kembali
</a>
<button type="button" class="ui grey button" onclick="saveDetails()">
<i class="save icon"></i> Simpan Draf
</button>
<button type="button" class="ui teal button" onclick="submitTuntutan()">
<i class="check circle icon"></i> Hantar Tuntutan
</button>
<a href="{{ route('overtime::overtime.listovertime') }}" class="ui grey button"><i class="arrow left icon"></i>Back</a>
@if($data->ocm_status == 1)
<button type="button" class="ui grey button" onclick="saveDetails()"><i class="save icon"></i>Save Draft</button>
<button type="button" class="ui teal button" onclick="submitTuntutan()"><i class="check circle icon"></i>Submit Claim</button>
@elseif($data->ocm_status == 6)
<button type="button" class="ui grey button" onclick="saveDetails()"><i class="save icon"></i>Save Draft</button>
@endif
</div>
</div>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
var mainId = {{ $data->id }};
var otMonth = {{ $data->ocm_month ?? 'null' }};
var otYear = {{ $data->ocm_year ?? 'null' }};
var MS_MONTH = ['Jan','Feb','Mac','Apr','Mei','Jun','Jul','Ogos','Sep','Okt','Nov','Dis'];
var DAY_NAMES = ['Ahad','Isnin','Selasa','Rabu','Khamis','Jumaat','Sabtu'];
var details = {};
var MS_MONTH = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var DAY_NAMES = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
$(document).ready(function () {
if ($.fn.dropdown) $('.ui.dropdown').dropdown({ fullTextSearch: true });
loadDetails();
bindEvents();
});
function bindEvents() {
$('#btn-add-day').on('click', addDay);
$('#btn-reset').on('click', resetForm);
$('#ocd_date_input').on('change', function () {
var v = $(this).val();
if (!v) return;
var dow = new Date(v).getDay();
$('#ocd_day_type').val((dow === 0 || dow === 6) ? 'Hari Rehat' : 'Hari Bekerja');
fetchAttendance(v);
});
$('#ocd_office_start').on('change', function () {
var v = $(this).val();
if (!v) { $('#ocd_office_end').val(''); return; }
var p = v.split(':');
var d = new Date(2000, 0, 1, +p[0], +p[1]);
d.setHours(d.getHours() + 9);
$('#ocd_office_end').val(pad(d.getHours()) + ':' + pad(d.getMinutes()));
updateOfficeEndFromStart();
});
$('#ocd_overtime_from, #ocd_overtime_to').on('change', function () {
var f = $('#ocd_overtime_from').val();
var t = $('#ocd_overtime_to').val();
if (!f || !t) return;
var diff = toMin(t) - toMin(f);
if (diff <= 0) diff += 1440;
var hrs = Math.round((diff / 60) * 2) / 2;
$('#ocd_effective_hours').val(hrs > 0 ? hrs : '');
updateTotalHours();
});
$('#btn-add-day').on('click', addDay);
$('#btn-reset').on('click', resetForm);
}
function pad(n) { return String(n).padStart(2, '0'); }
function toMin(t) { var p = t.split(':'); return +p[0] * 60 + +p[1]; }
function csrfToken(){ return $('meta[name="csrf-token"]').attr('content'); }
function esc(s) {
if (s === null || s === undefined) return '';
return String(s)
.replace(/&/g,'&amp;').replace(/</g,'&lt;')
.replace(/>/g,'&gt;').replace(/"/g,'&quot;');
function fetchAttendance(dateVal) {
$.ajax({
url: "{{ route('overtime::overtime.getattendance') }}",
method: 'GET',
data: { date: dateVal },
success: function (res) {
if (res.success && res.attendance && res.attendance.time_in) {
var start = (res.attendance.time_in || '').substring(0, 5);
var end = (res.attendance.time_out || '').substring(0, 5);
$('#ocd_office_start')
.val(start)
.prop('readonly', true)
.addClass('auto-field')
.removeAttr('placeholder');
$('#ocd_office_end')
.val(end)
.prop('readonly', true)
.addClass('auto-field');
// If time_out is missing in attendance record, fallback to +9 hours.
if (!end && start) {
updateOfficeEndFromStart();
}
} else {
enableManualOfficeHours();
}
},
error: function () {
enableManualOfficeHours();
},
});
}
function showSuccess(msg) {
$('#success-text').text(msg); $('#success-msg').show();
setTimeout(function () { $('#success-msg').hide(); }, 3500);
function enableManualOfficeHours() {
$('#ocd_office_start')
.prop('readonly', false)
.removeClass('auto-field')
.val('')
.attr('placeholder', 'No attendance found - enter manually');
$('#ocd_office_end')
.prop('readonly', true)
.addClass('auto-field')
.val('');
}
function showError(msg) {
$('#error-text').text(msg); $('#error-msg').show();
setTimeout(function () { $('#error-msg').hide(); }, 6000);
function updateOfficeEndFromStart() {
var startVal = $('#ocd_office_start').val();
if (!startVal) {
$('#ocd_office_end').val('');
return;
}
var p = startVal.split(':');
var d = new Date(2000, 0, 1, +p[0], +p[1]);
d.setHours(d.getHours() + 9);
$('#ocd_office_end').val(pad(d.getHours()) + ':' + pad(d.getMinutes()));
}
function formatDateLabel(dateStr) {
var d = new Date(dateStr);
var day = d.getDate();
var mon = MS_MONTH[d.getMonth()];
var yr = d.getFullYear();
return pad(day) + ' ' + mon + ' ' + yr
+ '<br><small style="color:#999;font-weight:400;">' + DAY_NAMES[d.getDay()] + '</small>';
function updateTotalHours() {
var fromVal = $('#ocd_overtime_from').val();
var toVal = $('#ocd_overtime_to').val();
if (!fromVal || !toVal) {
$('#ocd_total_hours').val('');
return;
}
var fromMin = toMin(fromVal);
var toMinVal = toMin(toVal);
// Support shifts crossing midnight.
if (toMinVal < fromMin) {
toMinVal += 24 * 60;
}
var hours = (toMinVal - fromMin) / 60;
if (hours < 0) {
$('#ocd_total_hours').val('');
return;
}
$('#ocd_total_hours').val(hours.toFixed(1));
}
/* ─── LOAD EXISTING DETAILS ───────────────────────────────────────────── */
function pad(n){ return String(n).padStart(2,'0'); }
function toMin(t){ var p = t.split(':'); return +p[0] * 60 + +p[1]; }
function csrfToken(){ return $('meta[name="csrf-token"]').attr('content'); }
function esc(s){ return s === null || s === undefined ? '' : String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;'); }
function showSuccess(msg){ $('#success-text').text(msg); $('#success-msg').show(); setTimeout(function(){ $('#success-msg').hide(); }, 3500); }
function showError(msg){ $('#error-text').text(msg); $('#error-msg').show(); setTimeout(function(){ $('#error-msg').hide(); }, 6000); }
function formatDateLabel(dateStr){ var d = new Date(dateStr); return pad(d.getDate()) + ' ' + MS_MONTH[d.getMonth()] + ' ' + d.getFullYear() + '<br><small style="color:#999;font-weight:400;">' + DAY_NAMES[d.getDay()] + '</small>'; }
function loadDetails() {
$.ajax({
url : "{{ route('overtime::overtime.viewovertimeclaim', $data->id) }}",
method : 'GET',
url: "{{ route('overtime::overtime.viewovertimeclaim', $data->id) }}",
method: 'GET',
success: function (res) {
if (!res.success || !res.data || !res.data.details) {
renderTable(); return;
}
if (res.success && res.data && res.data.details) {
res.data.details.forEach(function (d) {
var officeParts = (d.ocd_office_hour || '').split(' – ');
details[d.ocd_date] = {
id : d.id,
hours : parseFloat(d.ocd_effective_hours) || 0,
id: d.id,
totalHours: parseFloat(d.ocd_total_hours) || 0,
effectiveHours: parseFloat(d.ocd_effective_hours) || 0,
overtimeFrom: d.ocd_overtime_from || '',
overtimeTo : d.ocd_overtime_to || '',
tasks : d.ocd_tasks || '',
dayType : d.ocd_day_type || '',
officeStart : officeParts[0] || '',
officeEnd : officeParts[1] || '',
officeHour : d.ocd_office_hour || '',
projectId : d.fk_lkp_project || '',
projectName : d.project_name || '',
overtimeTo: d.ocd_overtime_to || '',
tasks: d.ocd_tasks || '',
dayType: d.ocd_day_type || '',
officeStart: officeParts[0] || '',
officeEnd: officeParts[1] || '',
officeHour: d.ocd_office_hour || '',
projectId: d.fk_lkp_project || '',
projectName: d.project_name || '',
};
});
}
renderTable();
},
error: function () {
showError('Gagal memuatkan entri sedia ada.');
renderTable();
},
error: function () { showError('Failed to load existing entries.'); renderTable(); },
});
}
/* ─── RENDER TABLE ────────────────────────────────────────────────────── */
function renderTable() {
var keys = Object.keys(details).sort();
var tbody = $('#ot-tbody');
if (keys.length === 0) {
tbody.html('<tr class="empty-row"><td colspan="9">Belum ada entri. Gunakan borang di bawah untuk menambah.</td></tr>');
$('#grand-total').text('0.0');
tbody.html('<tr class="empty-row"><td colspan="11">No entries yet. Use the form below to add one.</td></tr>');
$('#grand-total-total').text('0.0');
$('#grand-total-effective').text('0.0');
return;
}
var total = 0, html = '';
var totalHours = 0, effectiveHours = 0, html = '';
keys.forEach(function (dateStr) {
var d = details[dateStr];
total += d.hours;
var totalValue = parseFloat(d.totalHours || 0) || 0;
var effectiveValue = parseFloat(d.effectiveHours || 0) || 0;
totalHours += totalValue;
effectiveHours += effectiveValue;
html += '<tr data-date="' + dateStr + '">';
html += '<td>' + formatDateLabel(dateStr) + '</td>';
html += '<td class="td-shade">' + esc(d.dayType || '-') + '</td>';
html += '<td class="td-shade">' + esc(d.officeHour || '-') + '</td>';
html += '<td>' + esc(d.overtimeFrom || '-') + '</td>';
html += '<td>' + esc(d.overtimeTo || '-') + '</td>';
html += '<td class="td-project">'+ esc(d.projectName || '-') + '</td>';
html += '<td class="td-project">' + esc(d.projectName || '-') + '</td>';
html += '<td class="td-tasks">' + esc(d.tasks || '-') + '</td>';
html += '<td><strong>' + d.hours.toFixed(1) + '</strong></td>';
html += '<td><button class="btn-del" onclick="removeDay(\'' + dateStr + '\')">'
+ '<i class="trash icon"></i></button></td>';
html += '<td>' + (d.pmReviewed ? '<span class="ui green label">Reviewed</span>' : '<span class="ui orange label">Pending</span>') + '</td>';
html += '<td>' + totalValue.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 += '</tr>';
});
tbody.html(html);
$('#grand-total').text(total.toFixed(1));
$('#grand-total-total').text(totalHours.toFixed(1));
$('#grand-total-effective').text(effectiveHours.toFixed(1));
}
/* ─── ADD A DAY ENTRY ─────────────────────────────────────────────────── */
function addDay() {
var dateVal = $('#ocd_date_input').val();
var dayType = $('#ocd_day_type').val();
......@@ -445,151 +401,178 @@ function addDay() {
var officeEnd = $('#ocd_office_end').val();
var overtimeFrom = $('#ocd_overtime_from').val();
var overtimeTo = $('#ocd_overtime_to').val();
var hours = $('#ocd_effective_hours').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('Sila pilih tarikh.'); return; }
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('Tarikh mesti dalam bulan permohonan ini.');
return;
}
if (dYear !== otYear || dMonth !== otMonth) { showError('Date must be within the claim month.'); return; }
}
if (!dayType) { showError('Sila pilih jenis hari.'); return; }
if (!officeStart) { showError('Sila isi Office Hour — Mula.'); return; }
if (!overtimeFrom) { showError('Sila isi Overtime From.'); return; }
if (!overtimeTo) { showError('Sila isi Overtime To.'); return; }
if (!hours) { showError('Effective Hours tidak boleh kosong.'); return; }
if (!tasks) { showError('Sila isi ruangan Tasks.'); 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.addovertimeclaim', $data->id) }}",
url: "{{ route('overtime::overtime.addovertimeclaim', $data->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_effective_hours: hours,
ocd_tasks : tasks,
fk_lkp_project : projectId || null,
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 || 'Ralat semasa menambah.'); return; }
if (!res.success) { showError(res.message || 'Error while adding.'); return; }
details[dateVal] = {
id : res.detail.id,
hours : parseFloat(hours),
id: res.detail.id,
totalHours: parseFloat(totalHours),
effectiveHours: parseFloat(effectiveHours),
overtimeFrom: overtimeFrom,
overtimeTo : overtimeTo,
tasks : tasks,
dayType : dayType,
officeStart : officeStart,
officeEnd : officeEnd,
officeHour : res.detail.ocd_office_hour,
projectId : projectId,
projectName : projectName,
overtimeTo: overtimeTo,
tasks: tasks,
dayType: dayType,
officeStart: officeStart,
officeEnd: officeEnd,
officeHour: res.detail.ocd_office_hour,
projectId: projectId,
projectName: projectName,
};
renderTable();
resetForm();
showSuccess(res.message || 'Entri berjaya ditambah.');
showSuccess(res.message || 'Entry added.');
},
error: function (xhr) {
var msg = 'Ralat semasa menambah entri.';
var msg = 'Error while adding 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(' ');
}
if (xhr.responseJSON && xhr.responseJSON.errors) msg = Object.values(xhr.responseJSON.errors).flat().join(' ');
showError(msg);
},
});
}
/* ─── REMOVE DAY ENTRY ────────────────────────────────────────────────────── */
function removeDay(dateStr) {
if (!confirm('Buang entri ' + dateStr + ' daripada jadual?')) return;
if (!confirm('Remove entry ' + dateStr + ' from the table?')) return;
var detailId = details[dateStr] && details[dateStr].id;
if (!detailId) { showError('ID entri tidak dijumpai.'); return; }
if (!detailId) { showError('Entry ID not found.'); return; }
$.ajax({
url : "{{ route('overtime::overtime.removeovertimeclaim', ':id') }}".replace(':id', detailId),
url: "{{ route('overtime::overtime.removeovertimeclaim', ':id') }}".replace(':id', detailId),
method: 'POST',
data : { _token: csrfToken() },
data: { _token: csrfToken() },
success: function (res) {
if (!res.success) { showError(res.message || 'Ralat semasa membuang.'); return; }
if (!res.success) { showError(res.message || 'Error while removing.'); return; }
delete details[dateStr];
renderTable();
showSuccess(res.message || 'Entri berjaya dibuang.');
showSuccess(res.message || 'Entry removed.');
},
error: function () { showError('Ralat rangkaian. Sila cuba lagi.'); },
error: function () { showError('Network error. Please try again.'); },
});
}
/* ─── SAVE DRAFT ──────────────────────────────────────────────────────── */
function saveDetails() {
var respondVal = $('#kueri_respond').val();
function doSave() {
$.ajax({
url : "{{ route('overtime::overtime.saveovertimeclaim', $data->id) }}",
url: "{{ route('overtime::overtime.saveovertimeclaim', $data->id) }}",
method: 'POST',
data : { _token: csrfToken() },
data: { _token: csrfToken() },
success: function (res) {
if (res.success) {
showSuccess(res.message);
setTimeout(function () { window.location.href = res.redirect; }, 1500);
} else { showError(res.message); }
if (res.success) { showSuccess(res.message); setTimeout(function () { window.location.href = res.redirect; }, 1500); }
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);
},
error: function () { showError('Ralat semasa menyimpan draf.'); },
});
}
if ($('#kueri_respond').length && respondVal && respondVal.trim()) {
$.ajax({
url: "{{ route('overtime::overtime.savekueriresponddetail', $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();
}
}
/* ─── SUBMISSION ─────────────────────────────────────────────── */
function submitTuntutan() {
if (Object.keys(details).length === 0) {
alert('Sila tambah sekurang-kurangnya satu entri sebelum menghantar.');
return;
}
if (!confirm('Hantar tuntutan ini untuk kelulusan? Anda tidak boleh mengubahnya selepas ini.')) return;
if (Object.keys(details).length === 0) { alert('Please add at least one entry before submitting.'); return; }
var respondVal = $('#kueri_respond').val();
if ($('#kueri_respond').length && (!respondVal || !respondVal.trim())) { showError('Please enter a response before resubmitting.'); return; }
if (!confirm('Submit this claim for approval? You will not be able to edit it afterwards.')) return;
function doSubmit() {
$.ajax({
url : "{{ route('overtime::overtime.submitovertimeclaim', $data->id) }}",
url: "{{ route('overtime::overtime.submitovertimeclaim', $data->id) }}",
method: 'POST',
data : { _token: csrfToken() },
data: { _token: csrfToken() },
success: function (res) {
if (res.success) {
showSuccess(res.message);
setTimeout(function () { window.location.href = res.redirect; }, 1500);
} else { showError(res.message); }
if (res.success) { showSuccess(res.message); setTimeout(function () { window.location.href = res.redirect; }, 1500); }
else { showError(res.message); }
},
error: function (xhr) {
var msg = 'Error while submitting claim.';
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);
},
error: function () { showError('Ralat semasa menghantar tuntutan.'); },
});
}
if ($('#kueri_respond').length) {
$.ajax({
url: "{{ route('overtime::overtime.savekueriresponddetail', $data->id) }}",
method: 'POST',
data: { _token: csrfToken(), respond: respondVal.trim() },
success: function () { doSubmit(); },
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 {
doSubmit();
}
}
/* ─── RESET FORM ──────────────────────────────────────────────────────── */
function resetForm() {
$('#ocd_date_input').val('');
$('#ocd_day_type').val('');
$('#ocd_office_start').prop('readonly', false).removeClass('auto-field');
$('#ocd_office_start, #ocd_office_end').val('');
$('#ocd_overtime_from, #ocd_overtime_to').val('');
$('#ocd_total_hours').val('');
$('#ocd_effective_hours').val('');
$('#ocd_tasks').val('');
$('#fk_lkp_project').val('');
$('#field-tarikh, #field-jenis-hari').removeClass('error');
}
</script>
@endsection
@extends('ui::layouts.app')
@section('content')
<style>
.table-uppercase td { text-transform: uppercase; }
</style>
@if(session('success'))
<div class="ui positive message">{{ session('success') }}</div>
@endif
<div class="ui segment">
<a class="ui teal left ribbon label">List of Overtime Claims - HOD Support</a>
<div class="ui segment">
<div class="ui stackable two column grid" style="margin-bottom:1rem;">
<div class="column">
<h1 class="ui header">
<div class="content">
List of Overtime Claims - HOD Support
<div class="sub header">Only claims with status <strong>{{ $statuses[5]->description ?? '-' }}</strong> wil be shown.</div>
</div>
</h1>
</div>
</div>
<div class="ui divider"></div>
<div class="column sixteen wide table-uppercase">
{!!
Suitable::source($list)
->title(__('List of Overtime Claims (HOD)'))
->columns([
\Laravolt\Suitable\Columns\Numbering::make('No'),
['header' => __('Application Number'), 'field' => 'ocm_apply_no', 'sortable' => true],
['header' => __('Name'), 'raw' => function ($row) {
return $row->ocm_staff_name ?: '-';
}],
['header' => __('Month / Year'), 'raw' => function ($row) {
return ($row->ocm_month && $row->ocm_year)
? \Carbon\Carbon::createFromDate($row->ocm_year, $row->ocm_month, 1)->format('M Y')
: '-';
}],
['header' => __('Date Submitted'), 'raw' => function ($row) {
return $row->ocm_submit_date
? \Carbon\Carbon::parse($row->ocm_submit_date)->format('d/m/Y')
: '-';
}],
['header' => __('Status'), 'raw' => function ($row) use ($statuses) {
$label = $statuses[$row->ocm_status]->description ?? '-';
return "<span class='ui label'>{$label}</span>";
}],
['header' => __('Action'), 'raw' => function ($row) {
$view = "<a href='" . route('overtime::overtime.hodviewclaim', $row->id) . "'
class='ui blue button tiny'>
<i class='eye icon'></i> Review
</a>";
return "<div style='text-align:center;'>{$view}</div>";
}],
])
->render()
!!}
</div>
</div>
</div>
@endsection
@extends('ui::layouts.app')
@section('content')
<style>
.rf-summary { background:#ddeeff; border-radius:6px; padding:.9rem 1.2rem; margin-bottom:1.2rem; line-height:1.7; }
.rf-summary .apply-no { font-size:1.05rem; font-weight:700; color:#1a56a0; }
.rf-summary .meta-line { font-size:.92rem; color:#333; }
.rf-tbl { width:100%; border-collapse:collapse; font-size:.85rem; }
.rf-tbl th, .rf-tbl td { border:1px solid #cfd8e3; padding:6px 10px; text-align:center; vertical-align:middle; }
.rf-tbl thead th { background:#2185d0; color:#fff; font-size:.82rem; }
.rf-tbl tbody td.td-left { text-align:left; }
.rf-tbl tfoot td { background:#ddeeff; font-weight:700; color:#1a56a0; border-top:2px solid #2185d0; }
.rf-tbl tfoot .lbl { text-align:right; font-size:.82rem; }
.action-card { background:#fff; border:1px solid #dde3ea; border-left:4px solid #2185d0; border-radius:8px; padding:1.3rem 1.5rem; margin-bottom:1.3rem; }
.action-card .form-title { font-size:1rem; font-weight:700; color:#222; display:flex; align-items:center; gap:.45rem; margin-bottom:1.1rem; }
.rf-footer { display:flex; justify-content:flex-end; gap:.55rem; padding-top:.9rem; border-top:1px solid #e5e8ee; }
.query-history{width:100%;border-collapse:collapse;font-size:.85rem}
.query-history th,.query-history td{border:1px solid #cfd8e3;padding:8px 10px;vertical-align:top}
.query-history th{background:#f5f7fa;text-align:left}
</style>
<div class="ui segment" style="padding-bottom:2rem;">
<div id="success-msg" class="ui positive message" style="display:none; margin-bottom:.75rem;"><p id="success-text"></p></div>
<div id="error-msg" class="ui negative message" style="display:none; margin-bottom:.75rem;"><p id="error-text"></p></div>
<div class="rf-summary">
<div class="apply-no">{{ $data->ocm_apply_no }}</div>
<div class="meta-line">Request by: <strong>{{ $data->ocm_staff_name ?? '-' }}</strong></div>
<div class="meta-line">Department: <strong>{{ $data->ocm_division_label ?? '-' }}</strong></div>
<div class="meta-line">Month/Year: <strong>{{ $data->ocm_month && $data->ocm_year ? \Carbon\Carbon::createFromDate($data->ocm_year, $data->ocm_month, 1)->format('F Y') : '-' }}</strong></div>
<div class="meta-line">
Status:
<span class="ui label" style="font-size:.78rem;">{{ $statuses[$data->ocm_status]->description ?? '-' }}</span>
</div>
<div class="meta-line">Claim Date: <strong>{{ $data->ocm_submit_date ? \Carbon\Carbon::parse($data->ocm_submit_date)->format('d/m/Y') : '-' }}</strong></div>
<div class="meta-line">Approved by: <strong>{{ $data->ocm_approved_by_name ?? '-' }}</strong></div>
<div class="meta-line">Approved Date: <strong>{{ $data->ocm_approved_date ? \Carbon\Carbon::parse($data->ocm_approved_date)->format('d/m/Y') : '-' }}</strong></div>
</div>
<div style="overflow-x:auto; margin-bottom:1.3rem;">
<table class="rf-tbl">
<thead>
<tr>
<th>No</th>
<th>Date</th>
<th>Day Type</th>
<th>Office Hour</th>
<th>OT From</th>
<th>OT To</th>
<th>Project</th>
<th>Tasks</th>
<th>PM Review</th>
<th>Total Hours</th>
<th>Effective Hours</th>
</tr>
</thead>
<tbody>
@forelse($details as $i => $d)
<tr>
<td>{{ $i + 1 }}</td>
<td>{{ $d->ocd_date ? \Carbon\Carbon::parse($d->ocd_date)->format('d/m/Y') : '-' }}</td>
<td>{{ $d->ocd_day_type ?? '-' }}</td>
<td>{{ $d->ocd_office_hour ?? '-' }}</td>
<td>{{ $d->ocd_overtime_from ?? '-' }}</td>
<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><strong>{{ number_format($d->ocd_total_hours ?? 0, 1) }}</strong></td>
<td><strong>{{ number_format($d->ocd_effective_hours ?? 0, 1) }}</strong></td>
</tr>
@empty
<tr><td colspan="11" style="color:#bbb; font-style:italic; padding:1.5rem;">No detail found.</td></tr>
@endforelse
</tbody>
<tfoot>
<tr>
<td colspan="9" class="lbl">GRAND TOTAL HOURS</td>
<td>{{ number_format($details->sum('ocd_total_hours'), 1) }}</td>
<td>{{ number_format($details->sum('ocd_effective_hours'), 1) }}</td>
</tr>
</tfoot>
</table>
</div>
@if($data->ocm_status == 5)
<div class="action-card">
<div class="form-title">
<i class="gavel icon" style="color:#2185d0;"></i>
Review Action
</div>
@if(!empty($pendingPmReviews) && $pendingPmReviews > 0)
<div class="ui negative message" style="margin-top:0.75rem;">
<p>Not all PMs have reviewed yet. HOD support is not allowed until all PM rows are completed.</p>
</div>
@endif
<div style="margin-top:.8rem;">
<div class="ui form">
<div class="grouped fields">
<label style="font-weight:600;">Choose Action</label>
<div class="field">
<div class="ui radio checkbox">
<input type="radio" name="hod_action" value="support" id="hod_action_support" {{ !empty($pendingPmReviews) && $pendingPmReviews > 0 ? 'disabled' : 'checked' }}>
<label for="hod_action_support">Support</label>
</div>
</div>
<div class="field">
<div class="ui radio checkbox">
<input type="radio" name="hod_action" value="query" id="hod_action_query" {{ !empty($pendingPmReviews) && $pendingPmReviews > 0 ? 'checked' : '' }}>
<label for="hod_action_query">Query Back</label>
</div>
</div>
</div>
</div>
<div id="hod-query-box" style="display:none;">
<div class="field">
<label style="font-weight:600; margin-bottom:.4rem; display:block;">Query Notes <span style="color:#e53935;">*</span></label>
<textarea id="kueri_remark" rows="3" placeholder="Provide query reasons..."
style="width:100%; min-height:80px; padding:.7rem 1rem; border:1px solid #d4d8dd; border-radius:6px; resize:vertical;"></textarea>
</div>
</div>
<div style="margin-top:.8rem; display:flex; justify-content:flex-end; gap:.55rem;">
<button type="button" class="ui teal button" id="btn-hod-action" {{ !empty($pendingPmReviews) && $pendingPmReviews > 0 ? 'disabled' : '' }}>
<i class="check icon"></i> Submit
</button>
</div>
</div>
</div>
@endif
<div class="action-card" style="border-left:1px solid #dde3ea;">
<div class="form-title"><i class="comment alternate outline icon"></i>Query History</div>
<div style="overflow-x:auto;">
<table class="query-history">
<thead>
<tr>
<th style="width:180px;">From</th>
<th>Query Notes</th>
<th>Response</th>
<th style="width:150px;">Date</th>
</tr>
</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>
</tr>
@empty
<tr><td colspan="4" style="color:#999;font-style:italic;text-align:center;padding:1rem;">No query history found.</td></tr>
@endforelse
</tbody>
</table>
</div>
</div>
<div class="rf-footer">
<a href="{{ route('overtime::overtime.hodclaimreviewlist') }}" class="ui grey button">
<i class="arrow left icon"></i> Back
</a>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$(document).ready(function () {
function csrfToken() { return $('meta[name="csrf-token"]').attr('content'); }
function showSuccess(msg) { $('#success-text').text(msg); $('#success-msg').show(); $('#error-msg').hide(); }
function showError(msg) { $('#error-text').text(msg); $('#error-msg').show(); $('#success-msg').hide(); }
$('.ui.radio.checkbox').checkbox();
$('input[name="hod_action"]').on('change', function () {
$('#hod-query-box').toggle($(this).val() === 'query');
});
$('#btn-hod-action').on('click', function () {
var action = $('input[name="hod_action"]:checked').val();
if (action === 'support') {
if (!confirm('Support this claim form and forward it to HOD?')) return;
var btn = $(this).addClass('loading disabled');
$.ajax({
url : "{{ route('overtime::overtime.hodsokongclaim', $data->id) }}",
method: 'POST',
data : { _token: csrfToken() },
success: function (res) {
btn.removeClass('loading disabled');
if (res.success) {
showSuccess(res.message);
setTimeout(function () { window.location.href = res.redirect; }, 1200);
} else {
showError(res.message || 'Error while supporting the claim form.');
}
},
error: function (xhr) {
btn.removeClass('loading disabled');
showError((xhr.responseJSON && xhr.responseJSON.message) || 'Network error.');
},
});
return;
}
var remark = $('#kueri_remark').val().trim();
if (!remark) { showError('Please fill in the query notes before sending it back..'); return; }
if (!confirm('Send this query back to the applicant?')) return;
var btn = $(this).addClass('loading disabled');
$.ajax({
url : "{{ route('overtime::overtime.hodkuericlaim', $data->id) }}",
method: 'POST',
data : { _token: csrfToken(), remarks: remark },
success: function (res) {
btn.removeClass('loading disabled');
if (res.success) {
showSuccess(res.message);
setTimeout(function () { window.location.href = res.redirect; }, 1200);
} else {
showError(res.message || 'Error while sending the query back.');
}
},
error: function (xhr) {
btn.removeClass('loading disabled');
showError((xhr.responseJSON && xhr.responseJSON.message) || 'Network error.');
},
});
});
});
</script>
@endsection
......@@ -2,8 +2,8 @@
@section('content')
@include('overtime::overtime.modal.create_modal')
@include('overtime::overtime.modal.view_modal')
@include('overtime::overtime.overtimeclaim.create_modal')
@include('overtime::overtime.overtimeclaim.view_modal')
<style>
.table-uppercase td { text-transform: uppercase; }
......@@ -17,19 +17,19 @@
@endif
<div class="ui segment">
<a class="ui teal left ribbon label">Senarai Tuntutan Lebih Masa</a>
<a class="ui teal left ribbon label">List of Overtime Claim Forms</a>
<div class="ui segment">
<div class="ui stackable two column grid" style="margin-bottom:1rem;">
<div class="column">
<h1 class="ui header">
<div class="content">Senarai Tuntutan Lebih Masa</div>
<div class="content">List of Overtime Claim Forms</div>
</h1>
</div>
<div class="column" style="text-align:right; padding-top:1.2rem;">
<button class="ui teal button" id="btn-tuntutan-baharu">
<i class="plus icon"></i> Tuntutan Baharu
<i class="plus icon"></i> New Claim
</button>
</div>
</div>
......@@ -39,17 +39,17 @@
<div class="column sixteen wide table-uppercase">
{!!
Suitable::source($list)
->title(__('Senarai Tuntutan Lebih Masa'))
->title(__('List of Overtime Claim Forms'))
->columns([
\Laravolt\Suitable\Columns\Numbering::make('No'),
['header' => __('No. Tuntutan'), 'field' => 'ocm_apply_no', 'sortable' => true],
['header' => __('Application Number'), 'field' => 'ocm_apply_no', 'sortable' => true],
['header' => __('Nama'), 'raw' => function ($row) {
['header' => __('Name'), 'raw' => function ($row) {
return $row->ocm_staff_name ?: '-';
}],
['header' => __('Bulan / Tahun'), 'raw' => function ($row) {
['header' => __('Month/Year'), 'raw' => function ($row) {
if ($row->ocm_year && $row->ocm_month) {
$months = [
1=>'Jan',2=>'Feb',3=>'Mac',4=>'Apr',
......@@ -62,46 +62,40 @@
}],
['header' => __('Status'), 'raw' => function ($row) use ($statuses) {
$colours = [
1 => 'grey',
2 => 'blue',
3 => 'blue',
4 => 'red',
5 => 'yellow',
6 => 'orange',
7 => 'yellow',
8 => 'orange',
9 => 'yellow',
10 => 'orange',
11 => 'green',
12 => 'red',
];
$statusRow = $statuses[$row->ocm_status] ?? null;
$label = $statusRow ? $statusRow->description : '-';
$colour = $colours[$row->ocm_status] ?? 'grey';
return "<span class='ui {$colour} label'>{$label}</span>";
$label = $statuses[$row->ocm_status]->description ?? '-';
return "<span class='ui label'>{$label}</span>";
}],
['header' => __('Tindakan'), 'raw' => function ($row) {
['header' => __('Action'), 'raw' => function ($row) {
$view = "<button
class='ui blue button tiny'
onclick='viewTuntutan({$row->id})'>
<i class='eye icon'></i> Lihat
<i class='eye icon'></i> View
</button>";
$edit = "<a href='" . route('overtime::overtime.editovertimeclaim', $row->id) . "'
// Editable only for Draf (1) or Dikueri oleh PM (6)
$canEdit = in_array($row->ocm_status, [1, 6]);
$edit = $canEdit
? "<a href='" . route('overtime::overtime.editovertimeclaim', $row->id) . "'
class='ui yellow button tiny'>
<i class='edit icon'></i> Kemaskini
</a>";
<i class='edit icon'></i> Update
</a>"
: "";
// Batal allowed only from Draf (1) or Dikueri oleh PM (6)
$canBatal = in_array($row->ocm_status, [1, 6]);
$delete = "<button
class='ui red button tiny btn-delete'
$batal = $canBatal
? "<button
class='ui red button tiny btn-batal'
data-id='{$row->id}'
data-url='" . route('overtime::overtime.deleteovertimeclaim', $row->id) . "'>
<i class='trash icon'></i> Padam
</button>";
data-url='" . route('overtime::overtime.batalovertimeclaim', $row->id) . "'>
<i class='ban icon'></i> Cancel
</button>"
: "";
return "{$view} {$edit} {$delete}";
return "<div style='display:flex;justify-content:center;gap:.35rem;flex-wrap:wrap;'>{$view} {$edit} {$batal}</div>";
}],
])
->render()
......@@ -119,8 +113,8 @@
$('#modalTuntutanBaharu').modal({ blurring: true, closable: true }).modal('show');
});
$(document).on('click', '.btn-delete', function () {
if (!confirm('Padam tuntutan ini? Semua butiran dan nombor tuntutan akan dipadamkan.')) return;
$(document).on('click', '.btn-batal', function () {
if (!confirm('Cancel this claim form? This action cannot be undone.')) return;
var url = $(this).data('url');
var row = $(this).closest('tr');
......@@ -131,16 +125,16 @@
data : { _token: $('meta[name="csrf-token"]').attr('content') },
success: function (res) {
if (res.success) {
row.fadeOut(300, function () { $(this).remove(); });
location.reload();
} else {
alert(res.message || 'Ralat semasa memadam.');
alert(res.message || 'Error while canceling. Please try again');
}
},
error: function () {
alert('Ralat rangkaian. Sila cuba lagi.');
alert('Network error.');
},
});
});
});
});
</script>
......
@extends('ui::layouts.app')
@section('content')
<style>
.table-uppercase td { text-transform: uppercase; }
</style>
<div class="ui segment">
<a class="ui teal left ribbon label">List of Overtime Claims - PD Approval</a>
<div class="ui segment">
<div class="ui stackable two column grid" style="margin-bottom:1rem;">
<div class="column">
<h1 class="ui header">
<div class="content">
List of Overtime Claims - PD Approval
<div class="sub header">Claims with status <strong>{{ $statuses[7]->description ?? '-' }}</strong> and <strong>{{ $statuses[11]->description ?? '-' }}</strong>.</div>
</div>
</h1>
</div>
</div>
<div class="ui divider"></div>
<div class="column sixteen wide table-uppercase">
{!!
Suitable::source($list)
->title(__('List of Overtime Claims (PD)'))
->columns([
\Laravolt\Suitable\Columns\Numbering::make('No'),
['header' => __('Application Number'), 'field' => 'ocm_apply_no', 'sortable' => true],
['header' => __('Name'), 'raw' => function ($row) {
return $row->ocm_staff_name ?: '-';
}],
['header' => __('Month / Year'), 'raw' => function ($row) {
return ($row->ocm_month && $row->ocm_year)
? \Carbon\Carbon::createFromDate($row->ocm_year, $row->ocm_month, 1)->format('M Y')
: '-';
}],
['header' => __('Status'), 'raw' => function ($row) use ($statuses) {
$label = $statuses[$row->ocm_status]->description ?? '-';
return "<span class='ui label'>{$label}</span>";
}],
['header' => __('Action'), 'raw' => function ($row) {
$view = "<a href='" . route('overtime::overtime.pdviewclaim', $row->id) . "'
class='ui blue button tiny'>
<i class='eye icon'></i> Lihat
</a>";
return "<div style='text-align:center;'>{$view}</div>";
}],
])
->render()
!!}
</div>
</div>
</div>
@endsection
@extends('ui::layouts.app')
@section('content')
<style>
.rf-summary { background:#ddeeff; border-radius:6px; padding:.9rem 1.2rem; margin-bottom:1.2rem; line-height:1.7; }
.rf-summary .apply-no { font-size:1.05rem; font-weight:700; color:#1a56a0; }
.rf-summary .meta-line { font-size:.92rem; color:#333; }
.rf-tbl { width:100%; border-collapse:collapse; font-size:.85rem; }
.rf-tbl th, .rf-tbl td { border:1px solid #cfd8e3; padding:6px 10px; text-align:center; vertical-align:middle; }
.rf-tbl thead th { background:#2185d0; color:#fff; font-size:.82rem; }
.rf-tbl tbody td.td-left { text-align:left; }
.rf-tbl tfoot td { background:#ddeeff; font-weight:700; color:#1a56a0; border-top:2px solid #2185d0; }
.rf-tbl tfoot .lbl { text-align:right; font-size:.82rem; }
.action-card { background:#fff; border:1px solid #dde3ea; border-left:4px solid #2185d0; border-radius:8px; padding:1.3rem 1.5rem; margin-bottom:1.3rem; }
.action-card .form-title { font-size:1rem; font-weight:700; color:#222; display:flex; align-items:center; gap:.45rem; margin-bottom:1.1rem; }
.rf-footer { display:flex; justify-content:flex-end; gap:.55rem; padding-top:.9rem; border-top:1px solid #e5e8ee; }
.query-history{width:100%;border-collapse:collapse;font-size:.85rem}
.query-history th,.query-history td{border:1px solid #cfd8e3;padding:8px 10px;vertical-align:top}
.query-history th{background:#f5f7fa;text-align:left}
</style>
<div class="ui segment" style="padding-bottom:2rem;">
<div id="success-msg" class="ui positive message" style="display:none; margin-bottom:.75rem;"><p id="success-text"></p></div>
<div id="error-msg" class="ui negative message" style="display:none; margin-bottom:.75rem;"><p id="error-text"></p></div>
<div class="rf-summary">
<div class="apply-no">{{ $data->ocm_apply_no }}</div>
<div class="meta-line">Request by: <strong>{{ $data->ocm_staff_name ?? '-' }}</strong></div>
<div class="meta-line">Department: <strong>{{ $data->ocm_division_label ?? '-' }}</strong></div>
<div class="meta-line">Month/Year: <strong>{{ $data->ocm_month && $data->ocm_year ? \Carbon\Carbon::createFromDate($data->ocm_year, $data->ocm_month, 1)->format('F Y') : '-' }}</strong></div>
<div class="meta-line">
Status:
<span class="ui label" style="font-size:.78rem;">{{ $statuses[$data->ocm_status]->description ?? '-' }}</span>
</div>
<div class="meta-line">Claim Date: <strong>{{ $data->ocm_submit_date ? \Carbon\Carbon::parse($data->ocm_submit_date)->format('d/m/Y') : '-' }}</strong></div>
<div class="meta-line">Approved by: <strong>{{ $data->ocm_approved_by_name ?? '-' }}</strong></div>
<div class="meta-line">Approved Date: <strong>{{ $data->ocm_approved_date ? \Carbon\Carbon::parse($data->ocm_approved_date)->format('d/m/Y') : '-' }}</strong></div>
</div>
<div style="overflow-x:auto; margin-bottom:1.3rem;">
<table class="rf-tbl">
<thead>
<tr>
<th>No</th>
<th>Date</th>
<th>Day Type</th>
<th>Office Hour</th>
<th>OT From</th>
<th>OT To</th>
<th>Project</th>
<th>Tasks</th>
<th>PM Review</th>
<th>Total Hours</th>
<th>Effective Hours</th>
</tr>
</thead>
<tbody>
@forelse($details as $i => $d)
<tr>
<td>{{ $i + 1 }}</td>
<td>{{ $d->ocd_date ? \Carbon\Carbon::parse($d->ocd_date)->format('d/m/Y') : '-' }}</td>
<td>{{ $d->ocd_day_type ?? '-' }}</td>
<td>{{ $d->ocd_office_hour ?? '-' }}</td>
<td>{{ $d->ocd_overtime_from ?? '-' }}</td>
<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><strong>{{ number_format($d->ocd_total_hours ?? 0, 1) }}</strong></td>
<td><strong>{{ number_format($d->ocd_effective_hours ?? 0, 1) }}</strong></td>
</tr>
@empty
<tr><td colspan="11" style="color:#bbb; font-style:italic; padding:1.5rem;">No details.</td></tr>
@endforelse
</tbody>
<tfoot>
<tr>
<td colspan="9" class="lbl">GRAND TOTAL HOURS</td>
<td>{{ number_format($details->sum('ocd_total_hours'), 1) }}</td>
<td>{{ number_format($details->sum('ocd_effective_hours'), 1) }}</td>
</tr>
</tfoot>
</table>
</div>
@if($data->ocm_status == 7)
<div class="action-card">
<div class="form-title">
<i class="gavel icon" style="color:#2185d0;"></i>
Approval Action
</div>
<div class="ui form">
<div class="grouped fields">
<label style="font-weight:600;">Select Action</label>
<div class="field">
<div class="ui radio checkbox">
<input type="radio" name="pd_action" value="support" id="pd_action_support" checked>
<label for="pd_action_support">Support</label>
</div>
</div>
<div class="field">
<div class="ui radio checkbox">
<input type="radio" name="pd_action" value="query" id="pd_action_query">
<label for="pd_action_query">Query Back</label>
</div>
</div>
</div>
</div>
<div id="pd-query-box" style="display:none;">
<div class="field">
<label style="font-weight:600; margin-bottom:.4rem; display:block;">Query Notes <span style="color:#e53935;">*</span></label>
<textarea id="kueri_remark" rows="3" placeholder="Provide query reasons..." style="width:100%; min-height:80px; padding:.7rem 1rem; border:1px solid #d4d8dd; border-radius:6px; resize:vertical;"></textarea>
</div>
</div>
<div style="margin-top:.8rem; display:flex; justify-content:flex-end; gap:.55rem;">
<button type="button" class="ui teal button" id="btn-pd-action">
<i class="check icon"></i> Submit
</button>
</div>
</div>
@endif
<div class="action-card" style="border-left:1px solid #dde3ea;">
<div class="form-title"><i class="comment alternate outline icon"></i>Query History</div>
<div style="overflow-x:auto;">
<table class="query-history">
<thead>
<tr>
<th style="width:180px;">From</th>
<th>Query Notes</th>
<th>Response</th>
<th style="width:150px;">Date</th>
</tr>
</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>
</tr>
@empty
<tr><td colspan="4" style="color:#999;font-style:italic;text-align:center;padding:1rem;">No query history found.</td></tr>
@endforelse
</tbody>
</table>
</div>
</div>
// FOOTER
<div class="rf-footer">
<a href="{{ route('overtime::overtime.pdclaimreviewlist') }}" class="ui grey button">
<i class="arrow left icon"></i> Back
</a>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$(document).ready(function () {
function csrfToken() { return $('meta[name="csrf-token"]').attr('content'); }
function showSuccess(msg) { $('#success-text').text(msg); $('#success-msg').show(); $('#error-msg').hide(); }
function showError(msg) { $('#error-text').text(msg); $('#error-msg').show(); $('#success-msg').hide(); }
$('.ui.radio.checkbox').checkbox();
$('input[name="pd_action"]').on('change', function () {
$('#pd-query-box').toggle($(this).val() === 'query');
});
$('#btn-pd-action').on('click', function () {
var action = $('input[name="pd_action"]:checked').val();
if (action === 'support') {
if (!confirm('Approve this claim? The status will be updated to Application Approved.')) return;
var btn = $(this).addClass('loading disabled');
$.ajax({
url : "{{ route('overtime::overtime.pdsokongclaim', $data->id) }}",
method: 'POST',
data : { _token: csrfToken() },
success: function (res) {
btn.removeClass('loading disabled');
if (res.success) {
showSuccess(res.message);
setTimeout(function () { window.location.href = res.redirect; }, 1200);
} else {
showError(res.message || 'Error while approving.');
}
},
error: function (xhr) {
btn.removeClass('loading disabled');
showError((xhr.responseJSON && xhr.responseJSON.message) || 'Network error.');
},
});
return;
}
var remark = $('#kueri_remark').val().trim();
if (!remark) { showError('Provide query notes before query back.'); return; }
if (!confirm('Send this query back to the applicant?')) return;
var btn = $(this).addClass('loading disabled');
$.ajax({
url : "{{ route('overtime::overtime.pdkuericlaim', $data->id) }}",
method: 'POST',
data : { _token: csrfToken(), remarks: remark },
success: function (res) {
btn.removeClass('loading disabled');
if (res.success) {
showSuccess(res.message);
setTimeout(function () { window.location.href = res.redirect; }, 1200);
} else {
showError(res.message || 'Error while query back.');
}
},
error: function (xhr) {
btn.removeClass('loading disabled');
showError((xhr.responseJSON && xhr.responseJSON.message) || 'Network error.');
},
});
});
});
</script>
@endsection
@extends('ui::layouts.app')
@section('content')
<style>
.table-uppercase td { text-transform: uppercase; }
</style>
<div class="ui segment">
<a class="ui teal left ribbon label">List of Overtime Claim Forms</a>
<div class="ui segment">
<div class="ui two column grid" style="margin-bottom:1rem;">
<div class="column">
<h1 class="ui header">
<div class="content">List of Overtime Claim Forms</div>
</h1>
</div>
</div>
<div class="ui divider"></div>
<div class="column sixteen wide table-uppercase">
{!!
Suitable::source($list)
->title(__('List of Overtime Claim Forms (PM)'))
->columns([
\Laravolt\Suitable\Columns\Numbering::make('No'),
['header' => __('Application Number'), 'field' => 'ocm_apply_no', 'sortable' => true],
['header' => __('Name'), 'raw' => function ($row) {
return $row->ocm_staff_name ?: '-';
}],
['header' => __('Month / Year'), 'raw' => function ($row) {
$months = [
1=>'Jan',2=>'Feb',3=>'Mac',4=>'Apr',
5=>'Mei',6=>'Jun',7=>'Jul',8=>'Ogos',
9=>'Sep',10=>'Okt',11=>'Nov',12=>'Dis',
];
if ($row->ocm_year && $row->ocm_month) {
return ($months[$row->ocm_month] ?? '-') . ' ' . $row->ocm_year;
}
return '-';
}],
['header' => __('Status'), 'raw' => function ($row) use ($statuses) {
$label = $statuses[$row->ocm_status]->description ?? '-';
return "<span class='ui label'>{$label}</span>";
}],
['header' => __('Action'), 'raw' => function ($row) {
return "<a href='" . route('overtime::overtime.pmviewclaim', $row->id) . "'\n class='ui blue button tiny'>\n <i class='eye icon'></i> Review\n </a>";
}],
])
->render()
!!}
</div>
</div>
</div>
@push('scripts')
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</script>
@endpush
@endsection
<style>
.rf-summary {
background: #ddeeff; border-radius: 6px;
padding: .9rem 1.2rem; margin-bottom: 1.2rem; line-height: 1.7;
}
.rf-summary .apply-no { font-size: 1.05rem; font-weight: 700; color: #1a56a0; }
.rf-summary .meta-line { font-size: .92rem; color: #333; }
.rf-tbl { width: 100%; border-collapse: collapse; font-size: .85rem; }
.rf-tbl th, .rf-tbl td {
border: 1px solid #cfd8e3; padding: 6px 10px;
text-align: center; vertical-align: middle;
}
.rf-tbl thead th { background: #2185d0; color: #fff; font-size: .82rem; }
.rf-tbl tbody td.td-left { text-align: left; }
.rf-tbl tfoot td {
background: #ddeeff; font-weight: 700; color: #1a56a0;
border-top: 2px solid #2185d0;
}
.rf-tbl tfoot .lbl { text-align: right; font-size: .82rem; letter-spacing: .04em; }
</style>
<div class="ui segment" style="padding-bottom: 2rem;">
@php
$project = \DB::table('lkp_project')->where('id', $main->orm_project ?? null)->value('p_project_description');
$department = \DB::table('lkp_department')->where('id', $main->orm_department ?? null)->value('name');
$requestedBy = \DB::table('project_team')->where('id', $main->orm_requested_by_id ?? null)->value('pt_team');
@endphp
<div class="rf-summary">
<div class="apply-no">{{ $main->orm_apply_no ?? ('#' . $main->id) }}</div>
<div class="meta-line"><strong>Project:</strong> {{ $project ?? '-' }}</div>
<div class="meta-line"><strong>Date:</strong> {{ $main->orm_date ? \Carbon\Carbon::parse($main->orm_date)->format('d/m/Y') : '-' }}</div>
<div class="meta-line"><strong>Requested By:</strong> {{ $requestedBy ?? '-' }}</div>
<div class="meta-line"><strong>Department:</strong> {{ $department ?? '-' }}</div>
</div>
<div style="overflow-x:auto;">
<table class="rf-tbl">
<thead>
<tr>
<th>No</th>
<th>Name</th>
<th>Overtime Month</th>
<th>Budgeted</th>
<th>Utilised to Date</th>
<th>Planned OT Hour</th>
<th>Balance</th>
<th>Reason</th>
<th>Total Hours</th>
</tr>
</thead>
<tbody>
@forelse($details as $i => $d)
<tr>
<td>{{ $i + 1 }}</td>
<td class="td-left">{{ $d->ord_name ?? '-' }}</td>
<td>{{ $d->ord_month_of_overtime ? \Carbon\Carbon::parse($d->ord_month_of_overtime)->format('M Y') : '-' }}</td>
<td>{{ number_format($d->ord_budgeted ?? 0, 2) }}</td>
<td>{{ number_format($d->ord_utilised_to_date ?? 0, 2) }}</td>
<td>{{ number_format($d->ord_planned_ot_hour ?? 0, 2) }}</td>
<td>{{ number_format($d->ord_balance ?? 0, 2) }}</td>
<td class="td-left">{{ $d->ord_reason ?? '-' }}</td>
<td><strong>{{ number_format($d->ord_total_hours ?? 0, 2) }}</strong></td>
</tr>
@empty
<tr><td colspan="9" style="color:#bbb; font-style:italic; padding:1.5rem;">No details.</td></tr>
@endforelse
</tbody>
<tfoot>
<tr>
<td colspan="8" class="lbl">TOTAL HOURS OVERALL</td>
<td>{{ number_format($details->sum('ord_total_hours'), 2) }}</td>
</tr>
</tfoot>
</table>
</div>
</div>
\ No newline at end of file
@extends('ui::layouts.app')
@section('content')
<style>
select option:disabled {
background-color: #f2f2f2;
color: #7a7a7a;
}
.ot-summary {
background: #ddeeff; border-radius: 6px;
padding: .9rem 1.2rem; margin-bottom: 1.2rem; line-height: 1.7;
}
.ot-summary .apply-no { font-size: 1.05rem; font-weight: 700; color: #1a56a0; }
.ot-summary .meta-line { font-size: .92rem; color: #333; }
.ot-card {
background: #fff; border: 1px solid #dde3ea;
border-radius: 8px; padding: 1.2rem 1.4rem; margin-bottom: 1.3rem;
}
.ot-card .card-title {
font-size: 1rem; font-weight: 700; color: #222;
display: flex; align-items: center; gap: .45rem; margin-bottom: .9rem;
}
.ot-tbl { width: 100%; border-collapse: collapse; font-size: .85rem; }
.ot-tbl th, .ot-tbl td {
border: 1px solid #cfd8e3; padding: 6px 10px;
text-align: center; vertical-align: middle;
}
.ot-tbl thead th { background: #2185d0; color: #fff; font-size: .82rem; }
.ot-tbl tbody tr.disabled-row td { color: #8f9499; background: #f6f8fa; }
.ot-tbl tbody td.td-shade { background: #f0f7ff; }
.ot-tbl tbody td.td-disabled { color: #8f9499; }
.ot-tbl tbody td.td-tasks { text-align: left; }
.ot-tbl tbody td.td-project { text-align: left; }
.ot-tbl tfoot td {
background: #ddeeff; font-weight: 700; color: #1a56a0;
border-top: 2px solid #2185d0;
}
.ot-tbl tfoot .lbl { text-align: right; font-size: .82rem; letter-spacing: .04em; }
.query-history{width:100%;border-collapse:collapse;font-size:.85rem;margin-bottom:1.3rem}
.query-history th,.query-history td{border:1px solid #cfd8e3;padding:8px 10px;vertical-align:top}
.query-history th{background:#f5f7fa;text-align:left}
.action-card {
background: #fff; border: 1px solid #dde3ea;
border-left: 4px solid #2185d0; border-radius: 8px;
padding: 1.3rem 1.5rem; margin-bottom: 1.3rem;
}
.action-card .form-title {
font-size: 1rem; font-weight: 700; color: #222;
display: flex; align-items: center; gap: .45rem; margin-bottom: 1.1rem;
}
.ot-footer {
display: flex; justify-content: flex-end; gap: .55rem;
padding-top: .9rem; border-top: 1px solid #e5e8ee;
}
</style>
<div class="ui segment" style="padding-bottom: 2rem;">
<div id="success-msg" class="ui positive message" style="display:none; margin-bottom:.75rem;">
<p id="success-text"></p>
</div>
<div id="error-msg" class="ui negative message" style="display:none; margin-bottom:.75rem;">
<p id="error-text"></p>
</div>
@php
$msMonths = [
1=>'Januari',2=>'Februari',3=>'Mac',4=>'April',5=>'Mei',6=>'Jun',
7=>'Julai',8=>'Ogos',9=>'September',10=>'Oktober',11=>'November',12=>'Disember',
];
$monthLabel = ($main->ocm_month && $main->ocm_year)
? ($msMonths[$main->ocm_month] ?? '-') . ' ' . $main->ocm_year
: '-';
@endphp
<div class="ot-summary">
<div class="apply-no">{{ $main->ocm_apply_no }}</div>
<div class="meta-line">Request by: <strong>{{ $main->ocm_staff_name }}</strong></div>
<div class="meta-line">Department: <strong>{{ $main->ocm_division_label ?? '-' }}</strong></div>
<div class="meta-line">Month/Year: <strong>{{ $monthLabel }}</strong></div>
<div class="meta-line">
Status: <span class="ui label" style="font-size:.78rem;">{{ $statuses[$main->ocm_status]->description ?? '-' }}</span>
</div>
<div class="meta-line">Claim Date: <strong>{{ $main->ocm_submit_date ? \Carbon\Carbon::parse($main->ocm_submit_date)->format('d/m/Y') : '-' }}</strong></div>
<div class="meta-line">Approved by: <strong>{{ $main->ocm_approved_by_name ?? '-' }}</strong></div>
<div class="meta-line">Approved Date: <strong>{{ $main->ocm_approved_date ? \Carbon\Carbon::parse($main->ocm_approved_date)->format('d/m/Y') : '-' }}</strong></div>
</div>
<div class="ot-card">
<div class="card-title">
<i class="table icon" style="color:#2185d0;"></i>
Claim Details
</div>
<div style="overflow-x:auto;">
<table class="ot-tbl">
<thead>
<tr>
<th>Date</th>
<th>Day Type</th>
<th>Office Hour</th>
<th>OT From</th>
<th>OT To</th>
<th>Project</th>
<th>Tasks</th>
<th>PM Review</th>
<th>Total Hours</th>
<th>Effective Hours</th>
</tr>
</thead>
<tbody>
@forelse($details as $d)
<tr class="{{ $d->pm_owned ? '' : 'disabled-row' }}">
<td>{{ \Carbon\Carbon::parse($d->ocd_date)->format('d/m/Y') }}</td>
<td class="td-shade">{{ $d->ocd_day_type ?: '-' }}</td>
<td class="td-shade">{{ $d->ocd_office_hour ?: '-' }}</td>
<td>{{ $d->ocd_overtime_from ?: '-' }}</td>
<td>{{ $d->ocd_overtime_to ?: '-' }}</td>
<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>
@else
<span class="ui orange label">Pending</span>
@endif
@else
<span class="ui grey label">Restricted</span>
@endif
</td>
<td><strong>{{ number_format($d->ocd_total_hours ?? 0, 1) }}</strong></td>
<td><strong>{{ number_format($d->ocd_effective_hours, 1) }}</strong></td>
</tr>
@empty
<tr><td colspan="10" style="color:#bbb; font-style:italic; padding:1.5rem;">Tiada entri.</td></tr>
@endforelse
</tbody>
<tfoot>
<tr>
<td colspan="8" class="lbl">GRAND TOTAL HOURS</td>
<td>{{ number_format($details->sum('ocd_total_hours'), 1) }}</td>
<td>{{ number_format($details->sum('ocd_effective_hours'), 1) }}</td>
</tr>
</tfoot>
</table>
</div>
</div>
@if(in_array($main->ocm_status, [2, 3]))
<div class="action-card">
<div class="form-title">
<i class="gavel icon" style="color:#2185d0;"></i>
Action
</div>
<div class="ui form" style="margin-bottom:1.2rem;">
<div class="grouped fields">
<label style="font-weight:600;">Choose Action</label>
<div class="field">
<div class="ui radio checkbox">
<input type="radio" name="tindakan_choice" value="sokong" id="radio_sokong" checked>
<label for="radio_sokong">Support</label>
</div>
</div>
<div class="field">
<div class="ui radio checkbox">
<input type="radio" name="tindakan_choice" value="kueri" id="radio_kueri">
<label for="radio_kueri">Query</label>
</div>
</div>
</div>
</div>
<div id="panel-sokong">
<p style="color:#888; font-size:.88rem;">
Select the approved request form, then match the month/year and the requested staff name to continue the support.
</p>
<div class="ui form">
<div class="field">
<label style="font-weight:600;">Approved Request Form</label>
<select id="request_form_id" style="width:100%; padding:8px; border:1px solid rgba(34,36,38,.15); border-radius:4px;">
<option value="">-- Select Approved Request Form --</option>
@foreach($forms as $f)
<option value="{{ $f->id }}"
data-month="{{ $f->request_month_year }}"
data-staff="{{ $f->request_staff_name }}"
data-staff-list="{{ $f->request_staff_names->implode('||') }}"
{{ $f->is_pm_project ? '' : 'disabled' }}>
{{ $f->display_label ?? '-' }}{{ $f->is_pm_project ? '' : ' - Not your project' }}
</option>
@endforeach
</select>
</div>
<div class="two fields">
<div class="field">
<label style="font-weight:600;">Month / Year</label>
<select id="request_form_month" style="width:100%; padding:8px; border:1px solid rgba(34,36,38,.15); border-radius:4px;" disabled>
<option value="">-- Select Month / Year --</option>
</select>
</div>
<div class="field">
<label style="font-weight:600;">Staff Name</label>
<select id="request_form_staff" style="width:100%; padding:8px; border:1px solid rgba(34,36,38,.15); border-radius:4px;" disabled>
<option value="">-- Select Staff Name --</option>
</select>
</div>
</div>
<div style="display:flex; gap:.5rem; align-items:flex-start; margin-top:.75rem;">
<button type="button" id="btn-view-request-form" class="ui blue button" style="white-space:nowrap;" disabled>
<i class="eye icon"></i> View
</button>
</div>
@if($forms->isEmpty())
<p style="color:#bbb; font-style:italic; margin-top:.5rem;">No approved application forms were found.</p>
@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' : '' }}>
<i class="check icon"></i> Mark Reviewed
</button>
</div>
</div>
<div id="panel-kueri" style="display:none;">
<div class="field">
<label style="font-weight:600; margin-bottom:.5rem; display:block;">
Query Notes <span style="color:#e53935;">*</span>
</label>
<textarea id="kueri_remarks" rows="6"
placeholder="Provide reason for query...."
style="width:100%; min-height:140px; padding:.85rem 1rem; font-size:.95rem;
border:1px solid #d4d8dd; border-radius:6px; resize:vertical;
font-family:inherit; line-height:1.5;"></textarea>
</div>
<div style="display: flex; justify-content: flex-end; margin-top: 1rem;">
<button type="button" class="ui orange button" id="btn-kueri">
<i class="reply icon"></i> Query &amp; Return to Applicant
</button>
</div>
</div>
</div>
@endif
<div class="ot-card">
<div class="card-title"><i class="comment alternate outline icon" style="color:#2185d0;"></i>Query History</div>
<div style="overflow-x:auto;">
<table class="query-history">
<thead>
<tr>
<th style="width:180px;">From</th>
<th>Query Notes</th>
<th>Response</th>
<th style="width:150px;">Date</th>
</tr>
</thead>
<tbody>
@forelse($queryHistory 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>
</tr>
@empty
<tr><td colspan="4" style="color:#999;font-style:italic;text-align:center;padding:1rem;">No query history found.</td></tr>
@endforelse
</tbody>
</table>
</div>
</div>
{{-- FOOTER --}}
<div class="ot-footer">
<a href="{{ route('overtime::overtime.projectmanager.list') }}" class="ui grey button">
<i class="arrow left icon"></i> Back
</a>
</div>
</div>
<div class="ui modal" id="requestFormModal" style="max-width:95vw; width:1100px;">
<div class="header">
<i class="file alternate outline icon"></i>
Request Form Preview
</div>
<div class="scrolling content" id="requestFormModalBody">
<div style="text-align:center; padding:2rem; color:#888;">
<i class="spinner loading icon"></i> Loading request form...
</div>
</div>
<div class="actions">
<button type="button" class="ui grey button" onclick="$('#requestFormModal').modal('hide');">
<i class="times icon"></i> Close
</button>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$(document).ready(function () {
$('.ui.radio.checkbox').checkbox();
$('input[name="tindakan_choice"]').on('change', function () {
var choice = $(this).val();
if (choice === 'sokong') {
$('#panel-sokong').show();
$('#panel-kueri').hide();
} else {
$('#panel-sokong').hide();
$('#panel-kueri').show();
}
});
function csrfToken() { return $('meta[name="csrf-token"]').attr('content'); }
function showSuccess(msg) { $('#success-text').text(msg); $('#success-msg').show(); $('#error-msg').hide(); }
function showError(msg) { $('#error-text').text(msg); $('#error-msg').show(); $('#success-msg').hide(); }
var REQUEST_FORM_VIEW_BASE = "{{ route('overtime::overtime.pmviewrequestform', ':id') }}";
function resetSelection() {
$('#request_form_month').prop('disabled', true).empty().append('<option value="">-- Select Month / Year --</option>');
$('#request_form_staff').prop('disabled', true).empty().append('<option value="">-- Select Staff Name --</option>');
$('#btn-view-request-form').data('form-id', '').prop('disabled', true);
}
$('#request_form_id').on('change', function () {
var formId = $(this).val();
var selectedOption = $(this).find('option:selected');
resetSelection();
if (!formId) {
return;
}
var month = selectedOption.data('month');
var staff = selectedOption.data('staff');
var staffList = selectedOption.data('staff-list');
if (month) {
$('#request_form_month').append('<option value="' + month + '">' + month + '</option>');
$('#request_form_month').prop('disabled', false).val(month);
}
if (staffList) {
var names = staffList.split('||');
$.each(names, function (index, name) {
if (name) {
$('#request_form_staff').append('<option value="' + name + '">' + name + '</option>');
}
});
$('#request_form_staff').prop('disabled', false).val(staff || names[0] || '');
} else if (staff) {
$('#request_form_staff').append('<option value="' + staff + '">' + staff + '</option>');
$('#request_form_staff').prop('disabled', false).val(staff);
}
$('#btn-view-request-form').data('form-id', formId).prop('disabled', false);
});
$('#btn-view-request-form').on('click', function (e) {
e.preventDefault();
var formId = $(this).data('form-id') || $('#request_form_id').val();
if (!formId) {
showError('Please select the request form first.');
return;
}
$('#requestFormModalBody').html('<div style="text-align:center; padding:2rem; color:#888;"><i class="spinner loading icon"></i> Loading request form...</div>');
$('#requestFormModal').modal({ blurring: true, closable: true }).modal('show');
$.ajax({
url: REQUEST_FORM_VIEW_BASE.replace(':id', formId),
method: 'GET',
success: function (html) {
$('#requestFormModalBody').html(html);
$('#requestFormModal').modal('refresh');
},
error: function () {
$('#requestFormModalBody').html('<div class="ui negative message"><p>Unable to load the request form.</p></div>');
},
});
});
$('#btn-sokong').on('click', function () {
var formId = $('#request_form_id').val();
var month = $('#request_form_month').val();
var staff = $('#request_form_staff').val();
if (!formId) { showError('Please choose one request form.'); return; }
if (!month) { showError('Please choose the month/year related to the request form.'); return; }
if (!staff) { showError('Please choose the staff name from the request form.'); return; }
if (!confirm('Confirm this review and mark the project rows as reviewed?')) return;
$.ajax({
url : "{{ route('overtime::overtime.pmmarkreviewed', $main->id) }}",
method: 'POST',
data : { _token: csrfToken(), request_form_id: formId },
success: function (res) {
if (res.success) {
showSuccess(res.message);
setTimeout(function () { window.location.href = res.redirect; }, 1200);
} else {
showError(res.message || 'Error while marking reviewed.');
}
},
error: function (xhr) {
var msg = 'Network error.';
if (xhr.responseJSON && xhr.responseJSON.message) msg = xhr.responseJSON.message;
showError(msg);
},
});
});
$('#btn-kueri').on('click', function () {
var remarks = $('#kueri_remarks').val().trim();
if (!remarks) { showError('Provide query reason.'); return; }
if (!confirm('Verify the query and send it back to the applicant.?')) return;
$.ajax({
url : "{{ route('overtime::overtime.pmkuericlaim', $main->id) }}",
method: 'POST',
data : { _token: csrfToken(), remarks: remarks },
success: function (res) {
if (res.success) {
showSuccess(res.message);
setTimeout(function () { window.location.href = res.redirect; }, 1200);
} else {
showError(res.message || 'Error while query.');
}
},
error: function (xhr) {
var msg = 'Network error.';
if (xhr.responseJSON && xhr.responseJSON.message) msg = xhr.responseJSON.message;
showError(msg);
},
});
});
});
</script>
@endsection
......@@ -30,21 +30,21 @@
#modalViewTuntutan .vm-loading { text-align: center; padding: 2.5rem; color: #888; }
</style>
<div class="ui large modal" id="modalViewTuntutan">
<div class="ui fullscreen modal" id="modalViewTuntutan">
<div class="header">
<i class="eye icon"></i>
Lihat Tuntutan Lebih Masa
View Overtime Claim Form
</div>
<div class="scrolling content" id="vm-claim-content">
<div class="vm-loading">
<i class="spinner loading icon"></i> Memuatkan data…
<i class="spinner loading icon"></i> Loading data…
</div>
</div>
<div class="actions">
<button class="ui grey button" onclick="$('#modalViewTuntutan').modal('hide');">
<i class="times icon"></i> Tutup
<i class="times icon"></i> Close
</button>
</div>
</div>
......@@ -72,7 +72,7 @@ function vcmFmtDate(str) {
function viewTuntutan(id) {
$('#vm-claim-content').html(
'<div class="vm-loading"><i class="spinner loading icon"></i> Memuatkan data…</div>'
'<div class="vm-loading"><i class="spinner loading icon"></i> Loading data…</div>'
);
$('#modalViewTuntutan').modal({ blurring: true, closable: true }).modal('show');
......@@ -85,21 +85,20 @@ function viewTuntutan(id) {
} else {
$('#vm-claim-content').html(
'<div class="ui negative message"><p>'
+ vcmEsc(res.message || 'Ralat semasa memuatkan data.')
+ vcmEsc(res.message || 'Error occurred while loading data.')
+ '</p></div>'
);
}
},
error: function () {
$('#vm-claim-content').html(
'<div class="ui negative message"><p>Ralat rangkaian. Sila cuba lagi.</p></div>'
'<div class="ui negative message"><p>Network error. Please try again.</p></div>'
);
},
});
}
function vcmBuildHtml(main, details) {
// Status label comes directly from the controller (lkp_status lookup)
var badge = '<span class="ui label" style="font-size:.78rem;">' + vcmEsc(main.ocm_status_label || '-') + '</span>';
var monthName = (main.ocm_month && main.ocm_year)
......@@ -108,24 +107,26 @@ function vcmBuildHtml(main, details) {
var html = '<div class="vm-summary">'
+ '<div class="apply-no">' + vcmEsc(main.ocm_apply_no || '-') + '</div>'
+ '<div class="meta-line">Nama: <strong>' + vcmEsc(main.ocm_staff_name || '-') + '</strong></div>'
+ '<div class="meta-line">Bulan: <strong>' + monthName + '</strong></div>'
+ '<div class="meta-line">Status: ' + badge + '</div>';
if (main.ocm_submit_date)
html += '<div class="meta-line">Tarikh Hantar: <strong>' + vcmFmtDate(main.ocm_submit_date) + '</strong></div>';
if (main.ocm_approved_date)
html += '<div class="meta-line">Tarikh Lulus: <strong>' + vcmFmtDate(main.ocm_approved_date) + '</strong></div>';
+ '<div class="meta-line">Request by: <strong>' + vcmEsc(main.ocm_staff_name || '-') + '</strong></div>'
+ '<div class="meta-line">Department: <strong>' + vcmEsc(main.ocm_division_label || '-') + '</strong></div>'
+ '<div class="meta-line">Month/Year: <strong>' + monthName + '</strong></div>'
+ '<div class="meta-line">Status: ' + badge + '</div>'
+ '<div class="meta-line">Claim Date: <strong>' + vcmFmtDate(main.ocm_submit_date) + '</strong></div>'
+ '<div class="meta-line">Approved by: <strong>' + vcmEsc(main.ocm_approved_by_name || '-') + '</strong></div>'
+ '<div class="meta-line">Approved Date: <strong>' + vcmFmtDate(main.ocm_approved_date) + '</strong></div>'
html += '</div>';
html += '<div style="overflow-x:auto;">'
+ '<table class="vm-tbl"><thead>'
+ '<tr class="grp">'
+ '<th rowspan="2" class="vm-plain" style="min-width:105px;vertical-align:middle;">Tarikh</th>'
+ '<th rowspan="2" class="vm-plain" style="min-width:110px;vertical-align:middle;">Jenis Hari</th>'
+ '<th rowspan="2" class="vm-plain" style="min-width:105px;vertical-align:middle;">Date</th>'
+ '<th rowspan="2" class="vm-plain" style="min-width:110px;vertical-align:middle;">Day Type</th>'
+ '<th rowspan="2" class="vm-plain" style="min-width:110px;vertical-align:middle;">Office Hour</th>'
+ '<th colspan="2" style="min-width:180px;">Overtime</th>'
+ '<th rowspan="2" style="min-width:180px;vertical-align:middle;">Projek</th>'
+ '<th rowspan="2" style="min-width:280px;vertical-align:middle;">Tasks</th>'
+ '<th rowspan="2" style="min-width:180px;vertical-align:middle;">Project</th>'
+ '<th rowspan="2" style="min-width:220px;vertical-align:middle;">Tasks</th>'
+ '<th rowspan="2" class="vm-light" style="min-width:90px; vertical-align:middle;">PM Review</th>'
+ '<th rowspan="2" class="vm-light" style="min-width:90px; vertical-align:middle;">Total Hours</th>'
+ '<th rowspan="2" class="vm-light" style="min-width:90px; vertical-align:middle;">Effective Hours</th>'
+ '</tr>'
+ '<tr class="grp">'
......@@ -135,12 +136,13 @@ function vcmBuildHtml(main, details) {
+ '</thead><tbody>';
if (!details || details.length === 0) {
html += '<tr><td colspan="8" class="vm-empty">Tiada butiran ditambah.</td></tr>'
html += '<tr><td colspan="10" class="vm-empty">No details added.</td></tr>'
+ '</tbody></table></div>';
return html;
}
var grandTotal = 0;
var grandTotalTotal = 0;
var grandTotalEffective = 0;
details.forEach(function (d) {
var dt = new Date(d.ocd_date);
......@@ -149,8 +151,10 @@ function vcmBuildHtml(main, details) {
var dateLabel = vcmPad(day) + ' ' + VCM_MONTHS[dt.getMonth()] + ' ' + dt.getFullYear()
+ '<br><small style="color:#999;font-weight:400;">' + dayName + '</small>';
var hours = parseFloat(d.ocd_effective_hours) || 0;
grandTotal += hours;
var totalHours = parseFloat(d.ocd_total_hours) || 0;
var effectiveHours = parseFloat(d.ocd_effective_hours) || 0;
grandTotalTotal += totalHours;
grandTotalEffective += effectiveHours;
html += '<tr>'
+ '<td>' + dateLabel + '</td>'
......@@ -160,14 +164,20 @@ 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><strong>' + hours.toFixed(1) + '</strong></td>'
+ '<td>' + (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>'
+ '</tr>';
});
html += '</tbody>'
+ '<tfoot><tr>'
+ '<td colspan="7" class="lbl">GRAND TOTAL HOURS</td>'
+ '<td style="text-align:center;">' + grandTotal.toFixed(1) + '</td>'
+ '<td colspan="8" class="lbl">GRAND TOTAL HOURS</td>'
+ '<td style="text-align:center;">' + grandTotalTotal.toFixed(1) + '</td>'
+ '<td style="text-align:center;">' + grandTotalEffective.toFixed(1) + '</td>'
+ '</tr></tfoot>'
+ '</table></div>';
......
<?php
$months = ['Jan','Feb','Mac','Apr','Mei','Jun','Jul','Ogos','Sep','Okt','Nov','Dis'];
$days = ['Ahad','Isnin','Selasa','Rabu','Khamis','Jumaat','Sabtu'];
$monthNames = [
'Januari','Februari','Mac','April','Mei','Jun',
'Julai','Ogos','September','Oktober','November','Disember'
];
$escape = function ($value) {
if ($value === null || $value === '') {
return '';
}
return htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8');
};
$formatDate = function ($value) use ($escape) {
if (empty($value)) {
return '-';
}
try {
$date = $value instanceof \DateTimeInterface ? $value : \Carbon\Carbon::parse($value);
return $date->format('d/m/Y');
} catch (\Throwable $e) {
return '-';
}
};
$monthName = ($main['ocm_month'] && $main['ocm_year'])
? ($monthNames[(int) $main['ocm_month'] - 1] ?? '-') . ' ' . $main['ocm_year']
: '-';
$badge = '<span class="ui label" style="font-size:.78rem;">' . $escape($main['ocm_status_label'] ?? '-') . '</span>';
$grandTotalTotal = 0;
$grandTotalEffective = 0;
?>
<div class="vm-summary">
<div class="apply-no">{{ $escape($main['ocm_apply_no'] ?? '-') }}</div>
<div class="meta-line">Request by: <strong>{{ $escape($main['ocm_staff_name'] ?? '-') }}</strong></div>
<div class="meta-line">Department: <strong>{{ $escape($main['ocm_division_label'] ?? '-') }}</strong></div>
<div class="meta-line">Month/Year: <strong>{{ $escape($monthName) }}</strong></div>
<div class="meta-line">Status: {!! $badge !!}</div>
<div class="meta-line">Claim Date: <strong>{{ $formatDate($main['ocm_submit_date'] ?? null) }}</strong></div>
<div class="meta-line">Approved by: <strong>{{ $escape($main['ocm_approved_by_name'] ?? '-') }}</strong></div>
<div class="meta-line">Approved Date: <strong>{{ $formatDate($main['ocm_approved_date'] ?? null) }}</strong></div>
</div>
<div style="overflow-x:auto;">
<table class="vm-tbl">
<thead>
<tr class="grp">
<th rowspan="2" class="vm-plain" style="min-width:105px;vertical-align:middle;">Date</th>
<th rowspan="2" class="vm-plain" style="min-width:110px;vertical-align:middle;">Day Type</th>
<th rowspan="2" class="vm-plain" style="min-width:110px;vertical-align:middle;">Office Hour</th>
<th colspan="2" style="min-width:180px;">Overtime</th>
<th rowspan="2" style="min-width:180px;vertical-align:middle;">Project</th>
<th rowspan="2" style="min-width:220px;vertical-align:middle;">Tasks</th>
<th rowspan="2" class="vm-light" style="min-width:90px; vertical-align:middle;">PM Review</th>
<th rowspan="2" class="vm-light" style="min-width:90px; vertical-align:middle;">Total Hours</th>
<th rowspan="2" class="vm-light" style="min-width:90px; vertical-align:middle;">Effective Hours</th>
</tr>
<tr class="grp">
<th class="vm-light" style="min-width:85px;">From</th>
<th class="vm-light" style="min-width:85px;">To</th>
</tr>
</thead>
<tbody>
@if (empty($details))
<tr><td colspan="10" class="vm-empty">No details added.</td></tr>
@else
@foreach ($details as $detail)
@php
try {
$date = !empty($detail['ocd_date']) ? \Carbon\Carbon::parse($detail['ocd_date']) : null;
} catch (\Throwable $e) {
$date = null;
}
$dayName = $date ? $days[$date->dayOfWeek] : '-';
$dateLabel = $date ? $date->format('d') . ' ' . ($months[$date->month - 1] ?? '') . ' ' . $date->format('Y') . '<br><small style="color:#999;font-weight:400;">' . $dayName . '</small>' : '-';
$totalHours = (float) ($detail['ocd_total_hours'] ?? 0);
$effectiveHours = (float) ($detail['ocd_effective_hours'] ?? 0);
$grandTotalTotal += $totalHours;
$grandTotalEffective += $effectiveHours;
@endphp
<tr>
<td>{!! $dateLabel !!}</td>
<td class="vm-shade">{{ $escape($detail['ocd_day_type'] ?? '-') }}</td>
<td class="vm-shade">{{ $escape($detail['ocd_office_hour'] ?? '-') }}</td>
<td>{{ $escape($detail['ocd_overtime_from'] ?? '-') }}</td>
<td>{{ $escape($detail['ocd_overtime_to'] ?? '-') }}</td>
<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>
@else
<span class="ui orange label">Pending</span>
@endif
</td>
<td><strong>{{ number_format($totalHours, 1) }}</strong></td>
<td><strong>{{ number_format($effectiveHours, 1) }}</strong></td>
</tr>
@endforeach
@endif
</tbody>
@if (!empty($details))
<tfoot>
<tr>
<td colspan="8" class="lbl">GRAND TOTAL HOURS</td>
<td style="text-align:center;">{{ number_format($grandTotalTotal, 1) }}</td>
<td style="text-align:center;">{{ number_format($grandTotalEffective, 1) }}</td>
</tr>
</tfoot>
@endif
</table>
</div>
@extends('ui::layouts.app')
@section('content')
<style>
.table-uppercase td { text-transform: uppercase; }
</style>
<div class="ui segment">
<a class="ui teal left ribbon label">Review of Overtime Request Forms (HOD)</a>
<div class="ui segment">
<div class="ui stackable two column grid" style="margin-bottom:1rem;">
<div class="column">
<h1 class="ui header">
<div class="content">List of Forms Awaiting HOD Review</div>
</h1>
</div>
</div>
<div class="ui divider"></div>
<div class="column sixteen wide table-uppercase">
{!!
Suitable::source($list)
->title(__('List of Overtime Request Forms (HOD)'))
->columns([
\Laravolt\Suitable\Columns\Numbering::make('No'),
['header' => __('Application Number'), 'field' => 'orm_apply_no', 'sortable' => true],
['header' => __('Project'), 'raw' => function ($row) {
return \DB::table('lkp_project')->where('id', $row->orm_project)->value('p_project_description') ?? '-';
}],
['header' => __('Date'), 'raw' => function ($row) {
return $row->orm_date ? \Carbon\Carbon::parse($row->orm_date)->format('d/m/Y') : '-';
}],
['header' => __('Status'), 'raw' => function ($row) use ($statuses) {
$label = $statuses[$row->orm_status]->description ?? '-';
return "<span class='ui label'>{$label}</span>";
}],
['header' => __('Action'), 'raw' => function ($row) {
return "<a href='" . route('overtime::overtime.hodviewrequest', $row->id) . "'
class='ui blue button tiny'>
<i class='eye icon'></i> View
</a>";
}],
])
->render()
!!}
</div>
</div>
</div>
@endsection
@extends('ui::layouts.app')
@section('content')
<style>
.rf-summary {
background: #ddeeff; border-radius: 6px;
padding: .9rem 1.2rem; margin-bottom: 1.2rem; line-height: 1.7;
}
.rf-summary .apply-no { font-size: 1.05rem; font-weight: 700; color: #1a56a0; }
.rf-summary .meta-line { font-size: .92rem; color: #333; }
.rf-tbl { width: 100%; border-collapse: collapse; font-size: .85rem; }
.rf-tbl th, .rf-tbl td {
border: 1px solid #cfd8e3; padding: 6px 10px;
text-align: center; vertical-align: middle;
}
.rf-tbl thead th { background: #2185d0; color: #fff; font-size: .82rem; }
.rf-tbl tbody td.td-left { text-align: left; }
.rf-tbl tfoot td {
background: #ddeeff; font-weight: 700; color: #1a56a0;
border-top: 2px solid #2185d0;
}
.rf-tbl tfoot .lbl { text-align: right; font-size: .82rem; letter-spacing: .04em; }
.action-card {
background: #fff; border: 1px solid #dde3ea;
border-left: 4px solid #2185d0; border-radius: 8px;
padding: 1.3rem 1.5rem; margin-bottom: 1.3rem;
}
.action-card .form-title {
font-size: 1rem; font-weight: 700; color: #222;
display: flex; align-items: center; gap: .45rem; margin-bottom: 1.1rem;
}
.rf-footer {
display: flex; justify-content: flex-end; gap: .55rem;
padding-top: .9rem; border-top: 1px solid #e5e8ee;
}
.query-history{width:100%;border-collapse:collapse;font-size:.85rem}
.query-history th,.query-history td{border:1px solid #cfd8e3;padding:8px 10px;vertical-align:top}
.query-history th{background:#f5f7fa;text-align:left}
</style>
<div class="ui segment" style="padding-bottom: 2rem;">
<div id="success-msg" class="ui positive message" style="display:none; margin-bottom:.75rem;">
<p id="success-text"></p>
</div>
<div id="error-msg" class="ui negative message" style="display:none; margin-bottom:.75rem;">
<p id="error-text"></p>
</div>
<div class="rf-summary">
<div class="apply-no">{{ $main->orm_apply_no }}</div>
<div class="meta-line">Request by: <strong>{{ $main->orm_requested_by_name ?? '-' }}</strong></div>
<div class="meta-line">Position: <strong>{{ $main->orm_position_label ?? '-' }}</strong></div>
<div class="meta-line">Project: <strong>{{ $project->p_project_description ?? '-' }}</strong></div>
<div class="meta-line">Department: <strong>{{ $main->orm_department_label ?? '-' }}</strong></div>
<div class="meta-line">Request Date: <strong>{{ $main->orm_requested_date ? \Carbon\Carbon::parse($main->orm_requested_date)->format('d/m/Y') : '-' }}</strong></div>
<div class="meta-line">Approve by: <strong>{{ $main->orm_approved_by_name ?? '-' }}</strong></div>
<div class="meta-line">Approved Date: <strong>{{ $main->orm_approved_date ? \Carbon\Carbon::parse($main->orm_approved_date)->format('d/m/Y') : '-' }}</strong></div>
<div class="meta-line">Status: <span class="ui label" style="font-size:.78rem;">{{ $statuses[$main->orm_status]->description ?? '-' }}</span></div>
</div>
<div style="overflow-x:auto; margin-bottom:1.3rem;">
<table class="rf-tbl">
<thead>
<tr>
<th>No</th>
<th>Name</th>
<th>Overtime Month</th>
<th>Budgeted</th>
<th>Utilised to Date</th>
<th>Planned OT Hour</th>
<th>Balance</th>
<th>Reason</th>
</tr>
</thead>
<tbody>
@forelse($details as $i => $d)
<tr>
<td>{{ $i + 1 }}</td>
<td class="td-left">{{ $d->ord_name ?: '-' }}</td>
<td>{{ $d->ord_month_of_overtime ? \Carbon\Carbon::parse($d->ord_month_of_overtime)->format('M Y') : '-' }}</td>
<td>{{ number_format($d->ord_budgeted ?? 0, 2) }}</td>
<td>{{ number_format($d->ord_utilised_to_date ?? 0, 2) }}</td>
<td>{{ number_format($d->ord_planned_ot_hour ?? 0, 2) }}</td>
<td>{{ number_format($d->ord_balance ?? 0, 2) }}</td>
<td class="td-left">{{ $d->ord_reason ?: '-' }}</td>
</tr>
@empty
<tr><td colspan="9" style="color:#bbb; font-style:italic; padding:1.5rem;">No details.</td></tr>
@endforelse
</tbody>
<tfoot>
<tr>
<td colspan="4"></td>
<td class="lbl" style="text-align:center;">TOTAL PLANNED OT HOURS</td>
<td>{{ number_format($details->sum('ord_planned_ot_hour'), 2) }}</td>
<td colspan="2"></td>
</tr>
</tfoot>
</table>
</div>
@if($main->orm_status == 2)
<div class="action-card">
<div class="form-title">
<i class="gavel icon" style="color:#2185d0;"></i>
Review Action
</div>
<div style="margin-top:.8rem;">
<div class="ui form">
<div class="grouped fields">
<label style="font-weight:600;">Pilih Tindakan</label>
<div class="field">
<div class="ui radio checkbox">
<input type="radio" name="hod_action" value="support" id="hod_action_support" checked>
<label for="hod_action_support">Support</label>
</div>
</div>
<div class="field">
<div class="ui radio checkbox">
<input type="radio" name="hod_action" value="query" id="hod_action_query">
<label for="hod_action_query">Query Back</label>
</div>
</div>
</div>
</div>
<div id="hod-query-box" style="display:none;">
<div class="field">
<label style="font-weight:600; margin-bottom:.4rem; display:block;">Query Notes <span style="color:#e53935;">*</span></label>
<textarea id="kueri_remark" rows="3" placeholder="Provide query reasons..."
style="width:100%; min-height:80px; padding:.7rem 1rem; border:1px solid #d4d8dd; border-radius:6px; resize:vertical;"></textarea>
</div>
</div>
<div style="margin-top:.8rem; display:flex; justify-content:flex-end; gap:.55rem;">
<button type="button" class="ui teal button" id="btn-hod-action">
<i class="check icon"></i> Submit
</button>
</div>
</div>
</div>
@endif
<div class="action-card" style="border-left:1px solid #dde3ea;">
<div class="form-title"><i class="comment alternate outline icon"></i>Query History</div>
<div style="overflow-x:auto;">
<table class="query-history">
<thead>
<tr>
<th style="width:180px;">From</th>
<th>Query Notes</th>
<th>Response</th>
<th style="width:150px;">Date</th>
</tr>
</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>
</tr>
@empty
<tr><td colspan="4" style="color:#999;font-style:italic;text-align:center;padding:1rem;">No query history found.</td></tr>
@endforelse
</tbody>
</table>
</div>
</div>
{{-- FOOTER --}}
<div class="rf-footer">
<a href="{{ route('overtime::overtime.hodreviewlist') }}" class="ui grey button">
<i class="arrow left icon"></i> Back
</a>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$(document).ready(function () {
function csrfToken() { return $('meta[name="csrf-token"]').attr('content'); }
function showSuccess(msg) { $('#success-text').text(msg); $('#success-msg').show(); }
function showError(msg) { $('#error-text').text(msg); $('#error-msg').show(); }
$('.ui.radio.checkbox').checkbox();
$('input[name="hod_action"]').on('change', function () {
$('#hod-query-box').toggle($(this).val() === 'query');
});
$('#btn-hod-action').on('click', function () {
var action = $('input[name="hod_action"]:checked').val();
if (action === 'support') {
if (!confirm('Support this form and send it to the Project Director?')) return;
$.ajax({
url : "{{ route('overtime::overtime.hodapproverequest', $main->id) }}",
method: 'POST',
data : { _token: csrfToken() },
success: function (res) {
if (res.success) {
showSuccess(res.message);
setTimeout(function () { window.location.href = res.redirect; }, 1200);
} else {
showError(res.message || 'Error while approving. Please try again.');
}
},
error: function (xhr) {
showError((xhr.responseJSON && xhr.responseJSON.message) || 'Network error.');
},
});
return;
}
var remark = $('#kueri_remark').val().trim();
if (!remark) { showError('Please fill in the query note.'); return; }
if (!confirm('Send query back to the Project Manager?')) return;
$.ajax({
url : "{{ route('overtime::overtime.hodkuerirequest', $main->id) }}",
method: 'POST',
data : { _token: csrfToken(), remark: remark },
success: function (res) {
if (res.success) {
showSuccess(res.message);
setTimeout(function () { window.location.href = res.redirect; }, 1200);
} else {
showError(res.message || 'Error while sending query. Please try again.');
}
},
error: function (xhr) {
showError((xhr.responseJSON && xhr.responseJSON.message) || 'Network error.');
},
});
});
});
</script>
@endsection
@extends('ui::layouts.app')
@section('content')
<style>
.table-uppercase td { text-transform: uppercase; }
</style>
<div class="ui segment">
<a class="ui teal left ribbon label">Approval of Overtime Request Form (PD)</a>
<div class="ui segment">
<div class="ui stackable two column grid" style="margin-bottom:1rem;">
<div class="column">
<h1 class="ui header">
<div class="content">List of Forms Awaiting Approval</div>
</h1>
</div>
</div>
<div class="ui divider"></div>
<div class="column sixteen wide table-uppercase">
{!!
Suitable::source($list)
->title(__('List of Request Forms'))
->columns([
\Laravolt\Suitable\Columns\Numbering::make('No'),
['header' => __('Application Number'), 'field' => 'orm_apply_no', 'sortable' => true],
['header' => __('Project'), 'raw' => function ($row) {
return \DB::table('lkp_project')->where('id', $row->orm_project)->value('p_project_description') ?? '-';
}],
['header' => __('Date'), 'raw' => function ($row) {
return $row->orm_date ? \Carbon\Carbon::parse($row->orm_date)->format('d/m/Y') : '-';
}],
['header' => __('Status'), 'raw' => function ($row) use ($statuses) {
$label = $statuses[$row->orm_status]->description ?? '-';
return "<span class='ui label'>{$label}</span>";
}],
['header' => __('Action'), 'raw' => function ($row) {
return "<a href='" . route('overtime::overtime.pdviewrequest', $row->id) . "'
class='ui blue button tiny'>
<i class='eye icon'></i> View
</a>";
}],
])
->render()
!!}
</div>
</div>
</div>
@endsection
@extends('ui::layouts.app')
@section('content')
<style>
.rf-summary {
background: #ddeeff; border-radius: 6px;
padding: .9rem 1.2rem; margin-bottom: 1.2rem; line-height: 1.7;
}
.rf-summary .apply-no { font-size: 1.05rem; font-weight: 700; color: #1a56a0; }
.rf-summary .meta-line { font-size: .92rem; color: #333; }
.rf-tbl { width: 100%; border-collapse: collapse; font-size: .85rem; }
.rf-tbl th, .rf-tbl td {
border: 1px solid #cfd8e3; padding: 6px 10px;
text-align: center; vertical-align: middle;
}
.rf-tbl thead th { background: #2185d0; color: #fff; font-size: .82rem; }
.rf-tbl tbody td.td-left { text-align: left; }
.rf-tbl tfoot td {
background: #ddeeff; font-weight: 700; color: #1a56a0;
border-top: 2px solid #2185d0;
}
.rf-tbl tfoot .lbl { text-align: right; font-size: .82rem; letter-spacing: .04em; }
.action-card {
background: #fff; border: 1px solid #dde3ea;
border-left: 4px solid #2185d0; border-radius: 8px;
padding: 1.3rem 1.5rem; margin-bottom: 1.3rem;
}
.action-card .form-title {
font-size: 1rem; font-weight: 700; color: #222;
display: flex; align-items: center; gap: .45rem; margin-bottom: 1.1rem;
}
.rf-footer {
display: flex; justify-content: flex-end; gap: .55rem;
padding-top: .9rem; border-top: 1px solid #e5e8ee;
}
.query-history{width:100%;border-collapse:collapse;font-size:.85rem}
.query-history th,.query-history td{border:1px solid #cfd8e3;padding:8px 10px;vertical-align:top}
.query-history th{background:#f5f7fa;text-align:left}
</style>
<div class="ui segment" style="padding-bottom: 2rem;">
<div id="success-msg" class="ui positive message" style="display:none; margin-bottom:.75rem;">
<p id="success-text"></p>
</div>
<div id="error-msg" class="ui negative message" style="display:none; margin-bottom:.75rem;">
<p id="error-text"></p>
</div>
<div class="rf-summary">
<div class="apply-no">{{ $main->orm_apply_no }}</div>
<div class="meta-line">Request by: <strong>{{ $main->orm_requested_by_name ?? '-' }}</strong></div>
<div class="meta-line">Position: <strong>{{ $main->orm_position_label ?? '-' }}</strong></div>
<div class="meta-line">Project: <strong>{{ $project->p_project_description ?? '-' }}</strong></div>
<div class="meta-line">Department: <strong>{{ $main->orm_department_label ?? '-' }}</strong></div>
<div class="meta-line">Request Date: <strong>{{ $main->orm_requested_date ? \Carbon\Carbon::parse($main->orm_requested_date)->format('d/m/Y') : '-' }}</strong></div>
<div class="meta-line">Approve by: <strong>{{ $main->orm_approved_by_name ?? '-' }}</strong></div>
<div class="meta-line">Approved Date: <strong>{{ $main->orm_approved_date ? \Carbon\Carbon::parse($main->orm_approved_date)->format('d/m/Y') : '-' }}</strong></div>
<div class="meta-line">Status: <span class="ui label" style="font-size:.78rem;">{{ $statuses[$main->orm_status]->description ?? '-' }}</span></div>
</div>
<div style="overflow-x:auto; margin-bottom:1.3rem;">
<table class="rf-tbl">
<thead>
<tr>
<th>No</th>
<th>Name</th>
<th>Overtime Month</th>
<th>Budgeted</th>
<th>Utilised to Date</th>
<th>Planned OT Hour</th>
<th>Balance</th>
<th>Reason</th>
</tr>
</thead>
<tbody>
@forelse($details as $i => $d)
<tr>
<td>{{ $i + 1 }}</td>
<td class="td-left">{{ $d->ord_name ?: '-' }}</td>
<td>{{ $d->ord_month_of_overtime ? \Carbon\Carbon::parse($d->ord_month_of_overtime)->format('M Y') : '-' }}</td>
<td>{{ number_format($d->ord_budgeted ?? 0, 2) }}</td>
<td>{{ number_format($d->ord_utilised_to_date ?? 0, 2) }}</td>
<td>{{ number_format($d->ord_planned_ot_hour ?? 0, 2) }}</td>
<td>{{ number_format($d->ord_balance ?? 0, 2) }}</td>
<td class="td-left">{{ $d->ord_reason ?: '-' }}</td>
</tr>
@empty
<tr><td colspan="8" style="color:#bbb; font-style:italic; padding:1.5rem;">No details.</td></tr>
@endforelse
</tbody>
<tfoot>
<tr>
<td colspan="4"></td>
<td class="lbl" style="text-align:center;">TOTAL PLANNED OT HOURS</td>
<td>{{ number_format($details->sum('ord_planned_ot_hour'), 2) }}</td>
<td colspan="2"></td>
</tr>
</tfoot>
</table>
</div>
@if($main->orm_status == 7)
<div class="action-card">
<div class="form-title">
<i class="gavel icon" style="color:#2185d0;"></i>
Review Action
</div>
<div style="margin-top:.8rem;">
<div class="ui form">
<div class="grouped fields">
<label style="font-weight:600;">Pilih Tindakan</label>
<div class="field">
<div class="ui radio checkbox">
<input type="radio" name="pd_action" value="support" id="pd_action_support" checked>
<label for="pd_action_support">Support</label>
</div>
</div>
<div class="field">
<div class="ui radio checkbox">
<input type="radio" name="pd_action" value="query" id="pd_action_query">
<label for="pd_action_query">Query Back</label>
</div>
</div>
</div>
</div>
<div id="pd-query-box" style="display:none;">
<div class="field">
<label style="font-weight:600; margin-bottom:.4rem; display:block;">Query Notes <span style="color:#e53935;">*</span></label>
<textarea id="kueri_remark" rows="3" placeholder="Provide query reasons..."
style="width:100%; min-height:80px; padding:.7rem 1rem; border:1px solid #d4d8dd; border-radius:6px; resize:vertical;"></textarea>
</div>
</div>
<div style="margin-top:.8rem; display:flex; justify-content:flex-end; gap:.55rem;">
<button type="button" class="ui teal button" id="btn-pd-action">
<i class="check icon"></i> Submit
</button>
</div>
</div>
</div>
@endif
<div class="action-card" style="border-left:1px solid #dde3ea;">
<div class="form-title"><i class="comment alternate outline icon"></i>Query History</div>
<div style="overflow-x:auto;">
<table class="query-history">
<thead>
<tr>
<th style="width:180px;">From</th>
<th>Query Notes</th>
<th>Response</th>
<th style="width:150px;">Date</th>
</tr>
</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>
</tr>
@empty
<tr><td colspan="4" style="color:#999;font-style:italic;text-align:center;padding:1rem;">No query history found.</td></tr>
@endforelse
</tbody>
</table>
</div>
</div>
<div class="rf-footer">
<a href="{{ route('overtime::overtime.pdreviewlist') }}" class="ui grey button">
<i class="arrow left icon"></i> Back
</a>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$(document).ready(function () {
function csrfToken() { return $('meta[name="csrf-token"]').attr('content'); }
function showSuccess(msg) { $('#success-text').text(msg); $('#success-msg').show(); }
function showError(msg) { $('#error-text').text(msg); $('#error-msg').show(); }
$('.ui.radio.checkbox').checkbox();
$('input[name="pd_action"]').on('change', function () {
$('#pd-query-box').toggle($(this).val() === 'query');
});
$('#btn-pd-action').on('click', function () {
var action = $('input[name="pd_action"]:checked').val();
if (action === 'support') {
if (!confirm('Confirm the approval of this request form?')) return;
$.ajax({
url : "{{ route('overtime::overtime.pdapproverequest', $main->id) }}",
method: 'POST',
data : { _token: csrfToken() },
success: function (res) {
if (res.success) {
showSuccess(res.message);
setTimeout(function () { window.location.href = res.redirect; }, 1200);
} else {
showError(res.message || 'Error while approving. Please try again.');
}
},
error: function (xhr) {
showError((xhr.responseJSON && xhr.responseJSON.message) || 'Network error.');
},
});
return;
}
var remark = $('#kueri_remark').val().trim();
if (!remark) { showError('Sila isi catatan kueri.'); return; }
if (!confirm('Confirm the submission of this query back to the Project Manager?')) return;
$.ajax({
url : "{{ route('overtime::overtime.pdkuerirequest', $main->id) }}",
method: 'POST',
data : { _token: csrfToken(), remark: remark },
success: function (res) {
if (res.success) {
showSuccess(res.message);
setTimeout(function () { window.location.href = res.redirect; }, 1200);
} else {
showError(res.message || 'Error while submitting the query back. Please try again');
}
},
error: function (xhr) {
showError((xhr.responseJSON && xhr.responseJSON.message) || 'Network error.');
},
});
});
});
</script>
@endsection
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<div class="ui small modal" id="modalRequestBaharu">
<div class="header">
<i class="file alternate outline icon"></i>
Create New Request Form
</div>
<div class="content">
<div id="rmodal-success-msg" class="ui positive message" style="display:none;">
<p id="rmodal-success-text"></p>
</div>
<div id="rmodal-error-msg" class="ui negative message" style="display:none;">
<p id="rmodal-error-text"></p>
</div>
<form class="ui form" id="form-request-baharu">
@csrf
<p style="color:#888; margin-bottom:1.2rem;">
<i class="info circle icon"></i>
Select project for the new request form.
</p>
<div class="required field" id="field-orm_project">
<label>Project</label>
<select name="orm_project" id="orm_project"
style="width:100%; padding:8px; border:1px solid rgba(34,36,38,.15); border-radius:4px;">
<option value="">-- Select Project --</option>
</select>
</div>
<div class="required field" id="field-orm_date">
<label>OT Request Month</label>
<div class="two fields" style="margin-bottom:0;">
<div class="field">
<select name="orm_month" id="orm_month" class="ui dropdown">
<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>
@endforeach
</select>
</div>
<div class="field">
<select name="orm_year" id="orm_year" class="ui dropdown">
<option value="">Year</option>
@for($year = now()->year - 1; $year <= now()->year + 2; $year++)
<option value="{{ $year }}">{{ $year }}</option>
@endfor
</select>
</div>
</div>
</div>
</form>
</div>
<div class="actions">
<button type="button" class="ui teal button" id="btn-modal-request-submit">
Create Form
</button>
<button type="button" class="ui deny button">
<i class="times icon"></i> Cancel
</button>
</div>
</div>
<script>
$(document).ready(function () {
var EXISTING_PROJECTS_URL = "{{ route('overtime::overtime.existingprojects') }}";
var ALL_PROJECTS = @json($projects->map(fn($p) => ['id' => $p->id, 'name' => $p->p_project_description]));
function escapeHtml(value) {
return $('<div>').text(value || '').html();
}
function renderProjectOptions(occupied) {
occupied = occupied || [];
var current = $('#orm_project').val();
var html = '<option value="">-- Select Project --</option>';
ALL_PROJECTS.forEach(function (p) {
var isTaken = occupied.indexOf(String(p.id)) !== -1;
var label = p.name + (isTaken ? ' (Sudah ada borang untuk bulan ini)' : '');
var attrs = isTaken ? ' disabled style="color:#bbb;"' : '';
var selected = (!isTaken && current == p.id) ? ' selected' : '';
html += '<option value="' + escapeHtml(p.id) + '"' + attrs + selected + '>'
+ escapeHtml(label)
+ '</option>';
});
$('#orm_project').html(html);
}
function refreshProjectOptions() {
var month = $('#orm_month').val();
var year = $('#orm_year').val();
if (!month || !year) {
renderProjectOptions([]);
return;
}
var requestKeySuffix = year + month;
$.ajax({
url : EXISTING_PROJECTS_URL,
method : 'GET',
success: function (res) {
var occupiedKeys = res.success ? (res.existingRequests || []) : [];
var occupied = occupiedKeys
.filter(function (item) { return item.endsWith('|' + requestKeySuffix); })
.map(function (item) { return item.split('|')[0]; });
renderProjectOptions(occupied);
},
});
}
function resetRequestModal() {
$('#rmodal-success-msg, #rmodal-error-msg').hide();
$('#field-orm_project, #field-orm_date').removeClass('error');
$('#orm_month, #orm_year').val('');
if ($.fn.dropdown) $('#orm_month, #orm_year').dropdown('clear');
refreshProjectOptions();
}
renderProjectOptions(@json($existingRequests ?? []));
$('#modalRequestBaharu').modal({
blurring: true,
closable: true,
onShow: resetRequestModal,
});
$('#orm_month, #orm_year').on('change', refreshProjectOptions);
$('#btn-modal-request-submit').on('click', function () {
var btn = $(this);
var project = $('#orm_project').val();
var token = $('input[name="_token"]').first().val()
|| $('meta[name="csrf-token"]').attr('content');
$('#rmodal-success-msg, #rmodal-error-msg').hide();
$('#field-orm_project').removeClass('error');
var month = $('#orm_month').val();
var year = $('#orm_year').val();
if (!project) {
$('#field-orm_project').addClass('error');
$('#rmodal-error-text').text('Sila pilih projek.');
$('#rmodal-error-msg').show();
return;
}
if (!month || !year) {
$('#field-orm_date').addClass('error');
$('#rmodal-error-text').text('Sila pilih bulan permohonan OT.');
$('#rmodal-error-msg').show();
return;
}
btn.addClass('loading disabled');
$.ajax({
url : "{{ route('overtime::overtime.storeovertimerequest') }}",
method : 'POST',
dataType: 'json',
headers : { 'X-CSRF-TOKEN': token },
data : {
_token: token,
orm_project: project,
orm_date: year + '-' + month + '-01',
},
success : function (res) {
btn.removeClass('loading disabled');
if (res.success) {
$('#rmodal-success-text').text(res.message);
$('#rmodal-success-msg').show();
setTimeout(function () { window.location.href = res.redirect; }, 800);
} else {
$('#rmodal-error-text').text(res.message || 'Ralat tidak diketahui.');
$('#rmodal-error-msg').show();
}
},
error: function (xhr) {
btn.removeClass('loading disabled');
var msg = 'Ralat rangkaian. Sila cuba lagi.';
if (xhr.status === 422 && xhr.responseJSON && xhr.responseJSON.errors) {
msg = Object.values(xhr.responseJSON.errors).flat().join(' ');
} else if (xhr.responseJSON && xhr.responseJSON.message) {
msg = xhr.responseJSON.message;
}
$('#rmodal-error-text').text(msg);
$('#rmodal-error-msg').show();
},
});
});
});
</script>
@extends('ui::layouts.app')
@section('content')
<style>
.rf-summary,.rf-card,.rf-form-card,.rf-history-card,.rf-query-card{background:#fff;border:1px solid #dde3ea;border-radius:8px}
.rf-summary{background:#ddeeff;padding:.9rem 1.2rem;margin-bottom:1.2rem;line-height:1.7}
.rf-summary .apply-no{font-size:1.05rem;font-weight:700;color:#1a56a0}
.rf-summary .meta-line{font-size:.92rem;color:#333}
.rf-card,.rf-form-card,.rf-history-card,.rf-query-card{padding:1.2rem 1.4rem;margin-bottom:1.3rem}
.rf-card .card-title,.rf-form-card .form-title,.rf-history-card .card-title,.rf-query-card .card-title{font-size:1rem;font-weight:700;color:#222;display:flex;align-items:center;gap:.45rem;margin-bottom:.9rem}
.rf-tbl{width:100%;border-collapse:collapse;font-size:.85rem}
.rf-tbl th,.rf-tbl td{border:1px solid #cfd8e3;padding:6px 10px;text-align:center;vertical-align:middle}
.rf-tbl thead th{background:#2185d0;color:#fff;font-size:.82rem}
.rf-tbl tbody td.td-left{text-align:left}
.rf-tbl tfoot td{background:#ddeeff;font-weight:700;color:#1a56a0;border-top:2px solid #2185d0}
.rf-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:hover{background:#e53935;color:#fff}
.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}
.rf-footer,.button-row{display:flex;justify-content:flex-end;gap:.55rem;padding-top:.9rem;border-top:1px solid #e5e8ee}
.query-radio{display:flex;justify-content:flex-start;gap:1rem;flex-wrap:wrap}
.query-history{width:100%;border-collapse:collapse;font-size:.85rem}
.query-history th,.query-history td{border:1px solid #cfd8e3;padding:8px 10px;vertical-align:top}
.query-history th{background:#f5f7fa;text-align:left}
</style>
<div class="ui segment" style="padding-bottom:2rem;">
<div id="success-msg" class="ui positive message" style="display:none;margin-bottom:.75rem;"><p id="success-text"></p></div>
<div id="error-msg" class="ui negative message" style="display:none;margin-bottom:.75rem;"><p id="error-text"></p></div>
@php
$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');
@endphp
<div class="rf-summary">
<div class="apply-no">{{ $data->orm_apply_no }}</div>
<div class="meta-line">Request by: <strong>{{ $data->orm_requested_by_name ?? '-' }}</strong></div>
<div class="meta-line">Position: <strong>{{ $data->orm_position_label ?? '-' }}</strong></div>
<div class="meta-line">Project: <strong>{{ $project->p_project_description ?? '-' }}</strong></div>
<div class="meta-line">Department: <strong>{{ $data->orm_department_label ?? '-' }}</strong></div>
<div class="meta-line">Request Date: <strong>{{ $data->orm_requested_date ? \Carbon\Carbon::parse($data->orm_requested_date)->format('d/m/Y') : '-' }}</strong></div>
<div class="meta-line">Approve by: <strong>{{ $data->orm_approved_by_name ?? '-' }}</strong></div>
<div class="meta-line">Approved Date: <strong>{{ $data->orm_approved_date ? \Carbon\Carbon::parse($data->orm_approved_date)->format('d/m/Y') : '-' }}</strong></div>
<div class="meta-line">Status: <strong>{{ $statusLabel }}</strong></div>
</div>
<div class="rf-card">
<div class="card-title"><i class="table icon" style="color:#2185d0;"></i>Request Details</div>
<div style="overflow-x:auto;">
<table class="rf-tbl" id="rf-table">
<thead>
<tr>
<th>No</th>
<th>Name</th>
<th>Month of Overtime</th>
<th>Budgeted</th>
<th>Utilised to Date</th>
<th>Planned OT Hours</th>
<th>Balance</th>
<th>Reason</th>
</tr>
</thead>
<tbody id="rf-tbody">
<tr class="empty-row"><td colspan="9">Loading entries...</td></tr>
</tbody>
<tfoot>
<tr>
<td colspan="4"></td>
<td class="lbl" style="text-align:center;">TOTAL PLANNED OT HOURS</td>
<td id="grand-total">{{ number_format($totalHours, 2) }}</td>
<td colspan="3"></td>
</tr>
</tfoot>
</table>
</div>
</div>
<div class="rf-form-card">
<div class="form-title"><i class="plus circle icon" style="color:#2185d0;font-size:1.1em;"></i>Add Entry</div>
<div class="ui form" id="form-add-detail">@csrf
<div class="two fields">
<div class="required field">
<label>Name <span style="color:#e53935;"></span></label>
<select class="ui search dropdown" id="ord_name">
<option value="">Select project staff</option>
@foreach($staffOptions as $staff)
@php $staffName = $staff->fullname ?: ($staff->pt_team ?: $staff->user_name); @endphp
@if($staffName)<option value="{{ $staffName }}">{{ $staffName }}</option>@endif
@endforeach
</select>
</div>
<div class="required field">
<label>OT Month <span style="color:#e53935;"></span></label>
<div class="two fields" style="margin-bottom:0;">
<div class="field">
<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>
@endforeach
</select>
</div>
<div class="field">
<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>
@endfor
</select>
</div>
</div>
</div>
</div>
<div class="four fields">
<div class="field"><label>Budgeted</label><input type="number" id="ord_budgeted" step="0.01" min="0" placeholder="0.00"></div>
<div class="field"><label>Utilised to Date</label><input type="number" id="ord_utilised_to_date" step="0.01" min="0" placeholder="0.00"></div>
<div class="field"><label>Planned OT Hours <span style="color:#e53935;">*</span></label><input type="number" id="ord_planned_ot_hour" step="0.5" min="0" placeholder="0.00"></div>
<div class="field"><label>Balance <span class="badge-auto">auto</span></label><input type="number" id="ord_balance" class="auto-field" readonly placeholder="0.00"></div>
</div>
<div class="field">
<label>Reason <span style="color:#e53935;">*</span></label>
<textarea id="ord_reason" rows="3" placeholder="OT reason..."></textarea>
</div>
<div class="button-row">
<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 grey button" id="btn-reset"><i class="redo icon"></i>Clear</button>
</div>
</div>
</div>
@if(in_array($data->orm_status, [8, 10]))
<div class="rf-query-card">
<div class="card-title"><i class="comment alternate outline icon"></i>Query Response</div>
<div style="overflow-x:auto;margin-bottom:1rem;">
<table class="query-history">
<thead>
<tr>
<th style="width:180px;">From</th>
<th>Query Notes</th>
<th>Response</th>
<th style="width:150px;">Date</th>
</tr>
</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>
</tr>
@empty
<tr><td colspan="4" style="color:#999;font-style:italic;text-align:center;padding:1rem;">No query history found.</td></tr>
@endforelse
</tbody>
</table>
</div>
<div class="field">
<label style="font-weight:600;display:block;margin-bottom:.4rem;">Response <span style="color:#e53935;">*</span></label>
<textarea id="kueri_respond" rows="4" placeholder="Write your response here..." style="width:100%;min-height:100px;padding:.75rem 1rem;font-size:.92rem;border:1px solid #d4d8dd;border-radius:6px;resize:vertical;font-family:inherit;line-height:1.5;">{{ $data->orm_query_respond }}</textarea>
</div>
</div>
@endif
<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>
@endif
</div>
</div>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
var mainId = {{ $data->id }};
var rows = {};
$(document).ready(function () {
if ($.fn.dropdown) $('.ui.dropdown').dropdown({ fullTextSearch: true });
loadRows();
bindEvents();
});
function bindEvents() {
$('#ord_budgeted, #ord_utilised_to_date').on('input', function () {
var b = parseFloat($('#ord_budgeted').val()) || 0;
var u = parseFloat($('#ord_utilised_to_date').val()) || 0;
$('#ord_balance').val((b - u).toFixed(2));
});
$('#btn-add-row').on('click', addRow);
$('#btn-reset').on('click', resetForm);
}
function csrfToken() { return $('meta[name="csrf-token"]').attr('content'); }
function esc(s) { return s === null || s === undefined ? '' : String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;'); }
function showSuccess(msg) { $('#success-text').text(msg); $('#success-msg').show(); setTimeout(function(){ $('#success-msg').hide(); }, 3500); }
function showError(msg) { $('#error-text').text(msg); $('#error-msg').show(); setTimeout(function(){ $('#error-msg').hide(); }, 6000); }
function fmtMonth(val) { if (!val) return '-'; var d = new Date(val); var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']; return months[d.getMonth()] + ' ' + d.getFullYear(); }
function loadRows() {
$.ajax({
url: "{{ route('overtime::overtime.viewovertimerequest', $data->id) }}",
method: 'GET',
success: function (res) {
if (res.success && res.data.details) {
res.data.details.forEach(function (d) { rows[d.id] = d; });
}
renderTable();
},
error: function () { showError('Failed to load existing entries.'); renderTable(); },
});
}
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>');
$('#grand-total').text('0.00');
return;
}
var total = 0, html = '';
keys.forEach(function (id, i) {
var d = rows[id];
var hours = parseFloat(d.ord_planned_ot_hour) || 0;
total += hours;
html += '<tr data-id="' + id + '">';
html += '<td>' + (i + 1) + '</td>';
html += '<td class="td-left">' + esc(d.ord_name) + '</td>';
html += '<td>' + fmtMonth(d.ord_month_of_overtime) + '</td>';
html += '<td>' + parseFloat(d.ord_budgeted || 0).toFixed(2) + '</td>';
html += '<td>' + parseFloat(d.ord_utilised_to_date || 0).toFixed(2) + '</td>';
html += '<td>' + parseFloat(d.ord_planned_ot_hour || 0).toFixed(2) + '</td>';
html += '<td>' + parseFloat(d.ord_balance || 0).toFixed(2) + '</td>';
html += '<td class="td-left">' + esc(d.ord_reason) + '</td>';
html += '<td><button class="btn-del" onclick="removeRow(' + id + ')"><i class="trash icon"></i></button></td>';
html += '</tr>';
});
tbody.html(html);
$('#grand-total').text(total.toFixed(2));
}
function addRow() {
var name = ($('#ord_name').val() || '').trim();
var monthNo = $('#ord_month').val();
var year = $('#ord_year').val();
var month = year && monthNo ? year + '-' + monthNo : '';
var budgeted = $('#ord_budgeted').val();
var utilised = $('#ord_utilised_to_date').val();
var planned = $('#ord_planned_ot_hour').val();
var balance = $('#ord_balance').val();
var reason = $('#ord_reason').val().trim();
if (!name) { showError('Please enter a name.'); return; }
if (!month) { showError('Please select OT month.'); return; }
if (!planned) { showError('Please enter planned OT hours.'); return; }
if (!reason) { showError('Please enter a reason.'); return; }
$.ajax({
url: "{{ route('overtime::overtime.addovertimerequestdetail', $data->id) }}",
method: 'POST',
data: {
_token: csrfToken(),
ord_name: name,
ord_month_of_overtime: month + '-01',
ord_budgeted: budgeted || 0,
ord_utilised_to_date: utilised || 0,
ord_planned_ot_hour: planned,
ord_reason: reason,
ord_total_hours: planned,
},
success: function (res) {
if (!res.success) { showError(res.message || 'Error while adding.'); return; }
rows[res.detail.id] = res.detail;
renderTable();
resetForm();
showSuccess(res.message || 'Entry added.');
},
error: function (xhr) {
var msg = 'Error while adding 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 removeRow(id) {
if (!confirm('Remove this entry from the table?')) return;
$.ajax({
url: "{{ route('overtime::overtime.removeovertimerequestdetail', ':id') }}".replace(':id', id),
method: 'POST',
data: { _token: csrfToken() },
success: function (res) {
if (!res.success) { showError(res.message || 'Error while removing.'); return; }
delete rows[id];
renderTable();
showSuccess(res.message || 'Entry removed.');
},
error: function () { showError('Network error. Please try again.'); },
});
}
function resetForm() {
$('#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 submitRequestForm() {
var respondVal = $('#kueri_respond').val();
function doSubmit() {
if (!confirm('Submit this request for HOD review?')) return;
$.ajax({
url: "{{ route('overtime::overtime.submitovertimerequest', $data->id) }}",
method: 'POST',
data: { _token: csrfToken() },
success: function (res) {
if (res.success) { showSuccess(res.message); setTimeout(function () { window.location.href = res.redirect; }, 1200); }
else { showError(res.message || 'Error while submitting.'); }
},
error: function () { showError('Error while submitting the request.'); },
});
}
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 () { doSubmit(); },
error: function () { showError('Error while saving response.'); },
});
} else if ($('#kueri_respond').length) {
showError('Please enter a response before resubmitting.');
} else {
doSubmit();
}
}
</script>
@endsection
@extends('ui::layouts.app')
@section('content')
@include('overtime::overtime.overtimerequest.pm.create')
@include('overtime::overtime.overtimerequest.pm.view_modal')
<style>
.table-uppercase td { text-transform: uppercase; }
</style>
<div class="ui segment">
<a class="ui teal left ribbon label">List of Overtime Request Forms</a>
<div class="ui segment">
<div class="ui stackable two column grid" style="margin-bottom:1rem;">
<div class="column">
<h1 class="ui header">
<div class="content">List of Overtime Request Forms</div>
</h1>
</div>
<div class="column" style="text-align:right; padding-top:1.2rem;">
<button class="ui teal button" id="btn-request-baharu">
<i class="plus icon"></i> New Request
</button>
</div>
</div>
<div class="ui divider"></div>
<div class="column sixteen wide table-uppercase">
{!!
Suitable::source($list)
->title(__('List of Overtime Request Forms'))
->columns([
\Laravolt\Suitable\Columns\Numbering::make('No'),
['header' => __('Application Number'), 'field' => 'orm_apply_no', 'sortable' => true],
['header' => __('Project'), 'raw' => function ($row) {
return \DB::table('lkp_project')->where('id', $row->orm_project)->value('p_project_description') ?? '-';
}],
['header' => __('OT Month'), 'raw' => function ($row) {
return $row->orm_date ? \Carbon\Carbon::parse($row->orm_date)->format('M Y') : '-';
}],
['header' => __('Status'), 'raw' => function ($row) use ($statuses) {
$label = $statuses[$row->orm_status]->description ?? '-';
return "<span class='ui label'>{$label}</span>";
}],
['header' => __('Action'), 'raw' => function ($row) {
$view = "<button
class='ui blue button tiny'
onclick='viewRequestForm({$row->id})'>
<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]);
$edit = $canEdit
? "<a href='" . route('overtime::overtime.editovertimerequest', $row->id) . "'
class='ui yellow button tiny'>
<i class='edit icon'></i> Update
</a>"
: "";
$batal = $canBatal
? "<button
class='ui red button tiny btn-batal-request'
data-id='{$row->id}'
data-url='" . route('overtime::overtime.batalovertimerequest', $row->id) . "'>
<i class='ban icon'></i> Cancel
</button>"
: "";
return "<div style='display:flex;justify-content:center;gap:.35rem;flex-wrap:wrap;'>{$view} {$edit} {$batal}</div>";
}],
])
->render()
!!}
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$(document).ready(function () {
$('#btn-request-baharu').on('click', function () {
$('#modalRequestBaharu').modal('show');
});
$(document).on('click', '.btn-batal-request', function () {
if (!confirm('Cancel this application form? This action cannot be undone.')) return;
var url = $(this).data('url');
$.ajax({
url : url,
method : 'POST',
data : { _token: $('meta[name="csrf-token"]').attr('content') },
success: function (res) {
if (res.success) {
location.reload();
} else {
alert(res.message || 'Error while canceling the application form. Please try again.');
}
},
error: function () {
alert('Network error. Please try again.');
},
});
});
});
</script>
@endsection
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<style>
#modalViewRequestForm .scrolling.content { max-height: 80vh; overflow-y: auto; }
#modalViewRequestForm .vm-summary {
background: #ddeeff; border-radius: 6px;
padding: .8rem 1.1rem; margin-bottom: 1rem; line-height: 1.75;
}
#modalViewRequestForm .vm-summary .apply-no { font-size: 1.05rem; font-weight: 700; color: #1a56a0; }
#modalViewRequestForm .vm-summary .meta-line { font-size: .88rem; color: #333; }
#modalViewRequestForm .vm-tbl { width: 100%; border-collapse: collapse; font-size: .83rem; }
#modalViewRequestForm .vm-tbl th,
#modalViewRequestForm .vm-tbl td {
border: 1px solid #cfd8e3; padding: 6px 9px;
vertical-align: middle; text-align: center;
}
#modalViewRequestForm .vm-tbl thead th { background: #2185d0; color: #fff; font-weight: 600; font-size: .82rem; }
#modalViewRequestForm .vm-tbl tbody td.vm-left { text-align: left; }
#modalViewRequestForm .vm-tbl tfoot td {
background: #ddeeff; font-weight: 700; color: #1a56a0;
border-top: 2px solid #2185d0;
}
#modalViewRequestForm .vm-tbl tfoot .lbl { text-align: right; font-size: .8rem; letter-spacing: .04em; }
#modalViewRequestForm .vm-empty { text-align: center; color: #bbb; font-style: italic; padding: 1.6rem; }
#modalViewRequestForm .vm-loading { text-align: center; padding: 2.5rem; color: #888; }
</style>
<div class="ui fullscreen modal" id="modalViewRequestForm">
<div class="header">
<i class="eye icon"></i>
View Overtime Request Form
</div>
<div class="scrolling content" id="vrf-content">
<div class="vm-loading">
<i class="spinner loading icon"></i> Loading data…
</div>
</div>
<div class="actions">
<button class="ui grey button" onclick="$('#modalViewRequestForm').modal('hide');">
<i class="times icon"></i> Close
</button>
</div>
</div>
<script>
var VRF_MONTHS = ['Jan','Feb','Mac','Apr','Mei','Jun','Jul','Ogos','Sep','Okt','Nov','Dis'];
function vrfEsc(s) {
if (s === null || s === undefined) return '';
return String(s)
.replace(/&/g,'&amp;').replace(/</g,'&lt;')
.replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}
function vrfFmtDate(str) {
if (!str) return '-';
var d = new Date(str);
if (isNaN(d.getTime())) return '-';
return d.toLocaleDateString('en-GB');
}
function vrfFmtMonth(str) {
if (!str) return '-';
var d = new Date(str);
return VRF_MONTHS[d.getMonth()] + ' ' + d.getFullYear();
}
function viewRequestForm(id) {
$('#vrf-content').html(
'<div class="vm-loading"><i class="spinner loading icon"></i> Loading data…</div>'
);
$('#modalViewRequestForm').modal({ blurring: true, closable: true }).modal('show');
$.ajax({
url : "{{ route('overtime::overtime.viewovertimerequest', ':id') }}".replace(':id', id),
method : 'GET',
success: function (res) {
if (res.success) {
$('#vrf-content').html(vrfBuildHtml(res.data.main, res.data.details));
} else {
$('#vrf-content').html(
'<div class="ui negative message"><p>'
+ vrfEsc(res.message || 'Error while loading data. Please try again.')
+ '</p></div>'
);
}
},
error: function () {
$('#vrf-content').html(
'<div class="ui negative message"><p>Network error. Please try again.</p></div>'
);
},
});
}
function vrfBuildHtml(main, details) {
var badge = '<span class="ui label" style="font-size:.78rem;">' + vrfEsc(main.orm_status_label || '-') + '</span>';
var html = '<div class="vm-summary">'
+ '<div class="apply-no">' + vrfEsc(main.orm_apply_no || '-') + '</div>'
+ '<div class="meta-line">Request by: <strong>' + vrfEsc(main.orm_requested_by_name || '-') + '</strong></div>'
+ '<div class="meta-line">Position: <strong>' + vrfEsc(main.orm_position_label || '-') + '</strong></div>'
+ '<div class="meta-line">Project: <strong>' + vrfEsc(main.orm_project_label || '-') + '</strong></div>'
+ '<div class="meta-line">Department: <strong>' + vrfEsc(main.orm_department_label || '-') + '</strong></div>'
+ '<div class="meta-line">Request Date: <strong>' + vrfFmtDate(main.orm_requested_date || main.orm_date) + '</strong></div>'
+ '<div class="meta-line">Approve by: <strong>' + vrfEsc(main.orm_approved_by_name || '-') + '</strong></div>'
+ '<div class="meta-line">Approved Date: <strong>' + vrfFmtDate(main.orm_approved_date) + '</strong></div>'
+ '<div class="meta-line">Status: ' + badge + '</div>'
+ '</div>';
html += '<div style="overflow-x:auto;">'
+ '<table class="vm-tbl"><thead><tr>'
+ '<th>No</th><th>Name</th><th>Month of Overtime</th><th>Budgeted</th>'
+ '<th>Utilised to Date</th><th>Planned OT Hour</th><th>Balance</th>'
+ '<th>Reason</th>'
+ '</tr></thead><tbody>';
if (!details || details.length === 0) {
html += '<tr><td colspan="8" class="vm-empty">No additional details.</td></tr></tbody></table></div>';
return html;
}
var grandTotal = 0;
details.forEach(function (d, i) {
var hours = parseFloat(d.ord_planned_ot_hour) || 0;
grandTotal += hours;
html += '<tr>'
+ '<td>' + (i + 1) + '</td>'
+ '<td class="vm-left">' + vrfEsc(d.ord_name || '-') + '</td>'
+ '<td>' + vrfFmtMonth(d.ord_month_of_overtime) + '</td>'
+ '<td>' + parseFloat(d.ord_budgeted || 0).toFixed(2) + '</td>'
+ '<td>' + parseFloat(d.ord_utilised_to_date || 0).toFixed(2) + '</td>'
+ '<td>' + parseFloat(d.ord_planned_ot_hour || 0).toFixed(2) + '</td>'
+ '<td>' + parseFloat(d.ord_balance || 0).toFixed(2) + '</td>'
+ '<td class="vm-left">' + vrfEsc(d.ord_reason || '-') + '</td>'
+ '</tr>';
});
html += '</tbody><tfoot><tr>'
+ '<td colspan="4"></td>'
+ '<td class="lbl" style="text-align:center;">TOTAL PLANNED OT HOURS</td>'
+ '<td>' + grandTotal.toFixed(2) + '</td>'
+ '<td colspan="2"></td>'
+ '</tr></tfoot></table></div>';
return html;
}
</script>
<?php
use Illuminate\Support\Facades\Route;
use Portal\Overtime\Http\Controllers\OvertimeController;
use Portal\Overtime\Http\Controllers\OvertimeRequestController;
use Portal\Overtime\Http\Controllers\OvertimeClaimController;
Route::group(
[
......@@ -15,27 +12,73 @@
function () {
Route::get('index', ['uses' => 'OvertimeController@index', 'as' => 'overtime.index']);
Route::get('list', ['uses' => 'OvertimeClaimController@getListOvertimeClaim', 'as' => 'overtime.listovertime']);
// OVERTIME CLAIM
Route::get( 'claim/create', ['uses' => 'OvertimeClaimController@createOvertimeClaim', 'as' => 'overtime.createovertimeclaim']);
// OT CLAIM - Staff
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']);
Route::get( 'claim/existing-months', ['uses' => 'OvertimeClaimController@getExistingMonths', 'as' => 'overtime.existingmonths']);
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/existing-months', ['uses' => 'OvertimeClaimController@getExistingMonths', 'as' => 'overtime.existingmonths']);
Route::get('claim/{id}/view', ['uses' => 'OvertimeClaimController@viewOvertimeClaim', 'as' => 'overtime.viewovertimeclaim']);
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/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}/submit', ['uses' => 'OvertimeClaimController@submitOvertimeClaim', 'as' => 'overtime.submitovertimeclaim']);
Route::post('claim/{id}/kueri-respond', ['uses' => 'OvertimeClaimController@saveKueriRespond', 'as' => 'overtime.savekueriresponddetail']);
Route::post('claim/{id}/update', ['uses' => 'OvertimeClaimController@updateOvertimeClaim', 'as' => 'overtime.updateovertimeclaim']);
Route::post('claim/{id}/delete', ['uses' => 'OvertimeClaimController@deleteOvertimeClaim', 'as' => 'overtime.deleteovertimeclaim']);
Route::get('claim/audit-trail', ['uses' => 'OvertimeClaimController@getAuditTrailList', 'as' => 'overtime.audittrail']);
Route::post('claim/{id}/batal', ['uses' => 'OvertimeClaimController@batalOvertimeClaim', 'as' => 'overtime.batalovertimeclaim']);
Route::get('claim/attendance', ['uses' => 'OvertimeClaimController@getAttendanceByDate', 'as' => 'overtime.getattendance']);
// OT CLAIM - Project Manager (PM)
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']);
Route::post('claim/{id}/kueri', ['uses' => 'OvertimeProjectManagerController@kueriClaim', 'as' => 'overtime.pmkuericlaim']);
// OT CLAIM - Head of Department (HOD)
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']);
Route::post('claim/hod/{id}/kueri', ['uses' => 'OvertimeClaimHodController@kueriClaim', 'as' => 'overtime.hodkuericlaim']);
// OVERTIME REQUEST
Route::get( 'request/create', ['uses' => 'OvertimeRequestController@createOvertimeRequest', 'as' => 'overtime.createovertimerequest']);
// OT CLAIM - Project Director (PD)
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']);
Route::post('claim/pd/{id}/kueri', ['uses' => 'OvertimeClaimPdController@kueriClaim', 'as' => 'overtime.pdkuericlaim']);
// OT REQUEST - Project Manager (PM)
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']);
Route::post('request/store', ['uses' => 'OvertimeRequestController@storeOvertimeRequest', 'as' => 'overtime.storeovertimerequest']);
Route::get( 'request/{id}/edit', ['uses' => 'OvertimeRequestController@editOvertimeRequest', 'as' => 'overtime.editovertimerequest']);
Route::get('request/{id}/edit', ['uses' => 'OvertimeRequestController@editOvertimeRequest', 'as' => 'overtime.editovertimerequest']);
Route::post('request/{id}/update', ['uses' => 'OvertimeRequestController@updateOvertimeRequest', 'as' => 'overtime.updateovertimerequest']);
Route::post('request/{id}/batal', ['uses' => 'OvertimeRequestController@batalOvertimeRequest', 'as' => 'overtime.batalovertimerequest']);
Route::post('request/{id}/delete', ['uses' => 'OvertimeRequestController@deleteOvertimeRequest', 'as' => 'overtime.deleteovertimerequest']);
Route::get('request/{id}/view', ['uses' => 'OvertimeRequestController@viewOvertimeRequest', 'as' => 'overtime.viewovertimerequest']);
Route::post('request/{id}/detail/add', ['uses' => 'OvertimeRequestController@addOvertimeRequestDetail', 'as' => 'overtime.addovertimerequestdetail']);
Route::post('request/detail/{id}/update', ['uses' => 'OvertimeRequestController@updateOvertimeRequestDetail', 'as' => 'overtime.updateovertimerequestdetail']);
Route::post('request/detail/{id}/remove', ['uses' => 'OvertimeRequestController@removeOvertimeRequestDetail', 'as' => 'overtime.removeovertimerequestdetail']);
Route::post('request/{id}/submit', ['uses' => 'OvertimeRequestController@submitOvertimeRequest', 'as' => 'overtime.submitovertimerequest']);
Route::post('request/{id}/kueri-respond', ['uses' => 'OvertimeRequestController@saveKueriRespond', 'as' => 'overtime.savekueriresponddetail.request']);
Route::get('projectmanager/list', ['uses' => 'OvertimeProjectManagerController@getProjectManagerReviewList', 'as' => 'overtime.projectmanager.list']);
Route::get('requestform/{id}/view', ['uses' => 'OvertimeProjectManagerController@viewRequestForm', 'as' => 'overtime.pmviewrequestform']);
// OT REQUEST - Head of Department (HOD)
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']);
Route::post('request/hod/{id}/reject', ['uses' => 'OvertimeHodController@rejectRequestForm', 'as' => 'overtime.hodrejectrequest']);
Route::post('request/hod/{id}/kueri', ['uses' => 'OvertimeHodController@kueriRequestForm', 'as' => 'overtime.hodkuerirequest']);
// OT REQUEST - Project Director (PD)
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']);
Route::post('request/pd/{id}/reject', ['uses' => 'OvertimePdController@rejectRequestForm', 'as' => 'overtime.pdrejectrequest']);
Route::post('request/pd/{id}/kueri', ['uses' => 'OvertimePdController@kueriRequestForm', 'as' => 'overtime.pdkuerirequest']);
}
);
\ No newline at end of file
<?php
namespace Portal\Overtime\Data\Repo;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Portal\Overtime\Model\OvertimeAuditQuery;
use Portal\Overtime\Model\OvertimeAuditTrail;
use Portal\Overtime\Model\OvertimeClaimDetail;
use Portal\Overtime\Model\OvertimeClaimMain;
class OvertimeClaimHodRepo
{
// =========================================================================
// STATUSES
// =========================================================================
public function getOtStatuses(): \Illuminate\Support\Collection
{
return DB::table('lkp_status')
->where('module', 'ot')
->where('status', 1)
->orderBy('ref_id')
->get()
->keyBy('ref_id');
}
private function currentHodDepartmentId(): ?int
{
return DB::table('staff_info')
->where('fk_users', Auth::id())
->value('fk_lkp_department');
}
// =========================================================================
// HOD REVIEW LIST — status 7 is set by HOD itself, so the inbox is
// claims sokong'd by PM (status 5) waiting for HOD action
// =========================================================================
public function getHodReviewList($request)
{
$search = $request->get('search');
return OvertimeClaimMain::where('ocm_status', 5)
->where(function ($q) use ($search) {
$q->where('ocm_apply_no', 'like', "%{$search}%")
->orWhere('ocm_staff_name', 'like', "%{$search}%");
})
->orderBy('created_at', 'desc')
->paginate(10);
}
// =========================================================================
// FIND CLAIM (read-only view)
// =========================================================================
public function findClaim(int $id): OvertimeClaimMain
{
return OvertimeClaimMain::findOrFail($id);
}
public function findClaimDetails(int $id)
{
return OvertimeClaimDetail::where('fk_overtime_claim_main', $id)
->orderBy('ocd_date', 'asc')
->get();
}
public function countPendingPmReviews(int $claimId): int
{
return OvertimeClaimDetail::where('fk_overtime_claim_main', $claimId)
->where('ocd_pm_reviewed', 0)
->count();
}
public function findLatestKueri(int $claimId): ?OvertimeAuditQuery
{
$claim = $this->findClaim($claimId);
return OvertimeAuditQuery::where('fk_main', $claim->id)
->where('no_permohonan', $claim->ocm_apply_no)
->orderBy('created_at', 'desc')
->first();
}
public function findQueryHistory(int $claimId)
{
$claim = $this->findClaim($claimId);
return OvertimeAuditQuery::where('fk_main', $claim->id)
->where('no_permohonan', $claim->ocm_apply_no)
->orderBy('created_at', 'desc')
->get();
}
// =========================================================================
// SOKONG — HOD approves, forwards to PD
// =========================================================================
public function sokongClaim($request, int $claimId): OvertimeClaimMain
{
$claim = $this->findClaim($claimId);
$pending = $this->countPendingPmReviews($claimId);
if ($pending > 0) {
throw new \Exception('Belum semua PM telah menyemak. Sokongan HOD tidak dibenarkan lagi.');
}
$claim->update([
'ocm_status' => 7, // Disokong Oleh HOD
'updated_by' => Auth::id(),
]);
$this->logAudit('UPDATE', $claim->id, null,
"menyokong permohonan {$claim->ocm_apply_no} dan menghantar ke PD.");
return $claim;
}
// =========================================================================
// KUERI — HOD sends back to pemohon (same pattern as PM kueri)
// =========================================================================
public function kueriClaim($request, int $claimId): OvertimeClaimMain
{
$claim = $this->findClaim($claimId);
$claim->update([
'ocm_status' => 8, // Dikueri Oleh HOD
'kueri_status' => 1,
'updated_by' => Auth::id(),
]);
OvertimeAuditQuery::create([
'fk_main' => $claim->id,
'no_permohonan' => $claim->ocm_apply_no,
'fk_user_kueri' => Auth::id(),
'remarks' => $request->remarks,
'respond' => null,
'tarikh' => now(),
]);
$this->logAudit('UPDATE', $claim->id, null,
"mengueri permohonan {$claim->ocm_apply_no} dan menghantar semula kepada pemohon.");
return $claim;
}
// =========================================================================
// AUDIT TRAIL HELPER
// =========================================================================
private function logAudit(string $taskCode, int $claimId, ?int $detailId, string $extra = ''): void
{
$taskId = DB::table('lkp_overtime_task')
->where('task_code', $taskCode)
->where('is_active', 1)
->value('id');
$taskName = DB::table('lkp_overtime_task')
->where('task_code', $taskCode)
->value('task_name') ?? $taskCode;
$userName = Auth::user()->name ?? 'Unknown';
$applyNo = OvertimeClaimMain::where('id', $claimId)->value('ocm_apply_no') ?? '-';
$description = "{$userName} melakukan tindakan {$taskName} pada permohonan {$applyNo}.";
if ($extra) {
$description .= ' ' . $extra;
}
OvertimeAuditTrail::create([
'fk_overtime_claim_main' => $claimId,
'fk_overtime_claim_detail' => $detailId,
'fk_lkp_overtime_task' => $taskId,
'user' => Auth::id(),
'description' => $description,
]);
}
}
<?php
namespace Portal\Overtime\Data\Repo;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Portal\Overtime\Model\OvertimeAuditQuery;
use Portal\Overtime\Model\OvertimeAuditTrail;
use Portal\Overtime\Model\OvertimeClaimDetail;
use Portal\Overtime\Model\OvertimeClaimMain;
class OvertimeClaimPdRepo
{
// =========================================================================
// STATUSES
// =========================================================================
public function getOtStatuses(): \Illuminate\Support\Collection
{
return DB::table('lkp_status')
->where('module', 'ot')
->where('status', 1)
->orderBy('ref_id')
->get()
->keyBy('ref_id');
}
// =========================================================================
// PD REVIEW LIST — claims sokong'd by HOD (status 7) waiting for PD action
// =========================================================================
public function getPdReviewList($request)
{
$search = $request->get('search');
return OvertimeClaimMain::where('ocm_status', 7)
->where(function ($q) use ($search) {
$q->where('ocm_apply_no', 'like', "%{$search}%")
->orWhere('ocm_staff_name', 'like', "%{$search}%");
})
->orderBy('created_at', 'desc')
->paginate(10);
}
// =========================================================================
// FIND CLAIM (read-only view)
// =========================================================================
public function findClaim(int $id): OvertimeClaimMain
{
return OvertimeClaimMain::findOrFail($id);
}
public function findClaimDetails(int $id)
{
return OvertimeClaimDetail::where('fk_overtime_claim_main', $id)
->orderBy('ocd_date', 'asc')
->get();
}
public function findLatestKueri(int $claimId): ?OvertimeAuditQuery
{
$claim = $this->findClaim($claimId);
return OvertimeAuditQuery::where('fk_main', $claim->id)
->where('no_permohonan', $claim->ocm_apply_no)
->orderBy('created_at', 'desc')
->first();
}
public function findQueryHistory(int $claimId)
{
$claim = $this->findClaim($claimId);
return OvertimeAuditQuery::where('fk_main', $claim->id)
->where('no_permohonan', $claim->ocm_apply_no)
->orderBy('created_at', 'desc')
->get();
}
// =========================================================================
// SOKONG — PD gives final approval
// =========================================================================
public function sokongClaim($request, int $claimId): OvertimeClaimMain
{
$claim = $this->findClaim($claimId);
$claim->update([
'ocm_status' => 11, // Permohonan Diluluskan (final)
'ocm_approved_by' => Auth::id(),
'ocm_approved_date' => now(),
'updated_by' => Auth::id(),
]);
$this->logAudit('UPDATE', $claim->id, null,
"meluluskan permohonan {$claim->ocm_apply_no}.");
return $claim;
}
// =========================================================================
// KUERI — PD sends back to pemohon (same pattern as PM/HOD kueri)
// =========================================================================
public function kueriClaim($request, int $claimId): OvertimeClaimMain
{
$claim = $this->findClaim($claimId);
$claim->update([
'ocm_status' => 10, // Dikueri Oleh BOD/PD
'kueri_status' => 1,
'updated_by' => Auth::id(),
]);
OvertimeAuditQuery::create([
'fk_main' => $claim->id,
'no_permohonan' => $claim->ocm_apply_no,
'fk_user_kueri' => Auth::id(),
'remarks' => $request->remarks,
'respond' => null,
'tarikh' => now(),
]);
$this->logAudit('UPDATE', $claim->id, null,
"mengueri permohonan {$claim->ocm_apply_no} dan menghantar semula kepada pemohon.");
return $claim;
}
// =========================================================================
// AUDIT TRAIL HELPER
// =========================================================================
private function logAudit(string $taskCode, int $claimId, ?int $detailId, string $extra = ''): void
{
$taskId = DB::table('lkp_overtime_task')
->where('task_code', $taskCode)
->where('is_active', 1)
->value('id');
$taskName = DB::table('lkp_overtime_task')
->where('task_code', $taskCode)
->value('task_name') ?? $taskCode;
$userName = Auth::user()->name ?? 'Unknown';
$applyNo = OvertimeClaimMain::where('id', $claimId)->value('ocm_apply_no') ?? '-';
$description = "{$userName} melakukan tindakan {$taskName} pada permohonan {$applyNo}.";
if ($extra) {
$description .= ' ' . $extra;
}
OvertimeAuditTrail::create([
'fk_overtime_claim_main' => $claimId,
'fk_overtime_claim_detail' => $detailId,
'fk_lkp_overtime_task' => $taskId,
'user' => Auth::id(),
'description' => $description,
]);
}
}
......@@ -32,6 +32,29 @@ public function getOtStatuses(): \Illuminate\Support\Collection
->keyBy('ref_id');
}
public function getAttendanceByDate(string $date): ?array
{
$staffInfoId = $this->currentStaffInfoId();
if (!$staffInfoId) {
return null;
}
$attendance = DB::table('attendance')
->where('fk_staff_info', $staffInfoId)
->whereDate('date', $date)
->first();
if (!$attendance) {
return null;
}
return [
'time_in' => $attendance->time_in,
'time_out' => $attendance->time_out,
];
}
// LIST
......@@ -112,12 +135,12 @@ public function getExistingMonthsForUser(): array
return OvertimeClaimMain::where('fk_lkp_staff_info', $staffInfoId)
->whereNotNull('ocm_month')
->whereNotNull('ocm_year')
->whereNotIn('ocm_status', [4])
->get()
->map(fn ($item) => $item->ocm_year . str_pad($item->ocm_month, 2, '0', STR_PAD_LEFT))
->toArray();
}
// ADD DETAIL
......@@ -133,6 +156,7 @@ public function addOvertimeClaimDetail(int $id, $request): OvertimeClaimDetail
'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,
......@@ -206,8 +230,12 @@ public function updateOvertimeClaim($request, int $id): OvertimeClaimMain
// SUBMIT
// =========================================================================
// SUBMIT (status-aware — first submission goes to 2, resubmission after kueri goes to 3)
// =========================================================================
public function submitOvertimeClaim($request, int $id): OvertimeClaimMain
{
{
$record = $this->findOvertimeClaim($id);
$detailCount = OvertimeClaimDetail::where('fk_overtime_claim_main', $id)->count();
......@@ -215,16 +243,27 @@ public function submitOvertimeClaim($request, int $id): OvertimeClaimMain
throw new \Exception('Sila tambah sekurang-kurangnya satu hari tuntutan lebih masa.');
}
$isResubmission = $record->ocm_status == 6 && $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,
]);
$record->update([
'ocm_status' => 2, // Permohonan Baharu
'ocm_status' => $newStatus,
'ocm_submit_date' => now(),
'updated_by' => Auth::id(),
]);
$this->getAuditTrail('UPDATE', $id, null, 'Tuntutan dihantar untuk kelulusan.');
$this->getAuditTrail('SUBMIT', $id, null,
$isResubmission ? 'Tuntutan dihantar semula selepas kueri.' : 'Tuntutan dihantar untuk kelulusan.');
return $record;
}
}
// DELETE
......@@ -286,4 +325,47 @@ public function getAuditTrailList($request)
->orderBy('created_at', 'desc')
->paginate(15);
}
// =========================================================================
// BATAL (cancel — allowed only from Draf=1 or Dikueri oleh PM=6)
// =========================================================================
public function batalOvertimeClaim(int $id): OvertimeClaimMain
{
$record = $this->findOvertimeClaim($id);
if (!in_array($record->ocm_status, [1, 6])) {
throw new \Exception('Permohonan pada status semasa tidak boleh dibatalkan.');
}
$record->update([
'ocm_status' => 4, // Batal Permohonan
'updated_by' => Auth::id(),
]);
$this->getAuditTrail('UPDATE', $id, null, 'Permohonan dibatalkan oleh pemohon.');
return $record;
}
// =========================================================================
// SAVE KUERI RESPOND (pemohon responding to PM's kueri remark)
// =========================================================================
public function saveKueriRespond(int $claimId, string $respond): void
{
$record = $this->findOvertimeClaim($claimId);
$query = \Portal\Overtime\Model\OvertimeAuditQuery::where('fk_main', $record->id)
->where('no_permohonan', $record->ocm_apply_no)
->orderBy('created_at', 'desc')
->first();
if ($query) {
$query->update(['respond' => $respond]);
}
// Audit trail: claimant respond to kueri
$this->getAuditTrail('RESPOND', $record->id, null, 'Pemohon menjawab kueri: ' . substr($respond, 0, 100));
}
}
<?php
namespace Portal\Overtime\Data\Repo;
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;
use Portal\Overtime\Model\OvertimeRequestDetail;
class OvertimeHodRepo
{
private function currentStaffId(): ?string
{
return DB::table('staff_info')
->where('fk_users', Auth::id())
->value('staff_id');
}
private function currentHodDepartmentId(): ?int
{
$staffId = $this->currentStaffId();
if (!$staffId) {
return null;
}
return DB::table('staff_info')
->where('staff_id', $staffId)
->value('fk_lkp_department');
}
private function projectTeamProjectColumn(): string
{
if (Schema::hasColumn('project_team', 'pt_project_id')) {
return 'pt_project_id';
}
return 'fk_project_id';
}
private function currentHodProjectIds(): \Illuminate\Support\Collection
{
$departmentId = $this->currentHodDepartmentId();
if (!$departmentId) {
return collect();
}
$projectColumn = $this->projectTeamProjectColumn();
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();
}
public function getOtStatuses(): \Illuminate\Support\Collection
{
return DB::table('lkp_status')
->where('module', 'ot')
->where('status', 1)
->orderBy('ref_id')
->get()
->keyBy('ref_id');
}
// =========================================================================
// LIST (all status=2 — no role scoping for now)
// =========================================================================
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')
->paginate(10);
}
// =========================================================================
// FIND
// =========================================================================
public function findRequestForm(int $id): OvertimeRequestMain
{
return OvertimeRequestMain::findOrFail($id);
}
public function findRequestFormDetails(int $id)
{
return OvertimeRequestDetail::where('fk_overtime_request_main', $id)
->orderBy('id', 'asc')
->get();
}
public function findQueryHistory(int $id)
{
$record = $this->findRequestForm($id);
return OvertimeAuditQuery::where('fk_main', $record->id)
->where('no_permohonan', $record->orm_apply_no)
->orderBy('created_at', 'desc')
->get();
}
// =========================================================================
// SOKONG → status 7 (Disokong Oleh HOD, forwarded to PD)
// =========================================================================
public function approveRequestForm(int $id): OvertimeRequestMain
{
$record = OvertimeRequestMain::findOrFail($id);
if ($record->orm_status !== 2) {
throw new \Exception('Borang ini tidak lagi menunggu semakan HOD.');
}
$record->update([
'orm_status' => 7, // Disokong Oleh HOD
'updated_by' => Auth::id(),
]);
// Audit trail: HOD approval
$this->logAuditTrail('APPROVE', $record->id, null, 'Borang permohonan disokong oleh HOD.');
return $record;
}
// =========================================================================
// KUERI → status 8 (Dikueri Oleh HOD, sent back to PM)
// =========================================================================
public function kueriRequestForm(int $id, string $remark): OvertimeRequestMain
{
$record = OvertimeRequestMain::findOrFail($id);
if ($record->orm_status !== 2) {
throw new \Exception('Borang ini tidak lagi menunggu semakan HOD.');
}
$record->update([
'orm_status' => 8, // Dikueri Oleh HOD
'orm_query_remark' => $remark,
'orm_query_by' => Auth::id(),
'orm_query_respond'=> null,
'updated_by' => Auth::id(),
]);
OvertimeAuditQuery::create([
'fk_main' => $record->id,
'no_permohonan' => $record->orm_apply_no,
'fk_user_kueri' => Auth::id(),
'remarks' => $remark,
'respond' => null,
'tarikh' => now(),
]);
// Audit trail: HOD kueri
$this->logAuditTrail('KUERI', $record->id, null, 'Request form queried by HOD.');
return $record;
}
// =========================================================================
// REJECT → status 12 (Permohonan Ditolak)
// =========================================================================
public function rejectRequestForm(int $id): OvertimeRequestMain
{
$record = OvertimeRequestMain::findOrFail($id);
$record->update([
'orm_status' => 12,
'updated_by' => Auth::id(),
]);
// Audit trail: HOD reject
$this->logAuditTrail('REJECT', $record->id, null, 'Request form rejected by HOD.');
return $record;
}
// AUDIT TRAIL HELPER (for request actions)
private function logAuditTrail(string $taskCode, int $requestId, ?int $detailId = null, string $extra = ''): void
{
$taskId = DB::table('lkp_overtime_task')
->where('task_code', $taskCode)
->where('is_active', 1)
->value('id');
$taskName = DB::table('lkp_overtime_task')
->where('task_code', $taskCode)
->value('task_name') ?? $taskCode;
$userName = Auth::user()->name ?? 'Unknown';
$applyNo = OvertimeRequestMain::where('id', $requestId)->value('orm_apply_no') ?? '-';
$description = "{$userName} performed the action {$taskName} on application {$applyNo}.";
if ($extra) {
$description .= ' ' . $extra;
}
OvertimeAuditTrail::create([
'fk_overtime_claim_main' => null,
'fk_overtime_claim_detail' => null,
'fk_lkp_overtime_task' => $taskId,
'user' => Auth::id(),
'description' => $description,
]);
}
}
<?php
namespace Portal\Overtime\Data\Repo;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Portal\Overtime\Model\OvertimeAuditQuery;
use Portal\Overtime\Model\OvertimeAuditTrail;
use Portal\Overtime\Model\OvertimeRequestMain;
use Portal\Overtime\Model\OvertimeRequestDetail;
class OvertimePdRepo
{
public function getOtStatuses(): \Illuminate\Support\Collection
{
return DB::table('lkp_status')
->where('module', 'ot')
->where('status', 1)
->orderBy('ref_id')
->get()
->keyBy('ref_id');
}
// =========================================================================
// LIST (status 7 = pending, status 11 = approved — both stay in PD list)
// =========================================================================
public function getReviewList($request)
{
$search = $request->get('search', '');
return OvertimeRequestMain::whereIn('orm_status', [7, 11])
->whereNull('deleted_at')
->when($search, fn ($q) => $q->where('orm_apply_no', 'like', "%{$search}%"))
->orderBy('created_at', 'desc')
->paginate(10);
}
// =========================================================================
// FIND
// =========================================================================
public function findRequestForm(int $id): OvertimeRequestMain
{
return OvertimeRequestMain::findOrFail($id);
}
public function findRequestFormDetails(int $id)
{
return OvertimeRequestDetail::where('fk_overtime_request_main', $id)
->orderBy('id', 'asc')
->get();
}
public function findQueryHistory(int $id)
{
$record = $this->findRequestForm($id);
return OvertimeAuditQuery::where('fk_main', $record->id)
->where('no_permohonan', $record->orm_apply_no)
->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);
if ($record->orm_status !== 7) {
throw new \Exception('Borang ini tidak lagi menunggu kelulusan PD.');
}
$record->update([
'orm_status' => 9, // Diluluskan Oleh Project Director
'orm_approved_by_id' => Auth::id(),
'orm_approved_date' => now(),
'updated_by' => Auth::id(),
]);
// Audit trail: PD approval
$this->logAuditTrail('APPROVE', $record->id, null, 'Borang permohonan diluluskan oleh PD.');
return $record;
}
// =========================================================================
// KUERI → status 10 (Dikueri Oleh BOD, sent back to PM)
// =========================================================================
public function kueriRequestForm(int $id, string $remark): OvertimeRequestMain
{
$record = $this->findRequestForm($id);
if (! in_array($record->orm_status, [7, 11])) {
throw new \Exception('Borang ini tidak boleh dikueri pada status semasa.');
}
$record->update([
'orm_status' => 10, // Dikueri Oleh BOD
'orm_query_remark' => $remark,
'orm_query_by' => Auth::id(),
'orm_query_respond'=> null,
'updated_by' => Auth::id(),
]);
OvertimeAuditQuery::create([
'fk_main' => $record->id,
'no_permohonan' => $record->orm_apply_no,
'fk_user_kueri' => Auth::id(),
'remarks' => $remark,
'respond' => null,
'tarikh' => now(),
]);
// Audit trail: PD kueri
$this->logAuditTrail('KUERI', $record->id, null, 'Request form queried by PD.');
return $record;
}
// =========================================================================
// REJECT → status 12 (Permohonan Ditolak)
// =========================================================================
public function rejectRequestForm(int $id): OvertimeRequestMain
{
$record = $this->findRequestForm($id);
if (! in_array($record->orm_status, [7, 11])) {
throw new \Exception('Borang ini tidak boleh ditolak pada status semasa.');
}
$record->update([
'orm_status' => 12, // Permohonan Ditolak
'updated_by' => Auth::id(),
]);
// Audit trail: PD reject
$this->logAuditTrail('REJECT', $record->id, null, 'Request form rejected by PD.');
return $record;
}
// AUDIT TRAIL HELPER (for PD actions)
private function logAuditTrail(string $taskCode, int $requestId, ?int $detailId = null, string $extra = ''): void
{
$taskId = DB::table('lkp_overtime_task')
->where('task_code', $taskCode)
->where('is_active', 1)
->value('id');
$taskName = DB::table('lkp_overtime_task')
->where('task_code', $taskCode)
->value('task_name') ?? $taskCode;
$userName = Auth::user()->name ?? 'Unknown';
$applyNo = OvertimeRequestMain::where('id', $requestId)->value('orm_apply_no') ?? '-';
$description = "{$userName} performed the action {$taskName} on application {$applyNo}.";
if ($extra) {
$description .= ' ' . $extra;
}
OvertimeAuditTrail::create([
'fk_overtime_claim_main' => null,
'fk_overtime_claim_detail' => null,
'fk_lkp_overtime_task' => $taskId,
'user' => Auth::id(),
'description' => $description,
]);
}
}
<?php
namespace Portal\Overtime\Data\Repo;
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\OvertimeClaimDetail;
use Portal\Overtime\Model\OvertimeClaimMain;
class OvertimeProjectManagerRepo
{
// =========================================================================
// HELPERS
// =========================================================================
private function currentStaffId(): ?string
{
return DB::table('staff_info')
->where('fk_users', Auth::id())
->value('staff_id');
}
private function currentProjectTeamId(): ?int
{
$staffId = $this->currentStaffId();
if (!$staffId) return null;
return DB::table('project_team')
->where('pt_staff_id', $staffId)
->value('id');
}
private function projectTeamProjectColumn(): string
{
if (Schema::hasColumn('project_team', 'pt_project_id')) {
return 'pt_project_id';
}
return 'fk_project_id';
}
private function currentPmProjectIds(): \Illuminate\Support\Collection
{
$staffId = $this->currentStaffId();
if (!$staffId) return collect();
return DB::table('project_team')
->where('pt_staff_id', $staffId)
->pluck($this->projectTeamProjectColumn())
->filter()
->unique()
->values();
}
public function getPmProjectIds(): \Illuminate\Support\Collection
{
return $this->currentPmProjectIds();
}
public function getOtStatuses(): \Illuminate\Support\Collection
{
return DB::table('lkp_status')
->where('module', 'ot')
->where('status', 1)
->orderBy('ref_id')
->get()
->keyBy('ref_id');
}
// =========================================================================
// PM REVIEW LIST (status 2 = Permohonan, status 3 = Permohonan Semula)
// =========================================================================
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.
$query = OvertimeClaimMain::with('details')
->whereIn('ocm_status', [2, 3]);
if ($search) {
$query->where(function ($q) use ($search) {
$q->where('ocm_apply_no', 'like', "%{$search}%")
->orWhere('ocm_staff_name', 'like', "%{$search}%");
});
}
// Keep original semantics: only show claims that have at least one
// detail that hasn't been PM-reviewed yet.
$query->whereHas('details', function ($q) {
$q->where('ocd_pm_reviewed', 0);
});
return $query->orderBy('created_at', 'desc')->paginate(10);
}
// =========================================================================
// FIND CLAIM (full read-only details for PM view)
// =========================================================================
public function findClaimWithDetails(int $id): array
{
$main = OvertimeClaimMain::findOrFail($id);
$projectIds = $this->currentPmProjectIds();
$details = OvertimeClaimDetail::where('fk_overtime_claim_main', $id)
->orderBy('ocd_date', 'asc')
->get();
$details->each(function ($detail) use ($projectIds) {
$detail->pm_owned = $projectIds->contains($detail->fk_lkp_project);
});
$projectIds = $details->pluck('fk_lkp_project')->filter()->unique()->values();
$projectNames = $projectIds->isEmpty()
? collect()
: DB::table('lkp_project')->whereIn('id', $projectIds)->pluck('p_project_description', 'id');
$queryHistory = OvertimeAuditQuery::where('fk_main', $main->id)
->where('no_permohonan', $main->ocm_apply_no)
->orderBy('created_at', 'desc')
->get();
return [
'main' => $main,
'details' => $details,
'projectNames' => $projectNames,
'latestQuery' => $queryHistory->first(),
'queryHistory' => $queryHistory,
];
}
// =========================================================================
// APPROVED REQUEST FORMS (for Sokong picker — PM's own forms only)
// =========================================================================
public function getApprovedRequestFormsForCurrentPm(?OvertimeClaimMain $claim = null)
{
$projectIds = $this->currentPmProjectIds();
$query = DB::table('overtime_request_main as orm')
->select('orm.*', 'orm.orm_name as applicant_name')
->where('orm.orm_status', 9)
->whereNull('orm.deleted_at');
$forms = $query->orderBy('orm.orm_date', 'desc')->get();
$projectIdsForNames = $forms->pluck('orm_project')->filter()->unique()->values();
$projectNames = $projectIdsForNames->isEmpty()
? collect()
: DB::table('lkp_project')->whereIn('id', $projectIdsForNames)->pluck('p_project_description', 'id');
foreach ($forms as $form) {
$form->project_name = $projectNames[$form->orm_project] ?? '-';
$form->request_month_year = !empty($form->orm_date)
? \Carbon\Carbon::parse($form->orm_date)->format('m/Y')
: '-';
$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 !== ''));
}
return $forms;
}
public function getRequestFormSelectionData(?OvertimeClaimMain $claim = null): array
{
$forms = $this->getApprovedRequestFormsForCurrentPm($claim);
$months = collect();
$staffNames = collect();
foreach ($forms as $form) {
$monthKey = $form->request_month_year ?: '-';
$months->put($monthKey, $monthKey);
foreach ($form->request_staff_names as $name) {
if ($name !== '') {
$staffNames->put($name, $name);
}
}
}
return [
'forms' => $forms,
'months' => $months->sortKeys(),
'staffNames' => $staffNames->sort(),
];
}
private function getRequestFormStaffNames(int $requestFormId): \Illuminate\Support\Collection
{
$details = DB::table('overtime_request_detail')
->where('fk_overtime_request_main', $requestFormId)
->pluck('ord_name')
->filter(function ($value) {
return trim((string) $value) !== '';
})
->map(function ($value) {
return trim((string) $value);
})
->unique()
->values();
return $details;
}
private function resolveRequestFormStaffName($form): string
{
$value = $form->applicant_name ?? $form->orm_name ?? null;
if ($value === null || $value === '') {
return '';
}
if (is_numeric((string) $value)) {
$staffInfo = DB::table('staff_info')->where('fk_users', (int) $value)->first();
if ($staffInfo) {
return trim((string) ($staffInfo->fullname ?: $staffInfo->user_name ?: $staffInfo->staff_id ?: ''));
}
$userName = DB::table('users')->where('id', (int) $value)->value('name');
if ($userName) {
return trim((string) $userName);
}
return (string) $value;
}
return trim((string) $value);
}
public function getRequestFormSelectionByFormId(int $requestFormId): array
{
$form = DB::table('overtime_request_main as orm')
->select('orm.*', 'orm.orm_name as applicant_name')
->where('orm.id', $requestFormId)
->where('orm.orm_status', 9)
->whereNull('orm.deleted_at')
->first();
if (!$form) {
return [];
}
$projectName = DB::table('lkp_project')
->where('id', $form->orm_project)
->value('p_project_description') ?: '-';
$form->project_name = $projectName;
$form->request_month_year = !empty($form->orm_date)
? \Carbon\Carbon::parse($form->orm_date)->format('m/Y')
: '-';
$form->request_staff_name = $this->resolveRequestFormStaffName($form);
return [
'form' => $form,
'month' => $form->request_month_year,
'staffName' => $form->request_staff_name,
];
}
public function findRequestForm(int $id)
{
$main = DB::table('overtime_request_main')->where('id', $id)->first();
$details = DB::table('overtime_request_detail')
->where('fk_overtime_request_main', $id)
->get();
return ['main' => $main, 'details' => $details];
}
// =========================================================================
// SOKONG (approve & forward to HOD)
// =========================================================================
public function sokongClaim(int $id, int $requestFormId): OvertimeClaimMain
{
$record = OvertimeClaimMain::findOrFail($id);
$record->update([
'ocm_status' => 5, // Disemak oleh PM
'updated_by' => Auth::id(),
]);
$this->logAuditTrail('SOKONG', $id, null,
"Permohonan disokong dan dihantar ke HOD. Rujukan borang permohonan PM #{$requestFormId}.");
return $record;
}
public function markClaimReviewed(int $id, int $requestFormId): OvertimeClaimMain
{
$requestForm = DB::table('overtime_request_main')
->where('id', $requestFormId)
->where('orm_status', 9)
->whereNull('deleted_at')
->first();
if (!$requestForm) {
throw new \Exception('Borang permohonan yang dipilih tidak sah.');
}
$projectIds = $this->currentPmProjectIds();
if (!$projectIds->contains($requestForm->orm_project)) {
throw new \Exception('Borang permohonan tidak sepadan dengan projek anda.');
}
$claim = OvertimeClaimMain::findOrFail($id);
if ($claim->ocm_month && $claim->ocm_year) {
$formYear = (int) date('Y', strtotime($requestForm->orm_date));
$formMonth = (int) date('n', strtotime($requestForm->orm_date));
if ($formYear !== (int) $claim->ocm_year || $formMonth !== (int) $claim->ocm_month) {
throw new \Exception('Borang permohonan mesti sepadan dengan bulan tuntutan.');
}
}
$updatedRows = OvertimeClaimDetail::where('fk_overtime_claim_main', $id)
->where('fk_lkp_project', $requestForm->orm_project)
->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)
->count();
if ($pendingCount === 0) {
$claim->update([
'ocm_status' => 5,
'updated_by' => Auth::id(),
]);
}
$this->logAuditTrail('UPDATE', $id, null,
"PM menandakan baris tuntutan projek sebagai disemak. Rujukan borang permohonan PM #{$requestFormId}."
);
return $claim;
}
// =========================================================================
// KUERI (send back to pemohon with remark)
// =========================================================================
public function kueriClaim(int $id, string $remarks): OvertimeClaimMain
{
$record = OvertimeClaimMain::findOrFail($id);
$record->update([
'ocm_status' => 6, // Dikueri oleh PM
'ocm_query_status' => 1,
'updated_by' => Auth::id(),
]);
OvertimeAuditQuery::create([
'fk_main' => $id,
'no_permohonan' => $record->ocm_apply_no,
'fk_user_kueri' => Auth::id(),
'remarks' => $remarks,
'respond' => null,
'tarikh' => now(),
]);
$this->logAuditTrail('KUERI', $id, null, 'Permohonan dikueri balik kepada pemohon.');
return $record;
}
// =========================================================================
// AUDIT TRAIL (shared logger, mirrors OvertimeClaimRepo's version)
// =========================================================================
private function logAuditTrail(string $taskCode, int $claimId, ?int $detailId = null, string $extra = ''): void
{
$taskId = DB::table('lkp_overtime_task')
->where('task_code', $taskCode)
->where('is_active', 1)
->value('id');
$taskName = DB::table('lkp_overtime_task')
->where('task_code', $taskCode)
->value('task_name') ?? $taskCode;
$userName = Auth::user()->name ?? 'Unknown';
$applyNo = OvertimeClaimMain::where('id', $claimId)->value('ocm_apply_no') ?? '-';
$description = "{$userName} melakukan tindakan {$taskName} pada permohonan {$applyNo}.";
if ($extra) {
$description .= ' ' . $extra;
}
OvertimeAuditTrail::create([
'fk_overtime_claim_main' => $claimId,
'fk_overtime_claim_detail' => $detailId,
'fk_lkp_overtime_task' => $taskId,
'user' => Auth::id(),
'description' => $description,
]);
}
}
......@@ -2,54 +2,484 @@
namespace Portal\Overtime\Data\Repo;
use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Input;
use Carbon\Carbon;
use App\Events\AuditLog;
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;
use Portal\Overtime\Model\OvertimeRequestDetail;
use Auth;
use DB;
use Event;
use File;
use Mail;
use PDF;
use Redirect;
use Curl;
class OvertimeRequestRepo
{
// =========================================================================
// HELPERS
// =========================================================================
use Portal\Overtime\Model\MainOvertime;
use Portal\Mileage\Model\Users;
public function getOtStatuses(): \Illuminate\Support\Collection
{
$statuses = DB::table('lkp_status')
->where('module', 'ot')
->where('status', 1)
->orderBy('ref_id')
->get()
->keyBy('ref_id');
if (!$statuses->has(0)) {
$statuses->put(0, (object) [
'module' => 'ot',
'ref_id' => 0,
'description' => 'Draf',
'status' => 1,
]);
}
return $statuses;
}
/**
* undocumented function
*
* @return testing please hide this function and continue below
* @author afif@3fresources.com
**/
class OvertimeRepo
{
public function index($request)
private function currentStaffId(): ?string
{
return DB::table('staff_info')
->where('fk_users', Auth::id())
->value('staff_id');
}
private function currentStaffInfo()
{
return DB::table('staff_info')
->where('fk_users', Auth::id())
->first();
}
public function resolveApplicantName($ormName, $staffInfo = null): string
{
$value = trim((string) ($ormName ?? ''));
if ($value === '') {
$value = $staffInfo?->fk_users ?? Auth::id();
}
if (is_numeric($value)) {
$staffInfo = $staffInfo ?: DB::table('staff_info')
->where('fk_users', (int) $value)
->first();
if ($staffInfo) {
return trim((string) ($staffInfo->fullname ?: $staffInfo->user_name ?: $staffInfo->staff_id ?: ''));
}
$userName = DB::table('users')
->where('id', (int) $value)
->value('name');
if ($userName) {
return trim((string) $userName);
}
return (string) $value;
}
return $value;
}
public function normalizeApplicantName($ormName, $staffInfo = null): string
{
$value = $ormName ?? null;
if ($value === null || $value === '') {
$value = $staffInfo?->fk_users ?? Auth::id();
}
if (is_numeric((string) $value)) {
return $this->resolveApplicantName($value, $staffInfo);
}
return trim((string) $value);
}
private function projectTeamProjectColumn(): string
{
if (Schema::hasColumn('project_team', 'pt_project_id')) {
return 'pt_project_id';
}
return 'fk_project_id';
}
private function currentProjectTeamIds()
{
// $users = Users::where('status', 'ACTIVE')
// ->paginate(10);
$staffId = $this->currentStaffId();
if (!$staffId) return collect();
// return $users;
return DB::table('project_team')
->where('pt_staff_id', $staffId)
->pluck('id');
}
// overtime crud start
public function overtimeList($request)
private function currentProjectTeamId(?int $projectId = null): ?int
{
$search = request('search');
$staffId = $this->currentStaffId();
if (!$staffId) return null;
$data = MainOvertime::where('om_apply_no','like', '%' . $search . '%')
$query = DB::table('project_team')
->where('pt_staff_id', $staffId);
if ($projectId) {
$query->where($this->projectTeamProjectColumn(), $projectId);
}
return $query->value('id');
}
public function getProjectsForCurrentPm()
{
$staffId = $this->currentStaffId();
if (!$staffId) return collect();
$projectIds = DB::table('project_team')
->where('pt_staff_id', $staffId)
->pluck($this->projectTeamProjectColumn())
->filter()
->unique()
->values();
if ($projectIds->isEmpty()) {
return collect();
}
return DB::table('lkp_project')
->whereIn('id', $projectIds)
->whereNull('deleted_at')
->orderBy('p_project_description')
->get();
}
public function getProjectStaffOptions(int $projectId)
{
$projectColumn = $this->projectTeamProjectColumn();
return DB::table('project_team as pt')
->join('staff_info as si', 'si.staff_id', '=', 'pt.pt_staff_id')
->where("pt.{$projectColumn}", $projectId)
->whereNull('si.deleted_at')
->select('si.id', 'si.staff_id', 'si.fullname', 'si.user_name', 'pt.pt_team')
->distinct()
->orderBy('si.fullname')
->get();
}
public function isStaffNameInRequestProject(int $requestFormId, string $staffName): bool
{
$record = $this->findRequestForm($requestFormId);
return $this->getProjectStaffOptions((int) $record->orm_project)
->contains(function ($staff) use ($staffName) {
$name = $staff->fullname ?: $staff->pt_team ?: $staff->user_name;
return trim((string) $name) === trim($staffName);
});
}
// =========================================================================
// EXISTING PROJECTS (block duplicate form per project, for create modal)
// =========================================================================
public function getExistingProjectMonthsForUser(): array
{
$teamIds = $this->currentProjectTeamIds();
if ($teamIds->isEmpty()) {
return [];
}
return OvertimeRequestMain::whereIn('orm_requested_by_id', $teamIds)
->whereNull('deleted_at')
->whereNotIn('orm_status', [4]) // batal'd forms free up the project again
->whereNotNull('orm_date')
->get()
->map(fn ($row) => sprintf('%s|%s', (string) $row->orm_project, $row->orm_date->format('Ym')))
->toArray();
}
// =========================================================================
// LIST
// =========================================================================
public function getRequestFormList($request)
{
$teamIds = $this->currentProjectTeamIds();
$search = $request->get('search');
return OvertimeRequestMain::whereIn('orm_requested_by_id', $teamIds)
->whereNull('deleted_at')
->when($search, function ($q) use ($search) {
$q->where('orm_apply_no', 'like', "%{$search}%");
})
->orderBy('created_at', 'desc')
->paginate(10);
}
// =========================================================================
// FIND
// =========================================================================
public function findRequestForm(int $id): OvertimeRequestMain
{
return OvertimeRequestMain::findOrFail($id);
}
public function findRequestFormDetails(int $id)
{
return OvertimeRequestDetail::where('fk_overtime_request_main', $id)
->orderBy('id', 'asc')
->get();
}
public function findQueryHistory(int $id)
{
$record = $this->findRequestForm($id);
return OvertimeAuditQuery::where('fk_main', $record->id)
->where('no_permohonan', $record->orm_apply_no)
->orderBy('created_at', 'desc')
->get();
}
// =========================================================================
// STORE MAIN (create — pick project only)
// =========================================================================
public function storeRequestForm($request): OvertimeRequestMain
{
$staffInfo = $this->currentStaffInfo();
$teamId = $this->currentProjectTeamId((int) $request->orm_project);
$team = $teamId ? DB::table('project_team')->where('id', $teamId)->first() : null;
$requestDate = $request->orm_date ? Carbon::parse($request->orm_date) : now();
$record = OvertimeRequestMain::create([
'orm_date' => $requestDate,
'orm_name' => $this->normalizeApplicantName($staffInfo->fk_users ?? Auth::id(), $staffInfo),
'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_requested_by_id' => $teamId,
'orm_requested_date' => now(),
'updated_by' => Auth::id(),
]);
$record->orm_apply_no = 'OTR-' . $requestDate->format('Ym') . '-' . str_pad($record->id, 4, '0', STR_PAD_LEFT);
$record->save();
// Audit trail: creation of request form
$this->logAuditTrail('CREATE', $record->id, null, 'Borang permohonan dicipta.');
return $record;
}
// =========================================================================
// UPDATE MAIN
// =========================================================================
public function updateRequestForm($request, int $id): OvertimeRequestMain
{
$record = $this->findRequestForm($id);
$staffInfo = $this->currentStaffInfo();
$teamId = $this->currentProjectTeamId((int) $record->orm_project);
$team = $teamId ? DB::table('project_team')->where('id', $teamId)->first() : null;
$record->update([
'orm_name' => $this->normalizeApplicantName($record->orm_name ?: ($staffInfo->fk_users ?? Auth::id()), $staffInfo),
'orm_position' => $record->orm_position ?: ($team->role_id ?? null),
'orm_department' => $record->orm_department ?: ($staffInfo->fk_lkp_department ?? null),
'orm_requested_by_id' => $record->orm_requested_by_id ?: $teamId,
'updated_by' => Auth::id(),
]);
return $data;
// Audit trail: update of request form
$this->logAuditTrail('UPDATE', $record->id, null, 'Borang permohonan dikemaskini.');
return $record;
}
// =========================================================================
// BATAL (soft-cancel via status, mirrors claims)
// =========================================================================
public function batalRequestForm(int $id): OvertimeRequestMain
{
$record = $this->findRequestForm($id);
if ($record->orm_status != 0) {
throw new \Exception('Borang permohonan pada status semasa tidak boleh dibatalkan.');
}
$record->update([
'orm_status' => 4, // Batal
'updated_by' => Auth::id(),
]);
// Audit trail: cancel request form
$this->logAuditTrail('UPDATE', $record->id, null, 'Borang permohonan dibatalkan oleh pemohon.');
return $record;
}
// overtime crud end
// =========================================================================
// DELETE (soft delete via deleted_at — kept separate from Batal)
// =========================================================================
public function deleteRequestForm(int $id): void
{
OvertimeRequestDetail::where('fk_overtime_request_main', $id)->delete();
$this->findRequestForm($id)->update(['deleted_at' => now()]);
// Audit trail: delete request form
$this->logAuditTrail('DELETE', $id, null, 'Borang permohonan dipadam.');
}
// =========================================================================
// DETAIL ROWS
// =========================================================================
public function addRequestFormDetail(int $mainId, $request): OvertimeRequestDetail
{
$budgeted = (float) ($request->ord_budgeted ?? 0);
$utilised = (float) ($request->ord_utilised_to_date ?? 0);
$balance = $budgeted - $utilised;
$detail = OvertimeRequestDetail::create([
'fk_overtime_request_main' => $mainId,
'ord_name' => $request->ord_name,
'ord_month_of_overtime' => $request->ord_month_of_overtime,
'ord_budgeted' => $budgeted,
'ord_utilised_to_date' => $utilised,
'ord_planned_ot_hour' => $request->ord_planned_ot_hour ?? 0,
'ord_balance' => $balance,
'ord_reason' => $request->ord_reason,
'ord_total_hours' => $request->ord_total_hours ?? 0,
]);
// Audit trail: add detail row
$this->logAuditTrail('CREATE', $mainId, $detail->id, 'Perkara ditambah pada borang permohonan.');
return $detail;
}
public function updateRequestFormDetail(int $detailId, $request): OvertimeRequestDetail
{
$detail = OvertimeRequestDetail::findOrFail($detailId);
$budgeted = (float) ($request->ord_budgeted ?? 0);
$utilised = (float) ($request->ord_utilised_to_date ?? 0);
$balance = $budgeted - $utilised;
$detail->update([
'ord_name' => $request->ord_name,
'ord_month_of_overtime' => $request->ord_month_of_overtime,
'ord_budgeted' => $budgeted,
'ord_utilised_to_date' => $utilised,
'ord_planned_ot_hour' => $request->ord_planned_ot_hour ?? 0,
'ord_balance' => $balance,
'ord_reason' => $request->ord_reason,
'ord_total_hours' => $request->ord_total_hours ?? 0,
]);
// Audit trail: update detail row
$this->logAuditTrail('UPDATE', $detail->fk_overtime_request_main, $detail->id, 'Perkara dikemaskini pada borang permohonan.');
return $detail->fresh();
}
public function removeRequestFormDetail(int $detailId): void
{
$detail = OvertimeRequestDetail::findOrFail($detailId);
$mainId = $detail->fk_overtime_request_main;
$detail->delete();
// Audit trail: remove detail row
$this->logAuditTrail('DELETE', $mainId, $detailId, 'Perkara dipadam dari borang permohonan.');
}
// =========================================================================
// 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
{
$taskId = DB::table('lkp_overtime_task')
->where('task_code', $taskCode)
->where('is_active', 1)
->value('id');
$taskName = DB::table('lkp_overtime_task')
->where('task_code', $taskCode)
->value('task_name') ?? $taskCode;
$userName = Auth::user()->name ?? 'Unknown';
$applyNo = OvertimeRequestMain::where('id', $claimId)->value('orm_apply_no') ?? '-';
$description = "{$userName} melakukan tindakan {$taskName} pada permohonan {$applyNo}.";
if ($extra) {
$description .= ' ' . $extra;
}
OvertimeAuditTrail::create([
'fk_overtime_claim_main' => null,
'fk_overtime_claim_detail' => null,
'fk_lkp_overtime_task' => $taskId,
'user' => Auth::id(),
'description' => $description,
]);
}
// =========================================================================
// SUBMIT (Hantar untuk Semakan — first submission AND resubmission)
// =========================================================================
public function submitRequestForm(int $id): OvertimeRequestMain
{
$record = $this->findRequestForm($id);
$detailCount = OvertimeRequestDetail::where('fk_overtime_request_main', $id)->count();
if ($detailCount === 0) {
throw new \Exception('Sila tambah sekurang-kurangnya satu entri sebelum menghantar.');
}
$record->update([
'orm_status' => 2, // Permohonan Baharu (also used for resubmission)
'orm_requested_date' => now(),
'updated_by' => Auth::id(),
]);
// Audit trail: submission
$this->logAuditTrail('SUBMIT', $record->id, null, 'Borang permohonan dihantar untuk semakan HOD.');
return $record;
}
// =========================================================================
// SAVE KUERI RESPOND (PM responding to HOD/PD's kueri remark)
// =========================================================================
public function saveKueriRespond(int $id, string $respond): void
{
$record = $this->findRequestForm($id);
DB::table('overtime_request_main')
->where('id', $id)
->update([
'orm_query_respond' => $respond,
'updated_at' => now(),
]);
$query = OvertimeAuditQuery::where('fk_main', $record->id)
->where('no_permohonan', $record->orm_apply_no)
->orderBy('created_at', 'desc')
->first();
if ($query) {
$query->update(['respond' => $respond]);
}
// Audit trail: PM respond to kueri
$this->logAuditTrail('RESPOND', $record->id, null, 'PM menjawab kueri: ' . substr($respond, 0, 100));
}
}
......@@ -7,6 +7,7 @@
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
use Portal\Overtime\Data\Repo\OvertimeClaimRepo;
use Portal\Overtime\Model\OvertimeClaimMain;
......@@ -26,7 +27,7 @@ public function getListOvertimeClaim(Request $request)
$existingMonths = $this->repos->getExistingMonthsForUser();
$statuses = $this->repos->getOtStatuses();
return view('overtime::overtime.list', compact('list', 'existingMonths', 'statuses'));
return view('overtime::overtime.overtimeclaim.list', compact('list', 'existingMonths', 'statuses'));
}
......@@ -37,7 +38,7 @@ public function createOvertimeClaim()
{
$existingMonths = $this->repos->getExistingMonthsForUser();
return view('overtime::overtime.modal.create_modal', compact('existingMonths'));
return view('overtime::overtime.overtimeclaim.create_modal', compact('existingMonths'));
}
public function storeOvertimeClaim(Request $request): JsonResponse
......@@ -74,6 +75,22 @@ public function storeOvertimeClaim(Request $request): JsonResponse
});
}
// ATTENDANCE LOOKUP
public function getAttendanceByDate(Request $request): JsonResponse
{
$request->validate([
'date' => 'required|date',
], [
'date.required' => 'Tarikh diperlukan.',
]);
$attendance = $this->repos->getAttendanceByDate($request->date);
return response()->json([
'success' => true,
'attendance' => $attendance, // null if no record found
]);
}
// EXISTING MONTHS
......@@ -107,6 +124,24 @@ public function viewOvertimeClaim(Request $request, int $id): JsonResponse
->where('ref_id', $main->ocm_status)
->first();
$staffInfo = $main->fk_lkp_staff_info
? DB::table('staff_info')->where('id', $main->fk_lkp_staff_info)->first()
: null;
$departmentId = $staffInfo->fk_lkp_department ?? $main->ocm_division;
$divisionLabel = $departmentId
? (DB::table('lkp_department')->where('id', $departmentId)->value('description')
?: DB::table('lkp_department')->where('id', $departmentId)->value('name')
?: '-')
: '-';
$approvedByName = $main->ocm_approved_by
? (DB::table('staff_info')->where('fk_users', $main->ocm_approved_by)->value('fullname')
?: DB::table('users')->where('id', $main->ocm_approved_by)->value('name')
?: '-')
: '-';
$pmReviewed = $details->every(fn ($d) => (bool) $d->ocd_pm_reviewed);
$pendingPmReviews = $details->where('ocd_pm_reviewed', 0)->count();
return response()->json([
'success' => true,
'data' => [
......@@ -114,12 +149,16 @@ public function viewOvertimeClaim(Request $request, int $id): JsonResponse
'id' => $main->id,
'ocm_apply_no' => $main->ocm_apply_no,
'ocm_staff_name' => $main->ocm_staff_name,
'ocm_division_label' => $divisionLabel,
'ocm_status' => $main->ocm_status,
'ocm_status_label' => $statusRow->description ?? '-',
'ocm_month' => $main->ocm_month,
'ocm_year' => $main->ocm_year,
'ocm_submit_date' => $main->ocm_submit_date?->format('Y-m-d'),
'ocm_approved_by_name' => $approvedByName,
'ocm_approved_date' => $main->ocm_approved_date?->format('Y-m-d'),
'pm_reviewed' => $pmReviewed,
'pm_pending_review_cnt' => $pendingPmReviews,
],
'details' => $details->map(fn ($d) => [
'id' => $d->id,
......@@ -128,30 +167,66 @@ public function viewOvertimeClaim(Request $request, int $id): JsonResponse
'ocd_office_hour' => $d->ocd_office_hour,
'ocd_overtime_from' => $d->ocd_overtime_from,
'ocd_overtime_to' => $d->ocd_overtime_to,
'ocd_total_hours' => $d->ocd_total_hours,
'ocd_effective_hours' => $d->ocd_effective_hours,
'ocd_tasks' => $d->ocd_tasks,
'fk_lkp_project' => $d->fk_lkp_project,
'project_name' => $d->fk_lkp_project
? ($projectNames[$d->fk_lkp_project] ?? '')
: '',
'ocd_pm_reviewed' => (bool) $d->ocd_pm_reviewed,
]),
],
]);
}
// EDIT
public function editOvertimeClaim(Request $request, int $id)
{
{
$data = $this->repos->findOvertimeClaim($id);
// Editable only for Draf (1) or Permohonan Semula (3)
if (!in_array($data->ocm_status, [1, 3, 6])) {
return redirect()
->route('overtime::overtime.listovertime')
->with('error', 'Permohonan yang telah dihantar tidak boleh dikemaskini.');
}
$details = $this->repos->findOvertimeClaimDetails($id);
$projects = DB::table('lkp_project')->orderBy('p_project_description')->get();
$statuses = $this->repos->getOtStatuses();
return view('overtime::overtime.overtimeclaim.edit', compact('data', 'details', 'projects', 'statuses'));
}
$staffInfo = $data->fk_lkp_staff_info
? DB::table('staff_info')->where('id', $data->fk_lkp_staff_info)->first()
: null;
$departmentId = $staffInfo->fk_lkp_department ?? $data->ocm_division;
$data->ocm_division_label = $departmentId
? (DB::table('lkp_department')->where('id', $departmentId)->value('description')
?: DB::table('lkp_department')->where('id', $departmentId)->value('name')
?: '-')
: '-';
$data->ocm_approved_by_name = $data->ocm_approved_by
? (DB::table('staff_info')->where('fk_users', $data->ocm_approved_by)->value('fullname')
?: DB::table('users')->where('id', $data->ocm_approved_by)->value('name')
?: '-')
: '-';
$latestQuery = \Portal\Overtime\Model\OvertimeAuditQuery::where('fk_main', $id)
->where('no_permohonan', $data->ocm_apply_no)
->orderBy('created_at', 'desc')
->first();
$queryHistory = \Portal\Overtime\Model\OvertimeAuditQuery::with('queriedBy')
->where('fk_main', $id)
->where('no_permohonan', $data->ocm_apply_no)
->orderBy('created_at', 'desc')
->get();
return view('overtime::overtime.overtimeclaim.edit', compact('data', 'details', 'projects', 'statuses', 'latestQuery', 'queryHistory'));
}
// ADD DETAIL
......@@ -159,6 +234,14 @@ public function editOvertimeClaim(Request $request, int $id)
public function addOvertimeClaimDetail(Request $request, int $id): JsonResponse
{
$main = $this->repos->findOvertimeClaim($id);
if (!in_array($main->ocm_status, [1, 3, 6])) {
return response()->json([
'success' => false,
'message' => 'Permohonan yang telah dihantar tidak boleh dikemaskini.',
], 403);
}
$request->validate(
[
'ocd_date' => 'required|date',
......@@ -166,6 +249,7 @@ public function addOvertimeClaimDetail(Request $request, int $id): JsonResponse
'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',
],
......@@ -175,6 +259,7 @@ public function addOvertimeClaimDetail(Request $request, int $id): JsonResponse
'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.',
]
......@@ -212,6 +297,16 @@ public function addOvertimeClaimDetail(Request $request, int $id): JsonResponse
public function removeOvertimeClaimDetail(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, 3, 6])) {
return response()->json([
'success' => false,
'message' => 'Permohonan yang telah dihantar tidak boleh dikemaskini.',
], 403);
}
return $this->withTransaction(function () use ($id) {
$this->repos->removeOvertimeClaimDetail($id);
......@@ -228,6 +323,14 @@ public function removeOvertimeClaimDetail(Request $request, int $id): JsonRespon
public function saveOvertimeClaimDetails(Request $request, int $id): JsonResponse
{
$main = $this->repos->findOvertimeClaim($id);
if (!in_array($main->ocm_status, [1, 3, 6])) {
return response()->json([
'success' => false,
'message' => 'Permohonan yang telah dihantar tidak boleh dikemaskini.',
], 403);
}
return $this->withTransaction(function () use ($request, $id) {
$this->repos->updateOvertimeClaim($request, $id);
......@@ -302,6 +405,15 @@ private function withTransaction(callable $callback): JsonResponse
return $response;
} catch (ValidationException $e) {
DB::rollBack();
return response()->json([
'success' => false,
'message' => 'Validation failed.',
'errors' => $e->errors(),
], 422);
} catch (\Exception $e) {
DB::rollBack();
......@@ -312,9 +424,9 @@ private function withTransaction(callable $callback): JsonResponse
}
}
// =========================================================================
// AUDIT TRAIL
// =========================================================================
public function getAuditTrailList(Request $request)
{
......@@ -322,4 +434,42 @@ public function getAuditTrailList(Request $request)
return view('overtime::overtime.audit_trail', compact('list'));
}
// =========================================================================
// BATAL
// =========================================================================
public function batalOvertimeClaim(Request $request, int $id): JsonResponse
{
return $this->withTransaction(function () use ($id) {
$this->repos->batalOvertimeClaim($id);
return response()->json([
'success' => true,
'message' => 'Permohonan berjaya dibatalkan.',
]);
});
}
// =========================================================================
// SAVE KUERI RESPOND
// =========================================================================
public function saveKueriRespond(Request $request, int $id): JsonResponse
{
$request->validate([
'respond' => 'required|string|max:2000',
], [
'respond.required' => 'Sila isi respond.',
]);
return $this->withTransaction(function () use ($request, $id) {
$this->repos->saveKueriRespond($id, $request->respond);
return response()->json([
'success' => true,
'message' => 'Respond berjaya disimpan.',
]);
});
}
}
<?php
namespace Portal\Overtime\Http\Controllers;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\DB;
use Portal\Overtime\Data\Repo\OvertimeClaimHodRepo;
class OvertimeClaimHodController extends Controller
{
public function __construct(
protected OvertimeClaimHodRepo $repos
) {}
// =========================================================================
// HOD REVIEW LIST (status 5, sokong'd by PM)
// =========================================================================
public function getHodReviewList(Request $request)
{
$list = $this->repos->getHodReviewList($request);
$statuses = $this->repos->getOtStatuses();
return view('overtime::overtime.overtimeclaim.hod.list', compact('list', 'statuses'));
}
// =========================================================================
// HOD VIEW — read-only claim render + Sokong/Kueri actions
// =========================================================================
public function viewClaim(Request $request, int $id)
{
$data = $this->repos->findClaim($id);
$details = $this->repos->findClaimDetails($id);
$statuses = $this->repos->getOtStatuses();
$latestKueri = $this->repos->findLatestKueri($id);
$queryHistory = $this->repos->findQueryHistory($id);
$pendingPmReviews = $this->repos->countPendingPmReviews($id);
return view('overtime::overtime.overtimeclaim.hod.view', compact(
'data', 'details', 'statuses', 'latestKueri', 'queryHistory', 'pendingPmReviews'
));
}
// =========================================================================
// SOKONG — forwards to PD (status 7)
// =========================================================================
public function sokongClaim(Request $request, int $id): JsonResponse
{
return $this->withTransaction(function () use ($request, $id) {
$claim = $this->repos->sokongClaim($request, $id);
return response()->json([
'success' => true,
'message' => "Permohonan {$claim->ocm_apply_no} disokong dan dihantar ke PD.",
'redirect' => route('overtime::overtime.hodreviewlist'),
]);
});
}
// =========================================================================
// KUERI — sends back to pemohon (status 8)
// =========================================================================
public function kueriClaim(Request $request, int $id): JsonResponse
{
$request->validate(
['remarks' => 'required|string|max:2000'],
['remarks.required' => 'Sila isi remarks untuk kueri.']
);
return $this->withTransaction(function () use ($request, $id) {
$claim = $this->repos->kueriClaim($request, $id);
return response()->json([
'success' => true,
'message' => "Permohonan {$claim->ocm_apply_no} dikueri dan dihantar semula kepada pemohon.",
'redirect' => route('overtime::overtime.hodreviewlist'),
]);
});
}
// =========================================================================
// PRIVATE HELPERS
// =========================================================================
private function withTransaction(callable $callback): JsonResponse
{
try {
DB::beginTransaction();
$response = $callback();
DB::commit();
return $response;
} catch (\Exception $e) {
DB::rollBack();
return response()->json([
'success' => false,
'message' => $e->getMessage() ?: 'An error occurred.',
], 500);
}
}
}
<?php
namespace Portal\Overtime\Http\Controllers;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\DB;
use Portal\Overtime\Data\Repo\OvertimeClaimPdRepo;
class OvertimeClaimPdController extends Controller
{
public function __construct(
protected OvertimeClaimPdRepo $repos
) {}
// =========================================================================
// PD REVIEW LIST (status 7, sokong'd by HOD)
// =========================================================================
public function getPdReviewList(Request $request)
{
$list = $this->repos->getPdReviewList($request);
$statuses = $this->repos->getOtStatuses();
return view('overtime::overtime.overtimeclaim.pd.list', compact('list', 'statuses'));
}
// =========================================================================
// PD VIEW — read-only claim render + Sokong/Kueri actions
// =========================================================================
public function viewClaim(Request $request, int $id)
{
$data = $this->repos->findClaim($id);
$details = $this->repos->findClaimDetails($id);
$statuses = $this->repos->getOtStatuses();
$latestKueri = $this->repos->findLatestKueri($id);
$queryHistory = $this->repos->findQueryHistory($id);
return view('overtime::overtime.overtimeclaim.pd.view', compact(
'data', 'details', 'statuses', 'latestKueri', 'queryHistory'
));
}
// =========================================================================
// SOKONG — final approval (status 11)
// =========================================================================
public function sokongClaim(Request $request, int $id): JsonResponse
{
return $this->withTransaction(function () use ($request, $id) {
$claim = $this->repos->sokongClaim($request, $id);
return response()->json([
'success' => true,
'message' => "Permohonan {$claim->ocm_apply_no} telah diluluskan.",
'redirect' => route('overtime::overtime.pdreviewlist'),
]);
});
}
// =========================================================================
// KUERI — sends back to pemohon (status 10)
// =========================================================================
public function kueriClaim(Request $request, int $id): JsonResponse
{
$request->validate(
['remarks' => 'required|string|max:2000'],
['remarks.required' => 'Sila isi remarks untuk kueri.']
);
return $this->withTransaction(function () use ($request, $id) {
$claim = $this->repos->kueriClaim($request, $id);
return response()->json([
'success' => true,
'message' => "Permohonan {$claim->ocm_apply_no} dikueri dan dihantar semula kepada pemohon.",
'redirect' => route('overtime::overtime.pdreviewlist'),
]);
});
}
// =========================================================================
// PRIVATE HELPERS
// =========================================================================
private function withTransaction(callable $callback): JsonResponse
{
try {
DB::beginTransaction();
$response = $callback();
DB::commit();
return $response;
} catch (\Exception $e) {
DB::rollBack();
return response()->json([
'success' => false,
'message' => $e->getMessage() ?: 'An error occurred.',
], 500);
}
}
}
<?php
namespace Portal\Overtime\Http\Controllers;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\DB;
use Portal\Overtime\Data\Repo\OvertimeHodRepo;
class OvertimeHodController extends Controller
{
public function __construct(
protected OvertimeHodRepo $repos
) {}
public function getReviewList(Request $request)
{
$list = $this->repos->getReviewList($request);
$statuses = $this->repos->getOtStatuses();
return view('overtime::overtime.overtimerequest.hod.list', compact('list', 'statuses'));
}
public function viewRequestForm(Request $request, int $id)
{
$main = $this->repos->findRequestForm($id);
$details = $this->repos->findRequestFormDetails($id);
$project = DB::table('lkp_project')->where('id', $main->orm_project)->first();
$statuses = $this->repos->getOtStatuses();
$queryHistory = $this->repos->findQueryHistory($id);
$requestedByName = null;
if ($main->orm_requested_by_id) {
$requestedByName = DB::table('project_team')->where('id', $main->orm_requested_by_id)->value('pt_team');
}
if (!$requestedByName && $main->orm_name && is_numeric((string) $main->orm_name)) {
$requestedByName = DB::table('staff_info')->where('fk_users', (int) $main->orm_name)->value('fullname')
?: DB::table('users')->where('id', (int) $main->orm_name)->value('name')
?: (string) $main->orm_name;
} elseif (!$requestedByName && $main->orm_name) {
$requestedByName = (string) $main->orm_name;
}
$main->orm_requested_by_name = $requestedByName ?: '-';
$staffInfoForMain = $main->orm_name && is_numeric((string) $main->orm_name)
? DB::table('staff_info')->where('fk_users', (int) $main->orm_name)->first()
: null;
$main->orm_position_label = $main->orm_position
? (DB::table('project_role')->where('id', $main->orm_position)->value('role') ?: (string) $main->orm_position)
: '-';
$main->orm_department_label = $staffInfoForMain && $staffInfoForMain->fk_lkp_department
? (DB::table('lkp_department')->where('id', $staffInfoForMain->fk_lkp_department)->value('description') ?: DB::table('lkp_department')->where('id', $staffInfoForMain->fk_lkp_department)->value('name') ?: '-')
: (DB::table('lkp_department')->where('id', $main->orm_department)->value('description') ?: DB::table('lkp_department')->where('id', $main->orm_department)->value('name') ?: '-');
$main->orm_approved_by_name = $main->orm_approved_by_id
? (DB::table('staff_info')->where('fk_users', $main->orm_approved_by_id)->value('fullname')
?: DB::table('users')->where('id', $main->orm_approved_by_id)->value('name')
?: '-')
: '-';
return view('overtime::overtime.overtimerequest.hod.view', compact('main', 'details', 'project', 'statuses', 'queryHistory'));
}
public function approveRequestForm(Request $request, int $id): JsonResponse
{
return $this->withTransaction(function () use ($id) {
$this->repos->approveRequestForm($id);
return response()->json([
'success' => true,
'message' => 'Borang permohonan disokong dan dihantar ke Project Director.',
'redirect' => route('overtime::overtime.hodreviewlist'),
]);
});
}
public function rejectRequestForm(Request $request, int $id): JsonResponse
{
return $this->withTransaction(function () use ($id) {
$this->repos->rejectRequestForm($id);
return response()->json([
'success' => true,
'message' => 'Borang permohonan ditolak.',
'redirect' => route('overtime::overtime.hodreviewlist'),
]);
});
}
private function withTransaction(callable $callback): JsonResponse
{
try {
DB::beginTransaction();
$response = $callback();
DB::commit();
return $response;
} catch (\Exception $e) {
DB::rollBack();
return response()->json(['success' => false, 'message' => $e->getMessage() ?: 'An error occurred.'], 500);
}
}
public function kueriRequestForm(Request $request, int $id): JsonResponse
{
$request->validate([
'remark' => 'required|string|max:2000',
], [
'remark.required' => 'Sila isi catatan kueri.',
]);
return $this->withTransaction(function () use ($request, $id) {
$this->repos->kueriRequestForm($id, $request->remark);
return response()->json([
'success' => true,
'message' => 'Borang permohonan dikueri dan dihantar balik kepada PM.',
'redirect' => route('overtime::overtime.hodreviewlist'),
]);
});
}
}
<?php
namespace Portal\Overtime\Http\Controllers;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\DB;
use Portal\Overtime\Data\Repo\OvertimePdRepo;
class OvertimePdController extends Controller
{
public function __construct(
protected OvertimePdRepo $repos
) {}
public function getReviewList(Request $request)
{
$list = $this->repos->getReviewList($request);
$statuses = $this->repos->getOtStatuses();
return view('overtime::overtime.overtimerequest.pd.list', compact('list', 'statuses'));
}
public function getClaimReviewList(Request $request)
{
$list = $this->repos->getReviewList($request);
$statuses = $this->repos->getOtStatuses();
return view('overtime::overtime.overtimerequest.pd.list', compact('list', 'statuses'));
}
public function viewRequestForm(Request $request, int $id)
{
$main = $this->repos->findRequestForm($id);
$details = $this->repos->findRequestFormDetails($id);
$project = DB::table('lkp_project')->where('id', $main->orm_project)->first();
$statuses = $this->repos->getOtStatuses();
$queryHistory = $this->repos->findQueryHistory($id);
$requestedByName = null;
if ($main->orm_requested_by_id) {
$requestedByName = DB::table('project_team')->where('id', $main->orm_requested_by_id)->value('pt_team');
}
if (!$requestedByName && $main->orm_name && is_numeric((string) $main->orm_name)) {
$requestedByName = DB::table('staff_info')->where('fk_users', (int) $main->orm_name)->value('fullname')
?: DB::table('users')->where('id', (int) $main->orm_name)->value('name')
?: (string) $main->orm_name;
} elseif (!$requestedByName && $main->orm_name) {
$requestedByName = (string) $main->orm_name;
}
$main->orm_requested_by_name = $requestedByName ?: '-';
$staffInfoForMain = $main->orm_name && is_numeric((string) $main->orm_name)
? DB::table('staff_info')->where('fk_users', (int) $main->orm_name)->first()
: null;
$main->orm_position_label = $main->orm_position
? (DB::table('project_role')->where('id', $main->orm_position)->value('role') ?: (string) $main->orm_position)
: '-';
$main->orm_department_label = $staffInfoForMain && $staffInfoForMain->fk_lkp_department
? (DB::table('lkp_department')->where('id', $staffInfoForMain->fk_lkp_department)->value('description') ?: DB::table('lkp_department')->where('id', $staffInfoForMain->fk_lkp_department)->value('name') ?: '-')
: (DB::table('lkp_department')->where('id', $main->orm_department)->value('description') ?: DB::table('lkp_department')->where('id', $main->orm_department)->value('name') ?: '-');
$main->orm_approved_by_name = $main->orm_approved_by_id
? (DB::table('staff_info')->where('fk_users', $main->orm_approved_by_id)->value('fullname')
?: DB::table('users')->where('id', $main->orm_approved_by_id)->value('name')
?: '-')
: '-';
return view('overtime::overtime.overtimerequest.pd.view', compact('main', 'details', 'project', 'statuses', 'queryHistory'));
}
public function approveRequestForm(Request $request, int $id): JsonResponse
{
return $this->withTransaction(function () use ($id) {
$this->repos->approveRequestForm($id);
return response()->json([
'success' => true,
'message' => 'Borang permohonan diluluskan.',
'redirect' => route('overtime::overtime.pdreviewlist'),
]);
});
}
public function rejectRequestForm(Request $request, int $id): JsonResponse
{
return $this->withTransaction(function () use ($id) {
$this->repos->rejectRequestForm($id);
return response()->json([
'success' => true,
'message' => 'Borang permohonan ditolak.',
'redirect' => route('overtime::overtime.pdreviewlist'),
]);
});
}
private function withTransaction(callable $callback): JsonResponse
{
try {
DB::beginTransaction();
$response = $callback();
DB::commit();
return $response;
} catch (\Exception $e) {
DB::rollBack();
return response()->json(['success' => false, 'message' => $e->getMessage() ?: 'An error occurred.'], 500);
}
}
public function kueriRequestForm(Request $request, int $id): JsonResponse
{
$request->validate([
'remark' => 'required|string|max:2000',
], [
'remark.required' => 'Sila isi catatan kueri.',
]);
return $this->withTransaction(function () use ($request, $id) {
$this->repos->kueriRequestForm($id, $request->remark);
return response()->json([
'success' => true,
'message' => 'Borang permohonan dikueri dan dihantar balik kepada PM.',
'redirect' => route('overtime::overtime.pdreviewlist'),
]);
});
}
}
<?php
namespace Portal\Overtime\Http\Controllers;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\DB;
use Portal\Overtime\Data\Repo\OvertimeProjectManagerRepo;
class OvertimeProjectManagerController extends Controller
{
public function __construct(
protected OvertimeProjectManagerRepo $repos
) {}
// =========================================================================
// LIST (status 2 + 3)
// =========================================================================
public function getProjectManagerReviewList(Request $request)
{
$list = $this->repos->getProjectManagerReviewList($request);
$statuses = $this->repos->getOtStatuses();
$pmProjectIds = $this->repos->getPmProjectIds();
return view('overtime::overtime.overtimeclaim.projectmanager.list', compact('list', 'statuses', 'pmProjectIds'));
}
// =========================================================================
// VIEW (full read-only claim + sokong/kueri actions)
// =========================================================================
public function viewClaim(Request $request, int $id)
{
$data = $this->repos->findClaimWithDetails($id);
$statuses = $this->repos->getOtStatuses();
$selectionData = $this->repos->getRequestFormSelectionData($data['main']);
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'],
]);
}
// =========================================================================
// VIEW A REQUEST FORM (modal content, for picker preview)
// =========================================================================
public function viewRequestForm(Request $request, int $id)
{
$data = $this->repos->findRequestForm($id);
$view = view('overtime::overtime.overtimeclaim.projectmanager.request_form_view', [
'main' => $data['main'],
'details' => $data['details'],
]);
if ($request->ajax()) {
return response($view->render());
}
return $view;
}
// =========================================================================
// SOKONG
// =========================================================================
public function markReviewed(Request $request, int $id): JsonResponse
{
$request->validate([
'request_form_id' => 'required|integer|exists:overtime_request_main,id',
], [
'request_form_id.required' => 'Sila pilih borang permohonan berkaitan.',
]);
return $this->withTransaction(function () use ($request, $id) {
$this->repos->markClaimReviewed($id, $request->request_form_id);
return response()->json([
'success' => true,
'message' => 'Baris tuntutan projek telah ditandakan sebagai disemak.',
'redirect' => route('overtime::overtime.projectmanager.list'),
]);
});
}
public function sokongClaim(Request $request, int $id): JsonResponse
{
$request->validate([
'request_form_id' => 'required|integer|exists:overtime_request_main,id',
], [
'request_form_id.required' => 'Sila pilih borang permohonan berkaitan.',
]);
return $this->withTransaction(function () use ($request, $id) {
$this->repos->sokongClaim($id, $request->request_form_id);
return response()->json([
'success' => true,
'message' => 'Permohonan disokong dan dihantar ke HOD.',
'redirect' => route('overtime::overtime.projectmanager.list'),
]);
});
}
// =========================================================================
// KUERI
// =========================================================================
public function kueriClaim(Request $request, int $id): JsonResponse
{
$request->validate([
'remarks' => 'required|string|max:2000',
], [
'remarks.required' => 'Sila isi catatan kueri.',
]);
return $this->withTransaction(function () use ($request, $id) {
$this->repos->kueriClaim($id, $request->remarks);
return response()->json([
'success' => true,
'message' => 'Permohonan dikueri dan dihantar balik kepada pemohon.',
'redirect' => route('overtime::overtime.projectmanager.list'),
]);
});
}
// =========================================================================
// PRIVATE HELPERS
// =========================================================================
private function withTransaction(callable $callback): JsonResponse
{
try {
DB::beginTransaction();
$response = $callback();
DB::commit();
return $response;
} catch (\Exception $e) {
DB::rollBack();
return response()->json([
'success' => false,
'message' => $e->getMessage() ?: 'An error occurred.',
], 500);
}
}
}
......@@ -2,50 +2,330 @@
namespace Portal\Overtime\Http\Controllers;
use Illuminate\Routing\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Carbon\Carbon;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\DB;
use Portal\Overtime\Data\Repo\OvertimeRequestRepo;
use Auth;
use DB;
use Event;
use File;
use Mail;
use PDF;
use Redirect;
use Curl;
class OvertimeRequestController extends Controller
{
public function __construct(
protected OvertimeRequestRepo $repos
) {}
use Portal\Overtime\Data\Repo\OvertimeRepo;
// =========================================================================
// LIST
// =========================================================================
class OvertimeController extends Controller
public function getListOvertimeRequest(Request $request)
{
public function __construct(OvertimeRepo $repos)
$list = $this->repos->getRequestFormList($request);
$existingRequests = $this->repos->getExistingProjectMonthsForUser();
$projects = $this->repos->getProjectsForCurrentPm();
$statuses = $this->repos->getOtStatuses();
return view('overtime::overtime.overtimerequest.pm.list', compact('list', 'existingRequests', 'projects', 'statuses'));
}
// =========================================================================
// CREATE MODAL
// =========================================================================
public function createOvertimeRequest()
{
$projects = $this->repos->getProjectsForCurrentPm();
$existingRequests = $this->repos->getExistingProjectMonthsForUser();
return view('overtime::overtime.overtimerequest.pm.create', compact('projects', 'existingRequests'));
}
public function getExistingProjects(): JsonResponse
{
return response()->json([
'success' => true,
'existingRequests' => $this->repos->getExistingProjectMonthsForUser(),
]);
}
public function storeOvertimeRequest(Request $request): JsonResponse
{
$request->validate([
'orm_project' => 'required|integer',
'orm_date' => 'required|date',
], [
'orm_project.required' => 'Sila pilih projek.',
'orm_date.required' => 'Sila pilih bulan permohonan OT.',
]);
$requestKey = sprintf('%s|%s', (string) $request->orm_project, \Carbon\Carbon::parse($request->orm_date)->format('Ym'));
$existing = $this->repos->getExistingProjectMonthsForUser();
if (in_array($requestKey, $existing)) {
return response()->json([
'success' => false,
'message' => 'Borang permohonan untuk projek dan bulan ini sudah wujud.',
], 422);
}
return $this->withTransaction(function () use ($request) {
$record = $this->repos->storeRequestForm($request);
return response()->json([
'success' => true,
'message' => 'Borang permohonan berjaya dicipta.',
'redirect' => route('overtime::overtime.editovertimerequest', $record->id),
]);
});
}
// =========================================================================
// EDIT
// =========================================================================
public function editOvertimeRequest(Request $request, int $id)
{
$data = $this->repos->findRequestForm($id);
$details = $this->repos->findRequestFormDetails($id);
$project = DB::table('lkp_project')->where('id', $data->orm_project)->first();
$staffOptions = $this->repos->getProjectStaffOptions((int) $data->orm_project);
$statuses = $this->repos->getOtStatuses();
$queryHistory = $this->repos->findQueryHistory($id);
$data->orm_requested_by_name = $data->orm_requested_by_id
? (DB::table('project_team')->where('id', $data->orm_requested_by_id)->value('pt_team')
?: ($this->repos->resolveApplicantName($data->orm_name) ?: '-'))
: ($this->repos->resolveApplicantName($data->orm_name) ?: '-');
$staffInfoForData = $data->orm_name && is_numeric((string) $data->orm_name)
? DB::table('staff_info')->where('fk_users', (int) $data->orm_name)->first()
: null;
$data->orm_position_label = $data->orm_position
? (DB::table('project_role')->where('id', $data->orm_position)->value('role') ?: (string) $data->orm_position)
: '-';
$data->orm_department_label = $staffInfoForData && $staffInfoForData->fk_lkp_department
? (DB::table('lkp_department')->where('id', $staffInfoForData->fk_lkp_department)->value('description') ?: DB::table('lkp_department')->where('id', $staffInfoForData->fk_lkp_department)->value('name') ?: '-')
: (DB::table('lkp_department')->where('id', $data->orm_department)->value('description') ?: DB::table('lkp_department')->where('id', $data->orm_department)->value('name') ?: '-');
$data->orm_approved_by_name = $data->orm_approved_by_id
? (DB::table('staff_info')->where('fk_users', $data->orm_approved_by_id)->value('fullname')
?: DB::table('users')->where('id', $data->orm_approved_by_id)->value('name')
?: '-')
: '-';
return view('overtime::overtime.overtimerequest.pm.edit', compact('data', 'details', 'project', 'staffOptions', 'statuses', 'queryHistory'));
}
public function updateOvertimeRequest(Request $request, int $id): JsonResponse
{
return $this->withTransaction(function () use ($request, $id) {
$this->repos->updateRequestForm($request, $id);
return response()->json([
'success' => true,
'message' => 'Borang permohonan berjaya dikemaskini.',
]);
});
}
// =========================================================================
// ADD DETAIL
// =========================================================================
public function addOvertimeRequestDetail(Request $request, int $id): JsonResponse
{
$request->validate([
'ord_name' => 'required|string',
'ord_month_of_overtime' => 'required|date',
'ord_planned_ot_hour' => 'required|numeric|min:0',
'ord_reason' => 'required|string|max:2000',
'ord_total_hours' => 'required|numeric|min:0',
], [
'ord_name.required' => 'Nama diperlukan.',
'ord_month_of_overtime.required' => 'Bulan overtime diperlukan.',
'ord_planned_ot_hour.required' => 'Planned OT hour diperlukan.',
'ord_reason.required' => 'Sila isi sebab.',
'ord_total_hours.required' => 'Jumlah jam diperlukan.',
]);
if (!$this->repos->isStaffNameInRequestProject($id, $request->ord_name)) {
return response()->json([
'success' => false,
'message' => 'Nama staf mesti dipilih daripada senarai staf projek ini.',
], 422);
}
return $this->withTransaction(function () use ($request, $id) {
$detail = $this->repos->addRequestFormDetail($id, $request);
return response()->json([
'success' => true,
'message' => 'Entri berjaya ditambah.',
'detail' => $detail,
]);
});
}
public function updateOvertimeRequestDetail(Request $request, int $id): JsonResponse
{
$request->validate([
'ord_name' => 'required|string',
'ord_month_of_overtime' => 'required|date',
'ord_planned_ot_hour' => 'required|numeric|min:0',
'ord_reason' => 'required|string|max:2000',
'ord_total_hours' => 'required|numeric|min:0',
]);
return $this->withTransaction(function () use ($request, $id) {
$detail = $this->repos->updateRequestFormDetail($id, $request);
return response()->json([
'success' => true,
'message' => 'Entri berjaya dikemaskini.',
'detail' => $detail,
]);
});
}
// =========================================================================
// REMOVE DETAIL
// =========================================================================
public function removeOvertimeRequestDetail(Request $request, int $id): JsonResponse
{
$this->repos = $repos;
return $this->withTransaction(function () use ($id) {
$this->repos->removeRequestFormDetail($id);
return response()->json([
'success' => true,
'message' => 'Entri berjaya dibuang.',
]);
});
}
/**
* undocumented function
*
* @return testing please hide this function and continue below
* @author afif@3fresources.com
**/
public function index(Request $request)
// =========================================================================
// BATAL
// =========================================================================
public function batalOvertimeRequest(Request $request, int $id): JsonResponse
{
dd('Welcome to index E-OT 3FRSB');exit;
// $list = $this->repos->index($request);
return $this->withTransaction(function () use ($id) {
$this->repos->batalRequestForm($id);
// return view('overtime::list', compact('list'));
return response()->json([
'success' => true,
'message' => 'Borang permohonan berjaya dibatalkan.',
]);
});
}
// overtime crud start
public function getListOvertime(Request $request)
// =========================================================================
// DELETE (hard, kept for admin/dev use — not exposed in UI by default)
// =========================================================================
public function deleteOvertimeRequest(Request $request, int $id): JsonResponse
{
$list = $this->repos->overtimeList($request);
return $this->withTransaction(function () use ($id) {
$this->repos->deleteRequestForm($id);
return view('overtime::overtime.list', compact('list'));
return response()->json([
'success' => true,
'message' => 'Borang permohonan berjaya dipadam.',
]);
});
}
// overtime crud end
// =========================================================================
// VIEW (JSON for modal preview)
// =========================================================================
public function viewOvertimeRequest(Request $request, int $id): JsonResponse
{
$main = $this->repos->findRequestForm($id);
$details = $this->repos->findRequestFormDetails($id);
$status = DB::table('lkp_status')
->where('module', 'ot')
->where('ref_id', $main->orm_status)
->first();
$main->orm_status_label = $status->description ?? ($main->orm_status == 0 ? '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) ?: '-'))
: ($this->repos->resolveApplicantName($main->orm_name) ?: '-');
$staffInfoForMain = $main->orm_name && is_numeric((string) $main->orm_name)
? DB::table('staff_info')->where('fk_users', (int) $main->orm_name)->first()
: null;
$main->orm_position_label = $main->orm_position
? (DB::table('project_role')->where('id', $main->orm_position)->value('role') ?: (string) $main->orm_position)
: '-';
$main->orm_project_label = DB::table('lkp_project')->where('id', $main->orm_project)->value('p_project_description') ?: '-';
$main->orm_department_label = $staffInfoForMain && $staffInfoForMain->fk_lkp_department
? (DB::table('lkp_department')->where('id', $staffInfoForMain->fk_lkp_department)->value('description') ?: DB::table('lkp_department')->where('id', $staffInfoForMain->fk_lkp_department)->value('name') ?: '-')
: (DB::table('lkp_department')->where('id', $main->orm_department)->value('description') ?: DB::table('lkp_department')->where('id', $main->orm_department)->value('name') ?: '-');
$main->orm_approved_by_name = $main->orm_approved_by_id
? (DB::table('staff_info')->where('fk_users', $main->orm_approved_by_id)->value('fullname')
?: DB::table('users')->where('id', $main->orm_approved_by_id)->value('name')
?: '-')
: '-';
return response()->json([
'success' => true,
'data' => [
'main' => $main,
'details' => $details,
],
]);
}
// =========================================================================
// PRIVATE HELPERS
// =========================================================================
private function withTransaction(callable $callback): JsonResponse
{
try {
DB::beginTransaction();
$response = $callback();
DB::commit();
return $response;
} catch (\Exception $e) {
DB::rollBack();
return response()->json([
'success' => false,
'message' => $e->getMessage() ?: 'An error occurred.',
], 500);
}
}
public function submitOvertimeRequest(Request $request, int $id): JsonResponse
{
return $this->withTransaction(function () use ($id) {
$this->repos->submitRequestForm($id);
return response()->json([
'success' => true,
'message' => 'Borang permohonan berjaya dihantar untuk semakan HOD.',
'redirect' => route('overtime::overtime.listovertimerequest'),
]);
});
}
public function saveKueriRespond(Request $request, int $id): JsonResponse
{
$request->validate([
'respond' => 'required|string|max:2000',
], [
'respond.required' => 'Sila isi respond.',
]);
return $this->withTransaction(function () use ($request, $id) {
$this->repos->saveKueriRespond($id, $request->respond);
return response()->json([
'success' => true,
'message' => 'Respond berjaya disimpan.',
]);
});
}
}
<?php
namespace Portal\Overtime\Model;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class LkpStatus extends Model
{
use SoftDeletes;
protected $table = 'lkp_status';
protected $guarded = ['id'];
}
\ No newline at end of file
<?php
namespace Portal\Overtime\Model;
use Illuminate\Database\Eloquent\Model;
class OvertimeAuditQuery extends Model
{
protected $table = 'overtime_audit_query';
protected $guarded = ['id'];
protected $casts = [
'tarikh' => 'datetime',
];
public function claim()
{
return $this->belongsTo(OvertimeClaimMain::class, 'fk_main');
}
public function queriedBy()
{
return $this->belongsTo(\App\Models\User::class, 'fk_user_kueri');
}
}
\ No newline at end of file
......@@ -17,6 +17,8 @@ class OvertimeClaimDetail extends Model
'ocd_date' => 'date',
'ocd_effective_hours' => 'decimal:2',
'ocd_total_hours' => 'decimal:2',
'ocd_pm_reviewed' => 'boolean',
'ocd_pm_reviewed_at' => 'datetime',
'deleted_at' => 'datetime',
];
}
\ No newline at end of file
......@@ -16,9 +16,24 @@ class OvertimeClaimMain extends Model
protected $casts = [
'ocm_month' => 'integer',
'ocm_year' => 'integer',
'ocm_query_status' => 'integer',
'ocm_verified_date' => 'datetime',
'ocm_approved_date' => 'datetime',
'ocm_submit_date' => 'datetime',
'deleted_at' => 'datetime',
];
public function auditQueries()
{
return $this->hasMany(OvertimeAuditQuery::class, 'fk_main')->orderBy('created_at', 'desc');
}
public function latestAuditQuery()
{
return $this->hasOne(OvertimeAuditQuery::class, 'fk_main')->latestOfMany();
}
public function details()
{
return $this->hasMany(OvertimeClaimDetail::class, 'fk_overtime_claim_main');
}
}
\ No newline at end of file
......@@ -3,23 +3,24 @@
namespace Portal\Overtime\Model;
use Illuminate\Database\Eloquent\Model;
// use Illuminate\Database\Eloquent\SoftDeletes;
class OvertimeRequestDetail extends Model
{
// use SoftDeletes;
protected $table = 'overtime_request_detail';
protected $primaryKey = 'id';
protected $guarded = ['id'];
protected $casts = [
'ord_month_of_overtime' => 'date', // ← was 'datetime', caused ISO timestamp in JSON
'deleted_at' => 'datetime',
'ord_month_of_overtime' => 'date',
'ord_budgeted' => 'decimal:2',
'ord_utilised_to_date' => 'decimal:2',
'ord_planned_ot_hour' => 'decimal:2',
'ord_balance' => 'decimal:2',
'ord_total_hours' => 'decimal:2',
];
public function main()
{
return $this->belongsTo(OvertimeRequestMain::class, 'fk_overtime_request_main');
}
}
\ No newline at end of file
......@@ -3,12 +3,9 @@
namespace Portal\Overtime\Model;
use Illuminate\Database\Eloquent\Model;
// use Illuminate\Database\Eloquent\SoftDeletes;
class OvertimeRequestMain extends Model
{
// use SoftDeletes;
protected $table = 'overtime_request_main';
protected $primaryKey = 'id';
protected $guarded = ['id'];
......@@ -19,4 +16,16 @@ class OvertimeRequestMain extends Model
'orm_approved_date' => 'datetime',
'deleted_at' => 'datetime',
];
public function details()
{
return $this->hasMany(OvertimeRequestDetail::class, 'fk_overtime_request_main');
}
public function auditQueries()
{
return $this->hasMany(OvertimeAuditQuery::class, 'fk_main')
->where('no_permohonan', $this->orm_apply_no)
->orderBy('created_at', 'desc');
}
}
......@@ -87,6 +87,44 @@ protected function menu()
// ->active('overtime/*');
// ->data('permission', Permission::PROJECT_MANAGER);
$menu = $menus->add(__('Tuntutan Lebih Masa'))->data('icon', 'align justify');
$menu = $menus->add(__('OT REQUEST'))->data('icon', 'align justify');
$menu->add(__('List of Request Forms (PM)'), url('/overtime/request/list'))
->data('icon', 'file alternate')
->active('overtime/request/*')
->data('permission', Permission::REQUEST_OT);
$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);
$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);
$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);
$menu->add(__('Review Claim Forms (PM)'), url('/overtime/projectmanager/list'))
->data('icon', 'check')
->active('overtime/*')
->data('permission', Permission::APPLICATION_OT_REVIEW);
$menu->add(__('Support Claim Forms (HOD)'), url('/overtime/claim/hod/list'))
->data('icon', 'check circle')
->active('overtime/*')
->data('permission', Permission::APPLICATION_OT_SUPPORT);
$menu->add(__('Approve Claim Forms (PD)'), url('/overtime/claim/pd/list'))
->data('icon', 'check circle outline')
->active('overtime/*')
->data('permission', Permission::APPLICATION_OT_APPROVE);
});
}
......
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