Compare commits
8 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 1a7dead730 | |||
| 7cd6976114 | |||
| a627afb6c5 | |||
| 3ff62ccec6 | |||
| bd75a0ed03 | |||
| 5047f32118 | |||
| 337be0f332 | |||
| b0475e3371 |
@@ -5,6 +5,8 @@
|
||||
/docker-images
|
||||
/.vscode
|
||||
.env
|
||||
.env.*
|
||||
.gitea
|
||||
NOTE.md
|
||||
/node_modules
|
||||
/vendor
|
||||
|
||||
+1
-11
@@ -104,14 +104,4 @@ ONEWAYSMS_API_USERNAME=
|
||||
ONEWAYSMS_API_PASSWORD=
|
||||
ONEWAYSMS_SENDER_ID=
|
||||
|
||||
EXTERNAL_SYSTEM_SSO_ISSUER=mykopkb
|
||||
|
||||
# Billplz (Investment module) — use sandbox credentials locally
|
||||
BILLPLZ_API_KEY=
|
||||
BILLPLZ_X_SIGNATURE_KEY=
|
||||
BILLPLZ_COLLECTION_ID=
|
||||
BILLPLZ_BASE_URL=https://www.billplz-sandbox.com/api/v3
|
||||
# Optional overrides; defaults: {APP_URL}/v1/billplz/callback
|
||||
BILLPLZ_CALLBACK_URL=
|
||||
# Frontend return URL, investment_id query is appended automatically
|
||||
BILLPLZ_REDIRECT_URL=
|
||||
EXTERNAL_SYSTEM_SSO_ISSUER=mykopkb
|
||||
@@ -0,0 +1,42 @@
|
||||
name: Build Docker Image
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- "v*"
|
||||
|
||||
jobs:
|
||||
build-backend:
|
||||
runs-on: docker
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Login to Docker registry
|
||||
run: |
|
||||
echo "${{ secrets.REGISTRY_PASSWORD }}" | \
|
||||
docker login git.koppkb.com \
|
||||
-u "${{ secrets.REGISTRY_USERNAME }}" \
|
||||
--password-stdin
|
||||
|
||||
- name: Build & push backend image
|
||||
run: |
|
||||
set -e
|
||||
|
||||
IMAGE="git.koppkb.com/kopkb/my-kopkb-be"
|
||||
TAGS="-t ${IMAGE}:${{ gitea.sha }}"
|
||||
|
||||
if [ "${{ gitea.ref_type }}" = "tag" ] && echo "${{ gitea.ref_name }}" | grep -q '^v'; then
|
||||
TAGS="${TAGS} -t ${IMAGE}:${{ gitea.ref_name }}"
|
||||
fi
|
||||
|
||||
echo "Building and pushing backend: ${TAGS}"
|
||||
docker buildx build \
|
||||
--target production \
|
||||
--platform linux/amd64 \
|
||||
--cache-from type=registry,ref=${IMAGE}:buildcache,ignore-error=true \
|
||||
--cache-to type=registry,ref=${IMAGE}:buildcache,mode=max \
|
||||
-f docker/common/unified/Dockerfile \
|
||||
${TAGS} \
|
||||
--push .
|
||||
@@ -0,0 +1,84 @@
|
||||
name: Deploy Production Data Services
|
||||
|
||||
# Manual deploy for Postgres and Redis. A backend release does not run this.
|
||||
on:
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
runs-on: mykopkb-production
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Deploy data services over SSH
|
||||
env:
|
||||
PROD_HOST: ${{ secrets.PROD_HOST }}
|
||||
PROD_USER: ${{ secrets.PROD_USER }}
|
||||
PROD_SSH_KEY: ${{ secrets.PROD_SSH_KEY }}
|
||||
PROD_DEPLOY_DIR: ${{ secrets.PROD_DEPLOY_DIR }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
if [ ! -f .env.production ]; then
|
||||
echo "ERROR: .env.production is missing from the repository checkout"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if ! command -v ssh >/dev/null 2>&1; then
|
||||
apt-get update && apt-get install -y openssh-client
|
||||
fi
|
||||
|
||||
mkdir -p ~/.ssh
|
||||
umask 077
|
||||
if printf '%s' "$PROD_SSH_KEY" | grep -q -- '-----BEGIN'; then
|
||||
printf '%b\n' "$PROD_SSH_KEY" | tr -d '\r' > ~/.ssh/id_ed25519
|
||||
else
|
||||
printf '%s' "$PROD_SSH_KEY" | tr -d '[:space:]' | base64 -d > ~/.ssh/id_ed25519
|
||||
fi
|
||||
chmod 600 ~/.ssh/id_ed25519
|
||||
if ! ssh-keygen -y -f ~/.ssh/id_ed25519 >/dev/null; then
|
||||
echo "ERROR: PROD_SSH_KEY is not a readable private key."
|
||||
exit 1
|
||||
fi
|
||||
ssh-keyscan -H "$PROD_HOST" >> ~/.ssh/known_hosts
|
||||
|
||||
SSH=(ssh -i ~/.ssh/id_ed25519 -o IdentitiesOnly=yes "${PROD_USER}@${PROD_HOST}")
|
||||
|
||||
"${SSH[@]}" "bash -s" << EOF
|
||||
set -euo pipefail
|
||||
for name in mykopkb-postgres-production mykopkb-redis-production; do
|
||||
if docker inspect "\$name" >/dev/null 2>&1; then
|
||||
project=\$(docker inspect -f '{{index .Config.Labels "com.docker.compose.project"}}' "\$name" 2>/dev/null || true)
|
||||
if [ "\$project" != "mykopkb-data" ]; then
|
||||
echo "ERROR: \$name is already running under compose project '\${project:-unknown}'."
|
||||
echo "This workflow does not replace the existing database or Redis containers."
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
done
|
||||
EOF
|
||||
|
||||
"${SSH[@]}" "mkdir -p '${PROD_DEPLOY_DIR}/redis-config' '${PROD_DEPLOY_DIR}/docker/postgres/conf.d'"
|
||||
scp -i ~/.ssh/id_ed25519 -o IdentitiesOnly=yes \
|
||||
docker/production/docker-compose.data.yml \
|
||||
"${PROD_USER}@${PROD_HOST}:${PROD_DEPLOY_DIR}/docker-compose.data.yml"
|
||||
scp -i ~/.ssh/id_ed25519 -o IdentitiesOnly=yes \
|
||||
.env.production \
|
||||
"${PROD_USER}@${PROD_HOST}:${PROD_DEPLOY_DIR}/.env"
|
||||
scp -i ~/.ssh/id_ed25519 -o IdentitiesOnly=yes \
|
||||
docker/production/redis/redis.conf \
|
||||
"${PROD_USER}@${PROD_HOST}:${PROD_DEPLOY_DIR}/redis-config/redis.conf"
|
||||
|
||||
"${SSH[@]}" "bash -s" << EOF
|
||||
set -euo pipefail
|
||||
chmod 600 "${PROD_DEPLOY_DIR}/.env"
|
||||
|
||||
docker network inspect mykopkb-production-network >/dev/null 2>&1 \
|
||||
|| docker network create mykopkb-production-network
|
||||
|
||||
cd "${PROD_DEPLOY_DIR}"
|
||||
docker compose -p mykopkb-data -f docker-compose.data.yml up -d
|
||||
docker compose -p mykopkb-data -f docker-compose.data.yml ps
|
||||
EOF
|
||||
@@ -0,0 +1,155 @@
|
||||
name: Deploy to Production
|
||||
|
||||
# Manual production deploy — pulls pre-built images from the registry
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
image_tag:
|
||||
description: "Docker image tag to deploy (commit SHA or version tag, e.g. v1.0.0)"
|
||||
required: true
|
||||
default: "latest"
|
||||
type: string
|
||||
|
||||
env:
|
||||
BACKEND_IMAGE: git.koppkb.com/kopkb/my-kopkb-be
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
runs-on: mykopkb-production
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ inputs.image_tag }}
|
||||
|
||||
- name: Verify image exists in registry
|
||||
run: |
|
||||
set -e
|
||||
echo "${{ secrets.REGISTRY_PASSWORD }}" | \
|
||||
docker login git.koppkb.com \
|
||||
-u "${{ secrets.REGISTRY_USERNAME }}" \
|
||||
--password-stdin
|
||||
|
||||
IMAGE="${BACKEND_IMAGE}:${{ inputs.image_tag }}"
|
||||
echo "Checking if image exists: ${IMAGE}"
|
||||
docker manifest inspect "${IMAGE}" > /dev/null
|
||||
echo "✓ ${IMAGE} found"
|
||||
|
||||
- name: Deploy over SSH
|
||||
env:
|
||||
PROD_HOST: ${{ secrets.PROD_HOST }}
|
||||
PROD_USER: ${{ secrets.PROD_USER }}
|
||||
PROD_SSH_KEY: ${{ secrets.PROD_SSH_KEY }}
|
||||
PROD_DEPLOY_DIR: ${{ secrets.PROD_DEPLOY_DIR }}
|
||||
REGISTRY_USERNAME: ${{ secrets.REGISTRY_USERNAME }}
|
||||
REGISTRY_PASSWORD: ${{ secrets.REGISTRY_PASSWORD }}
|
||||
IMAGE_TAG: ${{ inputs.image_tag }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
if [ ! -f .env.production ]; then
|
||||
echo "ERROR: .env.production is missing from the repository checkout"
|
||||
exit 1
|
||||
fi
|
||||
if [ ! -f docker/production/nginx/nginx.conf ]; then
|
||||
echo "ERROR: docker/production/nginx/nginx.conf is missing from the repository checkout"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if ! command -v ssh >/dev/null 2>&1; then
|
||||
apt-get update && apt-get install -y openssh-client
|
||||
fi
|
||||
|
||||
mkdir -p ~/.ssh
|
||||
umask 077
|
||||
# Gitea often stores a multiline key as one line. Prefer a base64
|
||||
# secret (one line). A raw key that still contains BEGIN is accepted too.
|
||||
if printf '%s' "$PROD_SSH_KEY" | grep -q -- '-----BEGIN'; then
|
||||
printf '%b\n' "$PROD_SSH_KEY" | tr -d '\r' > ~/.ssh/id_ed25519
|
||||
else
|
||||
printf '%s' "$PROD_SSH_KEY" | tr -d '[:space:]' | base64 -d > ~/.ssh/id_ed25519
|
||||
fi
|
||||
chmod 600 ~/.ssh/id_ed25519
|
||||
if ! ssh-keygen -y -f ~/.ssh/id_ed25519 >/dev/null; then
|
||||
echo "ERROR: PROD_SSH_KEY is not a readable private key."
|
||||
echo "On the runner, run: base64 -w0 ~/.ssh/mykopkb_prod"
|
||||
echo "Put that single line in the PROD_SSH_KEY secret."
|
||||
exit 1
|
||||
fi
|
||||
ssh-keyscan -H "$PROD_HOST" >> ~/.ssh/known_hosts
|
||||
|
||||
SSH=(ssh -i ~/.ssh/id_ed25519 -o IdentitiesOnly=yes "${PROD_USER}@${PROD_HOST}")
|
||||
IMAGE="${BACKEND_IMAGE}:${IMAGE_TAG}"
|
||||
NGINX_CONF="${PROD_DEPLOY_DIR}/nginx/nginx.conf"
|
||||
|
||||
"${SSH[@]}" "mkdir -p '${PROD_DEPLOY_DIR}/nginx'"
|
||||
scp -i ~/.ssh/id_ed25519 -o IdentitiesOnly=yes \
|
||||
docker/production/docker-compose.production.yml \
|
||||
"${PROD_USER}@${PROD_HOST}:${PROD_DEPLOY_DIR}/docker-compose.yml"
|
||||
scp -i ~/.ssh/id_ed25519 -o IdentitiesOnly=yes \
|
||||
.env.production \
|
||||
"${PROD_USER}@${PROD_HOST}:${PROD_DEPLOY_DIR}/.env"
|
||||
scp -i ~/.ssh/id_ed25519 -o IdentitiesOnly=yes \
|
||||
docker/production/nginx/nginx.conf \
|
||||
"${PROD_USER}@${PROD_HOST}:${NGINX_CONF}"
|
||||
|
||||
"${SSH[@]}" "bash -s" << EOF
|
||||
set -euo pipefail
|
||||
echo "${REGISTRY_PASSWORD}" | docker login git.koppkb.com \
|
||||
-u "${REGISTRY_USERNAME}" --password-stdin
|
||||
|
||||
echo "Checking if image exists: ${IMAGE}"
|
||||
docker manifest inspect "${IMAGE}" > /dev/null
|
||||
echo "✓ ${IMAGE} found"
|
||||
|
||||
echo "Deploying backend IMAGE=${IMAGE}"
|
||||
chmod 600 "${PROD_DEPLOY_DIR}/.env"
|
||||
|
||||
docker network inspect mykopkb-production-network >/dev/null 2>&1 \
|
||||
|| docker network create mykopkb-production-network
|
||||
|
||||
cd "${PROD_DEPLOY_DIR}"
|
||||
export IMAGE_TAG="${IMAGE_TAG}"
|
||||
export NGINX_CONF="${NGINX_CONF}"
|
||||
|
||||
docker rm -f mykopkb-be-production || true
|
||||
docker compose -f docker-compose.yml pull backend
|
||||
docker compose -f docker-compose.yml up -d backend
|
||||
|
||||
echo "Waiting for the backend to start..."
|
||||
sleep 10
|
||||
|
||||
STATUS=\$(docker compose -f docker-compose.yml ps --status running --format '{{.Name}}' backend || true)
|
||||
if [ -z "\$STATUS" ]; then
|
||||
echo "ERROR: backend is not running"
|
||||
docker compose -f docker-compose.yml ps
|
||||
docker compose -f docker-compose.yml logs --tail=50 backend || true
|
||||
exit 1
|
||||
fi
|
||||
echo "✓ backend is running (\$STATUS)"
|
||||
|
||||
BE_CONTAINER=\$(docker compose -f docker-compose.yml ps -q backend)
|
||||
if docker exec "\$BE_CONTAINER" test -f /var/www/.env; then
|
||||
echo "✓ Backend .env file exists"
|
||||
else
|
||||
echo "WARNING: Backend .env file not found"
|
||||
fi
|
||||
|
||||
API_PORT=\$(grep -E '^API_PORT=' .env 2>/dev/null | cut -d= -f2- | tr -d '"' || true)
|
||||
API_PORT=\${API_PORT:-8080}
|
||||
|
||||
for i in 1 2 3 4 5 6; do
|
||||
if curl -sf "http://127.0.0.1:\${API_PORT}/health" > /dev/null; then
|
||||
echo "✓ backend health check passed (http://127.0.0.1:\${API_PORT}/health)"
|
||||
echo "✓ Deployed backend IMAGE_TAG=${IMAGE_TAG}"
|
||||
exit 0
|
||||
fi
|
||||
echo "Waiting for backend... attempt \${i}/6"
|
||||
sleep 5
|
||||
done
|
||||
|
||||
echo "ERROR: backend health check failed (http://127.0.0.1:\${API_PORT}/health)"
|
||||
docker compose -f docker-compose.yml logs --tail=50 backend || true
|
||||
exit 1
|
||||
EOF
|
||||
@@ -141,6 +141,10 @@ class ActivityServiceProvider extends ServiceProvider
|
||||
*/
|
||||
protected function merge_config_from(string $path, string $key): void
|
||||
{
|
||||
if ($this->app->configurationIsCached()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$existing = config($key, []);
|
||||
$module_config = require $path;
|
||||
|
||||
|
||||
@@ -19,6 +19,8 @@ class ActivityLogController extends Controller
|
||||
{
|
||||
$this->authorize('viewAny', Activity::class);
|
||||
|
||||
// ActivityLogger::logView(new Activity, 'Viewed activity logs');
|
||||
|
||||
$perPage = $request->get('per_page', 10);
|
||||
$perPage = min($perPage, 1000); // Limit max per page to 100
|
||||
$search = trim((string) $request->get('search', ''));
|
||||
|
||||
@@ -116,6 +116,10 @@ class ActivityLogServiceProvider extends ServiceProvider
|
||||
*/
|
||||
protected function merge_config_from(string $path, string $key): void
|
||||
{
|
||||
if ($this->app->configurationIsCached()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$existing = config($key, []);
|
||||
$module_config = require $path;
|
||||
|
||||
|
||||
@@ -11,7 +11,6 @@ use Illuminate\Foundation\Auth\User as Authenticatable;
|
||||
use Illuminate\Notifications\Notifiable;
|
||||
use Illuminate\Support\Str;
|
||||
use Laravel\Sanctum\HasApiTokens;
|
||||
use Spatie\Activitylog\Facades\Activity;
|
||||
use Spatie\Activitylog\LogOptions;
|
||||
use Spatie\Activitylog\Traits\LogsActivity;
|
||||
use Spatie\Permission\Contracts\Permission;
|
||||
@@ -106,24 +105,22 @@ class User extends Authenticatable implements MustVerifyEmail
|
||||
|
||||
public function ensurePublicProfileToken(): string
|
||||
{
|
||||
return Activity::withoutLogs(function () {
|
||||
$expiryDays = self::publicProfileTokenTtlDays();
|
||||
|
||||
if (blank($this->public_profile_token) || $this->isPublicProfileTokenExpired()) {
|
||||
$this->forceFill([
|
||||
'public_profile_token' => Str::random(48),
|
||||
'public_profile_token_expires_at' => now()->addDays($expiryDays),
|
||||
])->save();
|
||||
|
||||
return $this->public_profile_token;
|
||||
}
|
||||
$expiryDays = self::publicProfileTokenTtlDays();
|
||||
|
||||
if (blank($this->public_profile_token) || $this->isPublicProfileTokenExpired()) {
|
||||
$this->forceFill([
|
||||
'public_profile_token' => Str::random(48),
|
||||
'public_profile_token_expires_at' => now()->addDays($expiryDays),
|
||||
])->save();
|
||||
|
||||
return $this->public_profile_token;
|
||||
});
|
||||
}
|
||||
|
||||
$this->forceFill([
|
||||
'public_profile_token_expires_at' => now()->addDays($expiryDays),
|
||||
])->save();
|
||||
|
||||
return $this->public_profile_token;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -192,12 +189,6 @@ class User extends Authenticatable implements MustVerifyEmail
|
||||
{
|
||||
return LogOptions::defaults()
|
||||
->logAll()
|
||||
->logExcept([
|
||||
'public_profile_token',
|
||||
'public_profile_token_expires_at',
|
||||
'remember_token',
|
||||
'updated_at',
|
||||
])
|
||||
->logOnlyDirty()
|
||||
->dontSubmitEmptyLogs()
|
||||
->setDescriptionForEvent(fn (string $eventName) => "User {$this->name} was {$eventName}");
|
||||
|
||||
@@ -38,14 +38,6 @@ class VerifyEmailNotification extends Notification
|
||||
protected function verificationUrl(User $notifiable): string
|
||||
{
|
||||
$expireMinutes = (int) config('auth.verification.expire_minutes', 60);
|
||||
$root = rtrim((string) config('app.url'), '/');
|
||||
|
||||
// Prefer APP_URL over the current request host so queued/local proxy
|
||||
// contexts do not embed http://localhost in production emails.
|
||||
URL::forceRootUrl($root);
|
||||
if ($scheme = parse_url($root, PHP_URL_SCHEME)) {
|
||||
URL::forceScheme($scheme);
|
||||
}
|
||||
|
||||
return URL::temporarySignedRoute(
|
||||
'verification.verify',
|
||||
|
||||
@@ -127,6 +127,10 @@ class AuthServiceProvider extends ServiceProvider
|
||||
*/
|
||||
protected function merge_config_from(string $path, string $key): void
|
||||
{
|
||||
if ($this->app->configurationIsCached()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$existing = config($key, []);
|
||||
$module_config = require $path;
|
||||
|
||||
|
||||
@@ -7,48 +7,45 @@ use App\Support\AuthCookie;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Modules\Auth\Entities\User;
|
||||
use Modules\Auth\Transformers\UserResource;
|
||||
use Spatie\Activitylog\Facades\Activity;
|
||||
|
||||
class AuthSessionService
|
||||
{
|
||||
public function createAuthResponse(User $user, string $message, int $status = 200): JsonResponse
|
||||
{
|
||||
return Activity::withoutLogs(function () use ($user, $message, $status) {
|
||||
$user->ensurePublicProfileToken();
|
||||
$user->ensurePublicProfileToken();
|
||||
|
||||
if (config('app.env') !== 'local') {
|
||||
$user->tokens()->delete();
|
||||
}
|
||||
if (config('app.env') !== 'local') {
|
||||
$user->tokens()->delete();
|
||||
}
|
||||
|
||||
$token = $user->createToken(
|
||||
name: 'authToken',
|
||||
abilities: ['*'],
|
||||
expiresAt: now()->addMinutes((int) config('auth_cookie.lifetime_minutes', 720))
|
||||
);
|
||||
$token = $user->createToken(
|
||||
name: 'authToken',
|
||||
abilities: ['*'],
|
||||
expiresAt: now()->addMinutes((int) config('auth_cookie.lifetime_minutes', 720))
|
||||
);
|
||||
|
||||
$user->load(['roles.permissions']);
|
||||
$user->load(['roles.permissions']);
|
||||
|
||||
ActiveRoleService::assignDefaultToToken($user, $token->accessToken);
|
||||
ActiveRoleService::assignDefaultToToken($user, $token->accessToken);
|
||||
|
||||
$payload = [
|
||||
'success' => true,
|
||||
'message' => $message,
|
||||
'data' => [
|
||||
'user' => new UserResource($user),
|
||||
'token' => $token->plainTextToken,
|
||||
'token_type' => 'Bearer',
|
||||
'expires_at' => $token->accessToken->expires_at,
|
||||
],
|
||||
...ActiveRoleService::sessionMeta($user),
|
||||
];
|
||||
$payload = [
|
||||
'success' => true,
|
||||
'message' => $message,
|
||||
'data' => [
|
||||
'user' => new UserResource($user),
|
||||
'token' => $token->plainTextToken,
|
||||
'token_type' => 'Bearer',
|
||||
'expires_at' => $token->accessToken->expires_at,
|
||||
],
|
||||
...ActiveRoleService::sessionMeta($user),
|
||||
];
|
||||
|
||||
if (AuthCookie::shouldExposeTokenInResponse()) {
|
||||
$payload['data']['token'] = $token->plainTextToken;
|
||||
}
|
||||
if (AuthCookie::shouldExposeTokenInResponse()) {
|
||||
$payload['data']['token'] = $token->plainTextToken;
|
||||
}
|
||||
|
||||
$response = response()->json($payload, $status);
|
||||
$response = response()->json($payload, $status);
|
||||
|
||||
return AuthCookie::attachAuthToken($response, $token->plainTextToken);
|
||||
});
|
||||
return AuthCookie::attachAuthToken($response, $token->plainTextToken);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
<?php
|
||||
|
||||
return [
|
||||
'name' => 'Dashboard',
|
||||
];
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Dashboard\Database\Seeders;
|
||||
|
||||
use Illuminate\Database\Seeder;
|
||||
|
||||
class DashboardDatabaseSeeder extends Seeder
|
||||
{
|
||||
/**
|
||||
* Run the database seeds.
|
||||
*/
|
||||
public function run(): void
|
||||
{
|
||||
// $this->call([]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Dashboard\Http\Controllers;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Modules\Dashboard\Services\KJC\KJCDashboardService;
|
||||
use Modules\Dashboard\Services\PKJ\PKJDashboardService;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
|
||||
class DashboardController extends Controller
|
||||
{
|
||||
protected KJCDashboardService $kjcDashboardService;
|
||||
protected PKJDashboardService $pkjDashboardService;
|
||||
|
||||
public function __construct(
|
||||
KJCDashboardService $kjcDashboardService,
|
||||
PKJDashboardService $pkjDashboardService
|
||||
) {
|
||||
$this->kjcDashboardService = $kjcDashboardService;
|
||||
$this->pkjDashboardService = $pkjDashboardService;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get dashboard overview data
|
||||
*/
|
||||
public function getOverview(Request $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
$filters = $request->only(['date_from', 'date_to', 'unit_id', 'camp_id', 'formation_id', 'government_id']);
|
||||
$user = $request->user(); // Get authenticated user
|
||||
|
||||
$overview = [
|
||||
'total_units' => $this->kjcDashboardService->getTotalUnits($filters),
|
||||
'total_camps' => $this->kjcDashboardService->getTotalCamps($filters),
|
||||
'total_formations' => $this->kjcDashboardService->getTotalFormations($filters),
|
||||
'kjc' => [
|
||||
'total_assets' => $this->kjcDashboardService->getTotalAssets($filters, $user),
|
||||
'operational_assets' => $this->kjcDashboardService->getOperationalAssets($filters, $user),
|
||||
'under_repair' => $this->kjcDashboardService->getUnderRepairAssets($filters, $user),
|
||||
'maintenance_due' => $this->kjcDashboardService->getMaintenanceDueAssets($filters, $user),
|
||||
'active_repairs' => $this->kjcDashboardService->getActiveRepairs($filters),
|
||||
'pending_reports' => $this->kjcDashboardService->getPendingReports($filters)
|
||||
],
|
||||
'pkj' => [
|
||||
'total_assets' => $this->pkjDashboardService->getTotalAssets($filters, $user),
|
||||
'operational_assets' => $this->pkjDashboardService->getOperationalAssets($filters, $user),
|
||||
'under_repair' => $this->pkjDashboardService->getUnderRepairAssets($filters, $user),
|
||||
'maintenance_due' => $this->pkjDashboardService->getMaintenanceDueAssets($filters, $user),
|
||||
'active_repairs' => $this->pkjDashboardService->getActiveRepairs($filters),
|
||||
'pending_reports' => $this->pkjDashboardService->getPendingReports($filters)
|
||||
]
|
||||
];
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'data' => $overview
|
||||
]);
|
||||
} catch (\Exception $e) {
|
||||
return response()->json([
|
||||
'success' => false,
|
||||
'message' => 'Failed to fetch dashboard overview',
|
||||
'error' => $e->getMessage()
|
||||
], 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get stat cards data
|
||||
*/
|
||||
public function getStatCards(Request $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
$filters = $request->only(['date_from', 'date_to', 'unit_id', 'camp_id', 'formation_id', 'government_id']);
|
||||
$user = $request->user(); // Get authenticated user
|
||||
|
||||
$statCards = [
|
||||
'kjc' => [
|
||||
'total_assets' => $this->kjcDashboardService->getTotalAssets($filters, $user),
|
||||
'operational_assets' => $this->kjcDashboardService->getOperationalAssets($filters, $user),
|
||||
'under_repair' => $this->kjcDashboardService->getUnderRepairAssets($filters, $user),
|
||||
'maintenance_due' => $this->kjcDashboardService->getMaintenanceDueAssets($filters, $user),
|
||||
],
|
||||
'pkj' => [
|
||||
'total_assets' => $this->pkjDashboardService->getTotalAssets($filters, $user),
|
||||
'operational_assets' => $this->pkjDashboardService->getOperationalAssets($filters, $user),
|
||||
'under_repair' => $this->pkjDashboardService->getUnderRepairAssets($filters, $user),
|
||||
'maintenance_due' => $this->pkjDashboardService->getMaintenanceDueAssets($filters, $user),
|
||||
],
|
||||
'overview' => [
|
||||
'total_units' => $this->kjcDashboardService->getTotalUnits($filters),
|
||||
'active_repairs' => $this->kjcDashboardService->getActiveRepairs($filters) + $this->pkjDashboardService->getActiveRepairs($filters),
|
||||
'pending_reports' => $this->kjcDashboardService->getPendingReports($filters) + $this->pkjDashboardService->getPendingReports($filters),
|
||||
]
|
||||
];
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'data' => $statCards
|
||||
]);
|
||||
} catch (\Exception $e) {
|
||||
return response()->json([
|
||||
'success' => false,
|
||||
'message' => 'Failed to fetch stat cards',
|
||||
'error' => $e->getMessage()
|
||||
], 500);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Dashboard\Http\Controllers\KJC;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Modules\KJCAssetEntitlement\Entities\KJCAssetEntitlement;
|
||||
use Modules\KJCAssetHolding\Entities\KJCAssetHolding;
|
||||
use Modules\Dashboard\Services\KJC\KJCDashboardService;
|
||||
use Modules\Dashboard\Repositories\Contracts\KJCDashboardRepositoryInterface;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
|
||||
class KJCDashboardController extends Controller
|
||||
{
|
||||
protected KJCDashboardService $kjcDashboardService;
|
||||
protected KJCDashboardRepositoryInterface $kjcDashboardRepository;
|
||||
|
||||
public function __construct(KJCDashboardService $kjcDashboardService, KJCDashboardRepositoryInterface $kjcDashboardRepository)
|
||||
{
|
||||
$this->kjcDashboardService = $kjcDashboardService;
|
||||
$this->kjcDashboardRepository = $kjcDashboardRepository;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get KJC entitlement vs holdings pie chart
|
||||
*/
|
||||
public function getEntitlementVsHoldingsPieChart(Request $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
$filters = $request->only(['date_from', 'date_to', 'unit_id', 'camp_id', 'formation_id', 'government_id']);
|
||||
$user = $request->user(); // Get authenticated user
|
||||
$chartData = $this->kjcDashboardService->getEntitlementVsHoldingsPieChart($filters, $user);
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'data' => $chartData
|
||||
]);
|
||||
} catch (\Exception $e) {
|
||||
return response()->json([
|
||||
'success' => false,
|
||||
'message' => 'Failed to fetch KJC entitlement vs holdings chart',
|
||||
'error' => $e->getMessage()
|
||||
], 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get KJC holdings status breakdown pie chart
|
||||
*/
|
||||
public function getHoldingsStatusBreakdownPieChart(Request $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
$filters = $request->only(['date_from', 'date_to', 'unit_id', 'camp_id', 'formation_id', 'government_id']);
|
||||
$user = $request->user(); // Get authenticated user
|
||||
$chartData = $this->kjcDashboardService->getHoldingsStatusBreakdownPieChart($filters, $user);
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'data' => $chartData
|
||||
]);
|
||||
} catch (\Exception $e) {
|
||||
return response()->json([
|
||||
'success' => false,
|
||||
'message' => 'Failed to fetch KJC holdings status breakdown chart',
|
||||
'error' => $e->getMessage()
|
||||
], 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get KJC unit performance chart
|
||||
*/
|
||||
public function getUnitPerformanceChart(Request $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
$filters = $request->only(['date_from', 'date_to', 'unit_id', 'camp_id', 'formation_id', 'government_id']);
|
||||
$user = $request->user(); // Get authenticated user
|
||||
$chartData = $this->kjcDashboardService->getUnitPerformanceChart($filters, $user);
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'data' => $chartData
|
||||
]);
|
||||
} catch (\Exception $e) {
|
||||
return response()->json([
|
||||
'success' => false,
|
||||
'message' => 'Failed to fetch KJC unit performance chart',
|
||||
'error' => $e->getMessage()
|
||||
], 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get KJC monthly trends chart
|
||||
*/
|
||||
public function getMonthlyTrendsChart(Request $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
$filters = $request->only(['date_from', 'date_to', 'unit_id', 'camp_id', 'formation_id', 'government_id']);
|
||||
$user = $request->user(); // Get authenticated user
|
||||
$chartData = $this->kjcDashboardService->getMonthlyTrendsChart($filters, $user);
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'data' => $chartData
|
||||
]);
|
||||
} catch (\Exception $e) {
|
||||
return response()->json([
|
||||
'success' => false,
|
||||
'message' => 'Failed to fetch KJC monthly trends chart',
|
||||
'error' => $e->getMessage()
|
||||
], 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get KJC historical metrics bar chart
|
||||
*/
|
||||
public function getHistoricalMetricsBarChart(Request $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
$filters = $request->only(['date_from', 'date_to', 'unit_id', 'camp_id', 'formation_id', 'government_id']);
|
||||
$user = $request->user(); // Get authenticated user
|
||||
$chartData = $this->kjcDashboardService->getHistoricalMetricsBarChart($filters, $user);
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'data' => $chartData
|
||||
]);
|
||||
} catch (\Exception $e) {
|
||||
return response()->json([
|
||||
'success' => false,
|
||||
'message' => 'Failed to fetch KJC historical metrics chart',
|
||||
'error' => $e->getMessage()
|
||||
], 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get drill-down data for entitlement vs holdings
|
||||
*/
|
||||
public function getEntitlementVsHoldingsDetails(Request $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
$filters = $request->only(['type', 'date_from', 'date_to', 'unit_id', 'camp_id', 'formation_id', 'government_id']);
|
||||
|
||||
$type = $filters['type'] ?? 'entitlement';
|
||||
|
||||
if ($type === 'entitlement') {
|
||||
// Return entitlement details
|
||||
$entitlements = KJCAssetEntitlement::with(['kjcSubcategory'])
|
||||
->paginate(20);
|
||||
|
||||
$data = [
|
||||
'title' => 'KJC Asset Entitlements',
|
||||
'filters' => array_merge($filters, ['total_count' => $entitlements->total()]),
|
||||
'items' => $entitlements->items(),
|
||||
'pagination' => [
|
||||
'current_page' => $entitlements->currentPage(),
|
||||
'per_page' => $entitlements->perPage(),
|
||||
'total' => $entitlements->total(),
|
||||
'last_page' => $entitlements->lastPage(),
|
||||
'from' => $entitlements->firstItem(),
|
||||
'to' => $entitlements->lastItem()
|
||||
]
|
||||
];
|
||||
} else {
|
||||
// Return holdings details
|
||||
$query = KJCAssetHolding::with(['unit', 'kjcCategory', 'kjcSubcategory', 'kjcModel']);
|
||||
|
||||
if (isset($filters['date_from'])) {
|
||||
$query->where('created_at', '>=', $filters['date_from']);
|
||||
}
|
||||
|
||||
if (isset($filters['date_to'])) {
|
||||
$query->where('created_at', '<=', $filters['date_to']);
|
||||
}
|
||||
|
||||
if (isset($filters['unit_id'])) {
|
||||
$query->where('unit_id', $filters['unit_id']);
|
||||
}
|
||||
|
||||
$holdings = $query->paginate(20);
|
||||
|
||||
$data = [
|
||||
'title' => 'KJC Asset Holdings',
|
||||
'filters' => array_merge($filters, ['total_count' => $holdings->total()]),
|
||||
'items' => $holdings->items(),
|
||||
'pagination' => [
|
||||
'current_page' => $holdings->currentPage(),
|
||||
'per_page' => $holdings->perPage(),
|
||||
'total' => $holdings->total(),
|
||||
'last_page' => $holdings->lastPage(),
|
||||
'from' => $holdings->firstItem(),
|
||||
'to' => $holdings->lastItem()
|
||||
]
|
||||
];
|
||||
}
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'data' => $data
|
||||
]);
|
||||
} catch (\Exception $e) {
|
||||
return response()->json([
|
||||
'success' => false,
|
||||
'message' => 'Failed to fetch entitlement vs holdings details',
|
||||
'error' => $e->getMessage()
|
||||
], 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get drill-down data for holdings status
|
||||
*/
|
||||
public function getHoldingsStatusDetails(Request $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
$filters = $request->only(['status', 'date_from', 'date_to', 'unit_id', 'camp_id', 'formation_id', 'government_id']);
|
||||
|
||||
$query = KJCAssetHolding::with(['unit', 'kjcCategory', 'kjcSubcategory', 'kjcModel']);
|
||||
|
||||
if (isset($filters['status'])) {
|
||||
$query->where('status', $filters['status']);
|
||||
}
|
||||
|
||||
if (isset($filters['date_from'])) {
|
||||
$query->where('created_at', '>=', $filters['date_from']);
|
||||
}
|
||||
|
||||
if (isset($filters['date_to'])) {
|
||||
$query->where('created_at', '<=', $filters['date_to']);
|
||||
}
|
||||
|
||||
if (isset($filters['unit_id'])) {
|
||||
$query->where('unit_id', $filters['unit_id']);
|
||||
}
|
||||
|
||||
$holdings = $query->paginate(20);
|
||||
|
||||
// Map status codes to readable names
|
||||
$statusNames = [
|
||||
'BP' => 'Beroperasi (Operational)',
|
||||
'BDG' => 'Baik Diselenggara (Well Maintained)',
|
||||
'TBDG' => 'Tidak Baik Diselenggara (Poorly Maintained)'
|
||||
];
|
||||
|
||||
$statusName = $statusNames[$filters['status']] ?? $filters['status'];
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'data' => [
|
||||
'title' => "KJC Assets with Status: {$statusName}",
|
||||
'filters' => array_merge($filters, ['total_count' => $holdings->total()]),
|
||||
'items' => $holdings->items(),
|
||||
'pagination' => [
|
||||
'current_page' => $holdings->currentPage(),
|
||||
'per_page' => $holdings->perPage(),
|
||||
'total' => $holdings->total(),
|
||||
'last_page' => $holdings->lastPage(),
|
||||
'from' => $holdings->firstItem(),
|
||||
'to' => $holdings->lastItem()
|
||||
]
|
||||
]
|
||||
]);
|
||||
} catch (\Exception $e) {
|
||||
return response()->json([
|
||||
'success' => false,
|
||||
'message' => 'Failed to fetch holdings status details',
|
||||
'error' => $e->getMessage()
|
||||
], 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get KJC asset details by status (drill-down table, paginated).
|
||||
* Status can be 'null' for assets not yet assigned a status (DB column NULL).
|
||||
*/
|
||||
public function getAssetDetailsByStatus(Request $request, string $status): JsonResponse
|
||||
{
|
||||
try {
|
||||
$filters = $request->only(['date_from', 'date_to', 'unit_id', 'camp_id', 'formation_id', 'government_id', 'page', 'per_page']);
|
||||
$user = $request->user();
|
||||
|
||||
$status = trim($status);
|
||||
$status = $status === 'null' ? '' : $status;
|
||||
|
||||
$details = $this->kjcDashboardRepository->getAssetDetailsByStatus($status, $filters, $user);
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'data' => $details
|
||||
]);
|
||||
} catch (\Exception $e) {
|
||||
return response()->json([
|
||||
'success' => false,
|
||||
'message' => 'Failed to fetch KJC asset details',
|
||||
'error' => $e->getMessage()
|
||||
], 500);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Dashboard\Http\Controllers\PKJ;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Modules\Dashboard\Services\PKJ\PKJDashboardService;
|
||||
use Modules\Dashboard\Repositories\Contracts\PKJDashboardRepositoryInterface;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
|
||||
class PKJDashboardController extends Controller
|
||||
{
|
||||
protected PKJDashboardService $pkjDashboardService;
|
||||
protected PKJDashboardRepositoryInterface $pkjDashboardRepository;
|
||||
|
||||
public function __construct(PKJDashboardService $pkjDashboardService, PKJDashboardRepositoryInterface $pkjDashboardRepository)
|
||||
{
|
||||
$this->pkjDashboardService = $pkjDashboardService;
|
||||
$this->pkjDashboardRepository = $pkjDashboardRepository;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get PKJ entitlement vs holdings pie chart
|
||||
*/
|
||||
public function getEntitlementVsHoldingsPieChart(Request $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
$filters = $request->only(['date_from', 'date_to', 'unit_id', 'camp_id', 'formation_id', 'government_id']);
|
||||
$user = $request->user(); // Get authenticated user
|
||||
$chartData = $this->pkjDashboardService->getEntitlementVsHoldingsPieChart($filters, $user);
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'data' => $chartData
|
||||
]);
|
||||
} catch (\Exception $e) {
|
||||
return response()->json([
|
||||
'success' => false,
|
||||
'message' => 'Failed to fetch PKJ entitlement vs holdings chart',
|
||||
'error' => $e->getMessage()
|
||||
], 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get PKJ holdings status breakdown pie chart
|
||||
*/
|
||||
public function getHoldingsStatusBreakdownPieChart(Request $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
$filters = $request->only(['date_from', 'date_to', 'unit_id', 'camp_id', 'formation_id', 'government_id']);
|
||||
$user = $request->user(); // Get authenticated user
|
||||
$chartData = $this->pkjDashboardService->getHoldingsStatusBreakdownPieChart($filters, $user);
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'data' => $chartData
|
||||
]);
|
||||
} catch (\Exception $e) {
|
||||
return response()->json([
|
||||
'success' => false,
|
||||
'message' => 'Failed to fetch PKJ holdings status breakdown chart',
|
||||
'error' => $e->getMessage()
|
||||
], 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get PKJ monthly trends chart
|
||||
*/
|
||||
public function getMonthlyTrendsChart(Request $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
$filters = $request->only(['date_from', 'date_to', 'unit_id', 'camp_id', 'formation_id', 'government_id']);
|
||||
$user = $request->user(); // Get authenticated user
|
||||
$chartData = $this->pkjDashboardService->getMonthlyTrendsChart($filters, $user);
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'data' => $chartData
|
||||
]);
|
||||
} catch (\Exception $e) {
|
||||
return response()->json([
|
||||
'success' => false,
|
||||
'message' => 'Failed to fetch PKJ monthly trends chart',
|
||||
'error' => $e->getMessage()
|
||||
], 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get PKJ holdings by category bar chart
|
||||
*/
|
||||
public function getHoldingsByCategoryBarChart(Request $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
$filters = $request->only(['date_from', 'date_to', 'unit_id', 'camp_id', 'formation_id', 'government_id']);
|
||||
$user = $request->user(); // Get authenticated user
|
||||
$chartData = $this->pkjDashboardService->getHoldingsByCategoryBarChart($filters, $user);
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'data' => $chartData
|
||||
]);
|
||||
} catch (\Exception $e) {
|
||||
return response()->json([
|
||||
'success' => false,
|
||||
'message' => 'Failed to fetch PKJ holdings by category chart',
|
||||
'error' => $e->getMessage()
|
||||
], 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get PKJ category metrics bar chart (drill-down)
|
||||
*/
|
||||
public function getCategoryMetricsBarChart(Request $request, int $categoryId): JsonResponse
|
||||
{
|
||||
try {
|
||||
$filters = $request->only(['date_from', 'date_to', 'unit_id', 'camp_id', 'formation_id', 'government_id']);
|
||||
$user = $request->user(); // Get authenticated user
|
||||
$chartData = $this->pkjDashboardService->getCategoryMetricsBarChart($categoryId, $filters, $user);
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'data' => $chartData
|
||||
]);
|
||||
} catch (\Exception $e) {
|
||||
return response()->json([
|
||||
'success' => false,
|
||||
'message' => 'Failed to fetch PKJ category metrics chart',
|
||||
'error' => $e->getMessage()
|
||||
], 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get PKJ category status breakdown pie chart (drill-down)
|
||||
*/
|
||||
public function getCategoryStatusBreakdownPieChart(Request $request, int $categoryId): JsonResponse
|
||||
{
|
||||
try {
|
||||
$filters = $request->only(['date_from', 'date_to', 'unit_id', 'camp_id', 'formation_id', 'government_id']);
|
||||
$user = $request->user(); // Get authenticated user
|
||||
$chartData = $this->pkjDashboardService->getCategoryStatusBreakdownPieChart($categoryId, $filters, $user);
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'data' => $chartData
|
||||
]);
|
||||
} catch (\Exception $e) {
|
||||
return response()->json([
|
||||
'success' => false,
|
||||
'message' => 'Failed to fetch PKJ category status breakdown chart',
|
||||
'error' => $e->getMessage()
|
||||
], 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get PKJ asset details by category and status (drill-down)
|
||||
*/
|
||||
public function getAssetDetailsByCategoryAndStatus(Request $request, int $categoryId, string $status): JsonResponse
|
||||
{
|
||||
try {
|
||||
$filters = $request->only(['date_from', 'date_to', 'unit_id', 'camp_id', 'formation_id', 'government_id', 'page', 'per_page']);
|
||||
$user = $request->user(); // Get authenticated user
|
||||
|
||||
// Convert 'null' string to empty string for null status handling
|
||||
// Trim whitespace to ensure exact matching
|
||||
$status = trim($status);
|
||||
$status = $status === 'null' ? '' : $status;
|
||||
|
||||
$details = $this->pkjDashboardRepository->getAssetDetailsByCategoryAndStatus($categoryId, $status, $filters, $user);
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'data' => $details
|
||||
]);
|
||||
} catch (\Exception $e) {
|
||||
return response()->json([
|
||||
'success' => false,
|
||||
'message' => 'Failed to fetch PKJ asset details',
|
||||
'error' => $e->getMessage()
|
||||
], 500);
|
||||
}
|
||||
}
|
||||
}
|
||||
+26
-49
@@ -1,31 +1,20 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Investment\Providers;
|
||||
namespace Modules\Dashboard\Providers;
|
||||
|
||||
use Illuminate\Support\Facades\Blade;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
use Modules\Investment\Entities\Investment;
|
||||
use Modules\Investment\Entities\InvestmentLimitProfile;
|
||||
use Modules\Investment\Entities\InvestmentType;
|
||||
use Modules\Investment\Entities\SalaryContribution;
|
||||
use Modules\Investment\Entities\SalaryDeductionBatch;
|
||||
use Modules\Investment\Entities\UserInvestmentLimit;
|
||||
use Modules\Investment\Policies\InvestmentLimitPolicy;
|
||||
use Modules\Investment\Policies\InvestmentPolicy;
|
||||
use Modules\Investment\Policies\InvestmentTypePolicy;
|
||||
use Modules\Investment\Policies\SalaryDeductionPolicy;
|
||||
use Nwidart\Modules\Traits\PathNamespace;
|
||||
use RecursiveDirectoryIterator;
|
||||
use RecursiveIteratorIterator;
|
||||
|
||||
class InvestmentServiceProvider extends ServiceProvider
|
||||
class DashboardServiceProvider extends ServiceProvider
|
||||
{
|
||||
use PathNamespace;
|
||||
|
||||
protected string $name = 'Investment';
|
||||
protected string $name = 'Dashboard';
|
||||
|
||||
protected string $nameLower = 'investment';
|
||||
protected string $nameLower = 'dashboard';
|
||||
|
||||
/**
|
||||
* Boot the application events.
|
||||
@@ -38,7 +27,6 @@ class InvestmentServiceProvider extends ServiceProvider
|
||||
$this->registerConfig();
|
||||
$this->registerViews();
|
||||
$this->loadMigrationsFrom(module_path($this->name, 'Database/Migrations'));
|
||||
$this->registerPolicies();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -48,36 +36,21 @@ class InvestmentServiceProvider extends ServiceProvider
|
||||
{
|
||||
$this->app->register(EventServiceProvider::class);
|
||||
$this->app->register(RouteServiceProvider::class);
|
||||
|
||||
$this->app->bind(
|
||||
\Modules\Investment\Repositories\Contracts\InvestmentTypeRepositoryInterface::class,
|
||||
\Modules\Investment\Repositories\InvestmentTypeRepository::class
|
||||
);
|
||||
|
||||
$this->app->bind(
|
||||
\Modules\Investment\Repositories\Contracts\InvestmentLimitProfileRepositoryInterface::class,
|
||||
\Modules\Investment\Repositories\InvestmentLimitProfileRepository::class
|
||||
);
|
||||
|
||||
$this->app->bind(
|
||||
\Modules\Investment\Repositories\Contracts\UserInvestmentLimitRepositoryInterface::class,
|
||||
\Modules\Investment\Repositories\UserInvestmentLimitRepository::class
|
||||
);
|
||||
|
||||
$this->app->bind(
|
||||
\Modules\Investment\Repositories\Contracts\SalaryContributionRepositoryInterface::class,
|
||||
\Modules\Investment\Repositories\SalaryContributionRepository::class
|
||||
);
|
||||
}
|
||||
|
||||
protected function registerPolicies(): void
|
||||
{
|
||||
Gate::policy(InvestmentType::class, InvestmentTypePolicy::class);
|
||||
Gate::policy(Investment::class, InvestmentPolicy::class);
|
||||
Gate::policy(InvestmentLimitProfile::class, InvestmentLimitPolicy::class);
|
||||
Gate::policy(UserInvestmentLimit::class, InvestmentLimitPolicy::class);
|
||||
Gate::policy(SalaryContribution::class, SalaryDeductionPolicy::class);
|
||||
Gate::policy(SalaryDeductionBatch::class, SalaryDeductionPolicy::class);
|
||||
|
||||
// Register dashboard repositories
|
||||
$this->app->bind(
|
||||
\Modules\Dashboard\Repositories\Contracts\KJCDashboardRepositoryInterface::class,
|
||||
\Modules\Dashboard\Repositories\KJCDashboardRepository::class
|
||||
);
|
||||
|
||||
$this->app->bind(
|
||||
\Modules\Dashboard\Repositories\Contracts\PKJDashboardRepositoryInterface::class,
|
||||
\Modules\Dashboard\Repositories\PKJDashboardRepository::class
|
||||
);
|
||||
|
||||
// Register dashboard services
|
||||
$this->app->singleton(\Modules\Dashboard\Services\KJC\KJCDashboardService::class);
|
||||
$this->app->singleton(\Modules\Dashboard\Services\PKJ\PKJDashboardService::class);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -110,8 +83,8 @@ class InvestmentServiceProvider extends ServiceProvider
|
||||
$this->loadTranslationsFrom($langPath, $this->nameLower);
|
||||
$this->loadJsonTranslationsFrom($langPath);
|
||||
} else {
|
||||
$this->loadTranslationsFrom(module_path($this->name, '$PATH_LANG$'), $this->nameLower);
|
||||
$this->loadJsonTranslationsFrom(module_path($this->name, '$PATH_LANG$'));
|
||||
$this->loadTranslationsFrom(module_path($this->name, 'Lang'), $this->nameLower);
|
||||
$this->loadJsonTranslationsFrom(module_path($this->name, 'Lang'));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -153,6 +126,10 @@ class InvestmentServiceProvider extends ServiceProvider
|
||||
*/
|
||||
protected function merge_config_from(string $path, string $key): void
|
||||
{
|
||||
if ($this->app->configurationIsCached()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$existing = config($key, []);
|
||||
$module_config = require $path;
|
||||
|
||||
@@ -165,7 +142,7 @@ class InvestmentServiceProvider extends ServiceProvider
|
||||
public function registerViews(): void
|
||||
{
|
||||
$viewPath = resource_path('views/modules/'.$this->nameLower);
|
||||
$sourcePath = module_path($this->name, '$PATH_VIEWS$');
|
||||
$sourcePath = module_path($this->name, 'Resources/Views');
|
||||
|
||||
$this->publishes([$sourcePath => $viewPath], ['views', $this->nameLower.'-module-views']);
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Investment\Providers;
|
||||
namespace Modules\Dashboard\Providers;
|
||||
|
||||
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
|
||||
|
||||
+2
-3
@@ -1,13 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Investment\Providers;
|
||||
namespace Modules\Dashboard\Providers;
|
||||
|
||||
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
class RouteServiceProvider extends ServiceProvider
|
||||
{
|
||||
protected string $name = 'Investment';
|
||||
protected string $name = 'Dashboard';
|
||||
|
||||
/**
|
||||
* Called before routes are registered.
|
||||
@@ -25,7 +25,6 @@ class RouteServiceProvider extends ServiceProvider
|
||||
public function map(): void
|
||||
{
|
||||
$this->mapApiRoutes();
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Dashboard\Repositories\Contracts;
|
||||
|
||||
interface KJCDashboardRepositoryInterface
|
||||
{
|
||||
/**
|
||||
* Get total KJC asset entitlement
|
||||
*/
|
||||
public function getTotalEntitlement(array $filters = [], $user = null): int;
|
||||
|
||||
/**
|
||||
* Get total KJC asset holdings
|
||||
*/
|
||||
public function getTotalHoldings(array $filters = [], $user = null): int;
|
||||
|
||||
/**
|
||||
* Get KJC asset holdings by status
|
||||
*/
|
||||
public function getHoldingsByStatus(array $filters = [], $user = null): array;
|
||||
|
||||
/**
|
||||
* Get KJC asset holdings with pagination
|
||||
*/
|
||||
public function getHoldingsPaginated(array $filters = [], int $perPage = 20, $user = null): array;
|
||||
|
||||
/**
|
||||
* Get KJC asset entitlements with pagination
|
||||
*/
|
||||
public function getEntitlementsPaginated(array $filters = [], int $perPage = 20, $user = null): array;
|
||||
|
||||
/**
|
||||
* Get KJC asset holdings by specific status
|
||||
*/
|
||||
public function getHoldingsBySpecificStatus(string $status, array $filters = [], $user = null): array;
|
||||
|
||||
/**
|
||||
* Get KJC asset holdings grouped by unit
|
||||
*/
|
||||
public function getHoldingsByUnit(array $filters = [], $user = null): array;
|
||||
|
||||
/**
|
||||
* Get KJC asset holdings monthly trends
|
||||
*/
|
||||
public function getMonthlyTrends(array $filters = [], $user = null): array;
|
||||
|
||||
/**
|
||||
* Get KJC historical metrics (KEUPAYAAN, KESIAGAAN, SERVISIBILITI) by month
|
||||
*/
|
||||
public function getHistoricalMetricsByMonth(array $filters = []): array;
|
||||
|
||||
/**
|
||||
* Get KJC asset details by status (paginated).
|
||||
* When status is '' or 'null', returns assets where status column is NULL (not yet assigned).
|
||||
*/
|
||||
public function getAssetDetailsByStatus(string $status, array $filters = [], $user = null): array;
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Dashboard\Repositories\Contracts;
|
||||
|
||||
interface PKJDashboardRepositoryInterface
|
||||
{
|
||||
/**
|
||||
* Get total PKJ asset entitlement
|
||||
*/
|
||||
public function getTotalEntitlement(array $filters = [], $user = null): int;
|
||||
|
||||
/**
|
||||
* Get total PKJ asset holdings
|
||||
*/
|
||||
public function getTotalHoldings(array $filters = [], $user = null): int;
|
||||
|
||||
/**
|
||||
* Get PKJ asset holdings grouped by status
|
||||
*/
|
||||
public function getHoldingsByStatus(array $filters = [], $user = null): array;
|
||||
|
||||
/**
|
||||
* Get PKJ asset holdings by specific status
|
||||
*/
|
||||
public function getHoldingsBySpecificStatus(string $status, array $filters = [], $user = null): array;
|
||||
|
||||
/**
|
||||
* Get PKJ monthly trends
|
||||
*/
|
||||
public function getMonthlyTrends(array $filters = [], $user = null): array;
|
||||
|
||||
/**
|
||||
* Get PKJ holdings by category
|
||||
*/
|
||||
public function getHoldingsByCategory(array $filters = [], $user = null): array;
|
||||
|
||||
/**
|
||||
* Get PKJ category metrics (KEUPAYAAN, KESIAGAAN, SERVISIBILITI)
|
||||
*/
|
||||
public function getCategoryMetrics(int $categoryId, array $filters = [], $user = null): array;
|
||||
|
||||
/**
|
||||
* Get PKJ category status breakdown
|
||||
*/
|
||||
public function getCategoryStatusBreakdown(int $categoryId, array $filters = [], $user = null): array;
|
||||
|
||||
/**
|
||||
* Get PKJ asset details by category and status
|
||||
*/
|
||||
public function getAssetDetailsByCategoryAndStatus(int $categoryId, string $status, array $filters = [], $user = null): array;
|
||||
}
|
||||
@@ -0,0 +1,645 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Dashboard\Repositories;
|
||||
|
||||
use Modules\Dashboard\Repositories\Contracts\KJCDashboardRepositoryInterface;
|
||||
use Modules\KJCAssetEntitlement\Entities\KJCAssetEntitlement;
|
||||
use Modules\KJCAssetHolding\Entities\KJCAssetHolding;
|
||||
use App\Models\KJCHistoricalEntitlement;
|
||||
use App\Models\KJCHistoricalHoldingStatus;
|
||||
use Modules\Unit\Entities\Unit;
|
||||
use Modules\Formation\Entities\Formation;
|
||||
use App\Services\VisibilityService;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Carbon\Carbon;
|
||||
|
||||
class KJCDashboardRepository implements KJCDashboardRepositoryInterface
|
||||
{
|
||||
public function __construct(
|
||||
protected VisibilityService $visibilityService
|
||||
) {}
|
||||
/**
|
||||
* Get total KJC asset entitlement
|
||||
*/
|
||||
public function getTotalEntitlement(array $filters = [], $user = null): int
|
||||
{
|
||||
$query = KJCAssetEntitlement::query();
|
||||
|
||||
// Apply visibility scoping if user is provided
|
||||
if ($user) {
|
||||
$query->visibleTo($user);
|
||||
}
|
||||
|
||||
$this->applyFilters($query, $filters, excludeDateFilter: true);
|
||||
|
||||
return $query->sum('entitlement');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get total KJC asset holdings
|
||||
*/
|
||||
public function getTotalHoldings(array $filters = [], $user = null): int
|
||||
{
|
||||
$query = KJCAssetEntitlement::query();
|
||||
|
||||
// Apply visibility scoping if user is provided
|
||||
if ($user) {
|
||||
$query->visibleTo($user);
|
||||
}
|
||||
|
||||
$this->applyFilters($query, $filters, excludeDateFilter: true);
|
||||
|
||||
return $query->sum('holding');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get KJC asset holdings by status.
|
||||
* Does not filter by date so totals match full KJCAssetHolding counts (unit/government/formation filters still apply).
|
||||
*/
|
||||
public function getHoldingsByStatus(array $filters = [], $user = null): array
|
||||
{
|
||||
$query = KJCAssetHolding::query();
|
||||
|
||||
// Apply visibility scoping if user is provided
|
||||
if ($user) {
|
||||
$query->visibleTo($user);
|
||||
}
|
||||
|
||||
$this->applyFilters($query, $filters, excludeDateFilter: true);
|
||||
|
||||
return $query->selectRaw('status, COUNT(*) as count')
|
||||
->groupBy('status')
|
||||
->get()
|
||||
->toArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get KJC asset holdings with pagination
|
||||
*/
|
||||
public function getHoldingsPaginated(array $filters = [], int $perPage = 20, $user = null): array
|
||||
{
|
||||
$query = KJCAssetHolding::with(['unit', 'kjcCategory', 'kjcSubcategory', 'kjcModel']);
|
||||
|
||||
// Apply visibility scoping if user is provided
|
||||
if ($user) {
|
||||
$query->visibleTo($user);
|
||||
}
|
||||
|
||||
$this->applyFilters($query, $filters);
|
||||
|
||||
$holdings = $query->paginate($perPage);
|
||||
|
||||
return [
|
||||
'items' => $holdings->items(),
|
||||
'pagination' => [
|
||||
'current_page' => $holdings->currentPage(),
|
||||
'per_page' => $holdings->perPage(),
|
||||
'total' => $holdings->total(),
|
||||
'last_page' => $holdings->lastPage(),
|
||||
'from' => $holdings->firstItem(),
|
||||
'to' => $holdings->lastItem()
|
||||
]
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get KJC asset entitlements with pagination
|
||||
*/
|
||||
public function getEntitlementsPaginated(array $filters = [], int $perPage = 20, $user = null): array
|
||||
{
|
||||
$query = KJCAssetEntitlement::with(['kjcSubcategory']);
|
||||
|
||||
// Apply visibility scoping if user is provided
|
||||
if ($user) {
|
||||
$query->visibleTo($user);
|
||||
}
|
||||
|
||||
$this->applyFilters($query, $filters);
|
||||
|
||||
$entitlements = $query->paginate($perPage);
|
||||
|
||||
return [
|
||||
'items' => $entitlements->items(),
|
||||
'pagination' => [
|
||||
'current_page' => $entitlements->currentPage(),
|
||||
'per_page' => $entitlements->perPage(),
|
||||
'total' => $entitlements->total(),
|
||||
'last_page' => $entitlements->lastPage(),
|
||||
'from' => $entitlements->firstItem(),
|
||||
'to' => $entitlements->lastItem()
|
||||
]
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get KJC asset holdings by specific status
|
||||
*/
|
||||
public function getHoldingsBySpecificStatus(string $status, array $filters = [], $user = null): array
|
||||
{
|
||||
$query = KJCAssetHolding::with(['unit', 'kjcCategory', 'kjcSubcategory', 'kjcModel'])
|
||||
->where('status', $status);
|
||||
|
||||
// Apply visibility scoping if user is provided
|
||||
if ($user) {
|
||||
$query->visibleTo($user);
|
||||
}
|
||||
|
||||
$this->applyFilters($query, $filters);
|
||||
|
||||
$holdings = $query->paginate(20);
|
||||
|
||||
return [
|
||||
'items' => $holdings->items(),
|
||||
'pagination' => [
|
||||
'current_page' => $holdings->currentPage(),
|
||||
'per_page' => $holdings->perPage(),
|
||||
'total' => $holdings->total(),
|
||||
'last_page' => $holdings->lastPage(),
|
||||
'from' => $holdings->firstItem(),
|
||||
'to' => $holdings->lastItem()
|
||||
]
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get KJC asset details by status (paginated).
|
||||
* When status is '' or 'null', returns assets where status column is NULL (not yet assigned).
|
||||
*/
|
||||
public function getAssetDetailsByStatus(string $status, array $filters = [], $user = null): array
|
||||
{
|
||||
$status = trim($status ?? '');
|
||||
|
||||
$query = KJCAssetHolding::query()
|
||||
->with(['kjcCategory', 'kjcSubcategory', 'kjcModel', 'unit'])
|
||||
->select([
|
||||
'id',
|
||||
'uuid',
|
||||
'kjc_category_id',
|
||||
'kjc_subcategory_id',
|
||||
'kjc_model_id',
|
||||
'registration_number',
|
||||
'kewpa_registration_number',
|
||||
'status',
|
||||
'unit_id',
|
||||
'purchase_date',
|
||||
'receipt_date',
|
||||
'purchase_price',
|
||||
'contract_reference',
|
||||
'economic_year',
|
||||
'economic_distance',
|
||||
'note',
|
||||
'engine_number',
|
||||
'chassis_number',
|
||||
'created_at',
|
||||
'updated_at'
|
||||
]);
|
||||
|
||||
if ($status === '' || $status === 'null') {
|
||||
$query->whereNull('status');
|
||||
} else {
|
||||
$query->whereNotNull('status')
|
||||
->where('status', '=', $status);
|
||||
}
|
||||
|
||||
if ($user) {
|
||||
$query->visibleTo($user);
|
||||
}
|
||||
|
||||
$this->applyFilters($query, $filters, excludeDateFilter: true);
|
||||
|
||||
$perPage = isset($filters['per_page']) ? (int) $filters['per_page'] : 10;
|
||||
$page = isset($filters['page']) ? (int) $filters['page'] : null;
|
||||
$assets = $query->paginate($perPage, ['*'], 'page', $page);
|
||||
|
||||
return [
|
||||
'data' => $assets->items(),
|
||||
'pagination' => [
|
||||
'current_page' => $assets->currentPage(),
|
||||
'per_page' => $assets->perPage(),
|
||||
'total' => $assets->total(),
|
||||
'last_page' => $assets->lastPage(),
|
||||
'from' => $assets->firstItem(),
|
||||
'to' => $assets->lastItem(),
|
||||
'has_more_pages' => $assets->hasMorePages()
|
||||
]
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get KJC asset holdings grouped by unit
|
||||
*/
|
||||
public function getHoldingsByUnit(array $filters = [], $user = null): array
|
||||
{
|
||||
$query = KJCAssetHolding::query();
|
||||
|
||||
// Apply visibility scoping if user is provided
|
||||
if ($user) {
|
||||
$query->visibleTo($user);
|
||||
}
|
||||
|
||||
$this->applyFilters($query, $filters);
|
||||
|
||||
return $query->join('units', 'kjc_asset_holdings.unit_id', '=', 'units.id')
|
||||
->selectRaw('units.name as unit_name, COUNT(*) as count')
|
||||
->groupBy('units.name')
|
||||
->get()
|
||||
->toArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get KJC asset holdings monthly trends
|
||||
*/
|
||||
public function getMonthlyTrends(array $filters = [], $user = null): array
|
||||
{
|
||||
$dateRange = $this->getDateRange($filters);
|
||||
|
||||
$query = KJCAssetHolding::query();
|
||||
|
||||
// Apply visibility scoping if user is provided
|
||||
if ($user) {
|
||||
$query->visibleTo($user);
|
||||
}
|
||||
|
||||
$this->applyFilters($query, $filters);
|
||||
|
||||
return $query->selectRaw('
|
||||
DATE_FORMAT(created_at, "%Y-%m") as month,
|
||||
status,
|
||||
COUNT(*) as count
|
||||
')
|
||||
->whereBetween('created_at', [$dateRange['from'], $dateRange['to']])
|
||||
->groupBy('month', 'status')
|
||||
->orderBy('month')
|
||||
->get()
|
||||
->toArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get KJC historical metrics (KEUPAYAAN, KESIAGAAN, SERVISIBILITI) by month
|
||||
* 1. KEUPAYAAN (%) = (PEGANGAN/PERJAWATAN) * 100
|
||||
* 2. SIAPSIAGA or KESIAGAAN (%) = (BDG/perjawatan) * 100
|
||||
* 3. SERVISIBILITI (%) = (BDG/pegangan) * 100
|
||||
*/
|
||||
public function getHistoricalMetricsByMonth(array $filters = [], $user = null): array
|
||||
{
|
||||
$dateRange = $this->getDateRange($filters);
|
||||
$currentMonth = Carbon::now()->format('Y-m');
|
||||
|
||||
// Get entitlement and holding data by month from historical tables using Eloquent
|
||||
$entitlementQuery = KJCHistoricalEntitlement::query()
|
||||
->selectRaw('
|
||||
TO_CHAR(kjc_historical_entitlement.date, \'YYYY-MM\') as month,
|
||||
SUM(kjc_historical_entitlement.entitlement) as total_entitlement,
|
||||
SUM(kjc_historical_entitlement.holding) as total_holding
|
||||
')
|
||||
->whereBetween('kjc_historical_entitlement.date', [$dateRange['from'], $dateRange['to']]);
|
||||
|
||||
// Apply filters to historical entitlement query
|
||||
$this->applyHistoricalFiltersToEloquent($entitlementQuery, $filters);
|
||||
|
||||
// Apply visibility scoping if user is provided (uses HasVisibility trait)
|
||||
if ($user) {
|
||||
$entitlementQuery->visibleTo($user);
|
||||
}
|
||||
|
||||
$entitlementData = $entitlementQuery->groupBy('month')
|
||||
->orderBy('month')
|
||||
->get()
|
||||
->keyBy('month');
|
||||
|
||||
// Get BDG status count by month from historical tables using Eloquent
|
||||
$bdgQuery = KJCHistoricalHoldingStatus::query()
|
||||
->selectRaw('
|
||||
TO_CHAR(kjc_historical_holding_status.date, \'YYYY-MM\') as month,
|
||||
COUNT(*) as bdg_count
|
||||
')
|
||||
->where('kjc_historical_holding_status.status', 'BDG')
|
||||
->whereBetween('kjc_historical_holding_status.date', [$dateRange['from'], $dateRange['to']]);
|
||||
|
||||
// Apply filters to historical holding status query
|
||||
$this->applyHistoricalFiltersToEloquent($bdgQuery, $filters);
|
||||
|
||||
// Apply visibility scoping if user is provided (uses HasVisibility trait)
|
||||
if ($user) {
|
||||
$bdgQuery->visibleTo($user);
|
||||
}
|
||||
|
||||
$bdgData = $bdgQuery->groupBy('month')
|
||||
->orderBy('month')
|
||||
->get()
|
||||
->keyBy('month');
|
||||
|
||||
// Get current month data from real-time tables if current month is in range
|
||||
$currentMonthEntitlement = 0;
|
||||
$currentMonthHolding = 0;
|
||||
$currentMonthBdgCount = 0;
|
||||
|
||||
if ($this->isCurrentMonthInRange($currentMonth, $dateRange)) {
|
||||
// Get current month entitlement data (all entitlements, not filtered by updated_at)
|
||||
// This ensures we get real-time entitlement values regardless of when they were last updated
|
||||
$currentEntitlementQuery = KJCAssetEntitlement::query();
|
||||
if ($user) {
|
||||
$currentEntitlementQuery->visibleTo($user);
|
||||
}
|
||||
$this->applyCurrentMonthFilters($currentEntitlementQuery, $filters);
|
||||
|
||||
$currentMonthEntitlement = $currentEntitlementQuery->sum('entitlement');
|
||||
|
||||
// Calculate current month holdings from actual KJCAssetHolding records
|
||||
// This ensures we get real-time holding counts even if entitlement.holding is stale
|
||||
$currentHoldingQuery = KJCAssetHolding::query();
|
||||
if ($user) {
|
||||
$currentHoldingQuery->visibleTo($user);
|
||||
}
|
||||
$this->applyCurrentMonthFilters($currentHoldingQuery, $filters);
|
||||
|
||||
$currentMonthHolding = $currentHoldingQuery->count();
|
||||
|
||||
// Get current month BDG count (only holdings updated in current month)
|
||||
// This shows BDG holdings that were updated/changed status in the current month
|
||||
$currentBdgQuery = KJCAssetHolding::query()
|
||||
->where('status', 'BDG')
|
||||
->whereMonth('updated_at', Carbon::now()->month)
|
||||
->whereYear('updated_at', Carbon::now()->year);
|
||||
if ($user) {
|
||||
$currentBdgQuery->visibleTo($user);
|
||||
}
|
||||
$this->applyCurrentMonthFilters($currentBdgQuery, $filters);
|
||||
|
||||
$currentMonthBdgCount = $currentBdgQuery->count();
|
||||
}
|
||||
|
||||
// Generate all months in the range
|
||||
$months = [];
|
||||
$current = $dateRange['from']->copy()->startOfMonth();
|
||||
$end = $dateRange['to']->copy()->endOfMonth();
|
||||
|
||||
while ($current->lte($end)) {
|
||||
$monthKey = $current->format('Y-m');
|
||||
$months[] = $monthKey;
|
||||
$current->addMonth();
|
||||
}
|
||||
|
||||
// Calculate metrics for each month
|
||||
$result = [];
|
||||
foreach ($months as $month) {
|
||||
$entitlement = $entitlementData->get($month);
|
||||
$bdg = $bdgData->get($month);
|
||||
|
||||
// Use current month real-time data if this is the current month
|
||||
if ($month === $currentMonth && $this->isCurrentMonthInRange($currentMonth, $dateRange)) {
|
||||
$totalEntitlement = $currentMonthEntitlement;
|
||||
$totalHolding = $currentMonthHolding;
|
||||
$bdgCount = $currentMonthBdgCount;
|
||||
} else {
|
||||
$totalEntitlement = $entitlement ? $entitlement->total_entitlement : 0;
|
||||
$totalHolding = $entitlement ? $entitlement->total_holding : 0;
|
||||
$bdgCount = $bdg ? $bdg->bdg_count : 0;
|
||||
}
|
||||
|
||||
// Calculate metrics
|
||||
$keupayaan = $totalEntitlement > 0 ? ($totalHolding / $totalEntitlement) * 100 : 0;
|
||||
$kesiagaan = $totalEntitlement > 0 ? ($bdgCount / $totalEntitlement) * 100 : 0;
|
||||
$servisibiliti = $totalHolding > 0 ? ($bdgCount / $totalHolding) * 100 : 0;
|
||||
|
||||
$result[] = [
|
||||
'month' => $month,
|
||||
'keupayaan' => round($keupayaan, 2),
|
||||
'kesiagaan' => round($kesiagaan, 2),
|
||||
'servisibiliti' => round($servisibiliti, 2),
|
||||
'total_entitlement' => $totalEntitlement,
|
||||
'total_holding' => $totalHolding,
|
||||
'bdg_count' => $bdgCount
|
||||
];
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply common filters to query
|
||||
*/
|
||||
private function applyFilters($query, array $filters = [], bool $excludeDateFilter = false): void
|
||||
{
|
||||
$model = $query->getModel();
|
||||
if ($model && method_exists($model, 'getTable')) {
|
||||
$schema = $model->getConnection()->getSchemaBuilder();
|
||||
$columns = $schema->getColumnListing($model->getTable());
|
||||
|
||||
// Only apply created_at filter if the model has created_at column (skip when excludeDateFilter)
|
||||
if (!$excludeDateFilter && in_array('created_at', $columns)) {
|
||||
$dateRange = $this->getDateRange($filters);
|
||||
$query->whereBetween('created_at', [$dateRange['from'], $dateRange['to']]);
|
||||
}
|
||||
|
||||
// Apply unit_id filter if model has unit_id column
|
||||
if (isset($filters['unit_id']) && $filters['unit_id']) {
|
||||
if (in_array('unit_id', $columns)) {
|
||||
$query->where('unit_id', $filters['unit_id']);
|
||||
}
|
||||
}
|
||||
|
||||
// Apply government_id filter if provided
|
||||
if (isset($filters['government_id']) && $filters['government_id']) {
|
||||
$unitIds = $this->getUnitsByGovernment($filters['government_id']);
|
||||
if (in_array('unit_id', $columns)) {
|
||||
if (!empty($unitIds)) {
|
||||
$query->whereIn('unit_id', $unitIds);
|
||||
} else {
|
||||
// No units found for this government - return empty result
|
||||
$query->whereNull('id');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Apply camp_id filter
|
||||
if (isset($filters['camp_id']) && $filters['camp_id']) {
|
||||
$query->whereHas('unit', function ($q) use ($filters) {
|
||||
$q->where('camp_id', $filters['camp_id']);
|
||||
});
|
||||
}
|
||||
|
||||
// Apply formation_id filter
|
||||
if (isset($filters['formation_id']) && $filters['formation_id']) {
|
||||
// Get units under this formation
|
||||
$unitIds = Unit::where('formation_id', $filters['formation_id'])
|
||||
->pluck('id')
|
||||
->toArray();
|
||||
|
||||
if (!empty($unitIds)) {
|
||||
if (in_array('unit_id', $columns)) {
|
||||
$query->whereIn('unit_id', $unitIds);
|
||||
} else {
|
||||
// Fallback to whereHas if no unit_id column
|
||||
$query->whereHas('unit', function ($q) use ($filters) {
|
||||
$q->where('formation_id', $filters['formation_id']);
|
||||
});
|
||||
}
|
||||
} else {
|
||||
// No units found for this formation - return empty result
|
||||
$query->whereNull('id');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get units by government ID
|
||||
* Uses VisibilityService for consistent logic
|
||||
*/
|
||||
private function getUnitsByGovernment(int $governmentId): array
|
||||
{
|
||||
$governmentUnit = Unit::where('government_id', $governmentId)->first();
|
||||
if (!$governmentUnit) {
|
||||
// If no direct unit found, try to get from formation
|
||||
$formation = Formation::where('government_id', $governmentId)->first();
|
||||
if ($formation) {
|
||||
$governmentUnit = Unit::where('formation_id', $formation->id)->first();
|
||||
}
|
||||
}
|
||||
|
||||
if (!$governmentUnit) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return $this->visibilityService->getUnitsUnderGovernment($governmentUnit);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get date range for filtering
|
||||
*/
|
||||
private function getDateRange(array $filters = []): array
|
||||
{
|
||||
$dateFrom = $filters['date_from'] ?? Carbon::now()->startOfYear();
|
||||
$dateTo = $filters['date_to'] ?? Carbon::now()->endOfYear();
|
||||
|
||||
return [
|
||||
'from' => Carbon::parse($dateFrom)->startOfDay(),
|
||||
'to' => Carbon::parse($dateTo)->endOfDay()
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply filters to historical Eloquent queries
|
||||
* Handles government_id, formation_id, unit_id, and camp_id filters
|
||||
*/
|
||||
private function applyHistoricalFiltersToEloquent($query, array $filters = []): void
|
||||
{
|
||||
$model = $query->getModel();
|
||||
$isHoldingStatus = $model instanceof KJCHistoricalHoldingStatus;
|
||||
|
||||
// Apply unit_id filter
|
||||
if (isset($filters['unit_id']) && $filters['unit_id']) {
|
||||
if ($isHoldingStatus) {
|
||||
// For holding status, filter through the relationship
|
||||
$query->whereHas('kjcAssetHolding', function ($q) use ($filters) {
|
||||
$q->where('unit_id', $filters['unit_id']);
|
||||
});
|
||||
} else {
|
||||
$query->where('unit_id', $filters['unit_id']);
|
||||
}
|
||||
}
|
||||
|
||||
// Apply government_id filter
|
||||
if (isset($filters['government_id']) && $filters['government_id']) {
|
||||
$unitIds = $this->getUnitsByGovernment($filters['government_id']);
|
||||
if (!empty($unitIds)) {
|
||||
if ($isHoldingStatus) {
|
||||
$query->whereHas('kjcAssetHolding', function ($q) use ($unitIds) {
|
||||
$q->whereIn('unit_id', $unitIds);
|
||||
});
|
||||
} else {
|
||||
$query->whereIn('unit_id', $unitIds);
|
||||
}
|
||||
} else {
|
||||
// No units found for this government - return empty result
|
||||
$query->whereRaw('1 = 0');
|
||||
}
|
||||
}
|
||||
|
||||
// Apply formation_id filter
|
||||
if (isset($filters['formation_id']) && $filters['formation_id']) {
|
||||
// Get units under this formation
|
||||
$unitIds = Unit::where('formation_id', $filters['formation_id'])
|
||||
->pluck('id')
|
||||
->toArray();
|
||||
|
||||
if (!empty($unitIds)) {
|
||||
if ($isHoldingStatus) {
|
||||
$query->whereHas('kjcAssetHolding', function ($q) use ($unitIds) {
|
||||
$q->whereIn('unit_id', $unitIds);
|
||||
});
|
||||
} else {
|
||||
$query->whereIn('unit_id', $unitIds);
|
||||
}
|
||||
} else {
|
||||
// No units found for this formation - return empty result
|
||||
$query->whereRaw('1 = 0');
|
||||
}
|
||||
}
|
||||
|
||||
// Apply camp_id filter
|
||||
if (isset($filters['camp_id']) && $filters['camp_id']) {
|
||||
if ($isHoldingStatus) {
|
||||
$query->whereHas('kjcAssetHolding.unit', function ($q) use ($filters) {
|
||||
$q->where('camp_id', $filters['camp_id']);
|
||||
});
|
||||
} else {
|
||||
$query->whereHas('unit', function ($q) use ($filters) {
|
||||
$q->where('camp_id', $filters['camp_id']);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if current month is within the date range
|
||||
*/
|
||||
private function isCurrentMonthInRange(string $currentMonth, array $dateRange): bool
|
||||
{
|
||||
$currentMonthDate = Carbon::createFromFormat('Y-m', $currentMonth)->startOfMonth();
|
||||
return $currentMonthDate->between($dateRange['from'], $dateRange['to']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply filters for current month data queries (without date range filtering)
|
||||
*/
|
||||
private function applyCurrentMonthFilters($query, array $filters = []): void
|
||||
{
|
||||
if (isset($filters['unit_id']) && $filters['unit_id']) {
|
||||
$query->where('unit_id', $filters['unit_id']);
|
||||
}
|
||||
|
||||
// Apply government_id filter
|
||||
if (isset($filters['government_id']) && $filters['government_id']) {
|
||||
$unitIds = $this->getUnitsByGovernment($filters['government_id']);
|
||||
if (!empty($unitIds)) {
|
||||
$query->whereIn('unit_id', $unitIds);
|
||||
} else {
|
||||
// No units found for this government - return empty result
|
||||
$query->whereNull('id');
|
||||
}
|
||||
}
|
||||
|
||||
if (isset($filters['camp_id']) && $filters['camp_id']) {
|
||||
$query->whereHas('unit', function ($q) use ($filters) {
|
||||
$q->where('camp_id', $filters['camp_id']);
|
||||
});
|
||||
}
|
||||
|
||||
if (isset($filters['formation_id']) && $filters['formation_id']) {
|
||||
// Get units under this formation
|
||||
$unitIds = Unit::where('formation_id', $filters['formation_id'])
|
||||
->pluck('id')
|
||||
->toArray();
|
||||
|
||||
if (!empty($unitIds)) {
|
||||
$query->whereIn('unit_id', $unitIds);
|
||||
} else {
|
||||
// No units found for this formation - return empty result
|
||||
$query->whereNull('id');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,495 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Dashboard\Repositories;
|
||||
|
||||
use Modules\Dashboard\Repositories\Contracts\PKJDashboardRepositoryInterface;
|
||||
use Modules\PKJAssetEntitlement\Entities\PKJAssetEntitlement;
|
||||
use Modules\PKJAssetHolding\Entities\PKJAssetHolding;
|
||||
use Modules\PKJRepair\Entities\PKJRepair;
|
||||
use Modules\PKJReport\Entities\PKJReport;
|
||||
use Modules\PKJVariant\Entities\PKJCategory;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Modules\Unit\Entities\Unit;
|
||||
use App\Services\VisibilityService;
|
||||
use Carbon\Carbon;
|
||||
|
||||
class PKJDashboardRepository implements PKJDashboardRepositoryInterface
|
||||
{
|
||||
public function __construct(
|
||||
protected VisibilityService $visibilityService
|
||||
) {}
|
||||
/**
|
||||
* Get total PKJ asset entitlement
|
||||
*/
|
||||
public function getTotalEntitlement(array $filters = [], $user = null): int
|
||||
{
|
||||
$query = PKJAssetEntitlement::query();
|
||||
|
||||
// Apply visibility scoping if user is provided
|
||||
if ($user) {
|
||||
$query->visibleTo($user);
|
||||
}
|
||||
|
||||
$this->applyFilters($query, $filters, excludeDateFilter: true);
|
||||
|
||||
return $query->sum('entitlement');
|
||||
}
|
||||
|
||||
public function getTotalHoldings(array $filters = [], $user = null): int
|
||||
{
|
||||
$query = PKJAssetEntitlement::query();
|
||||
|
||||
// Apply visibility scoping if user is provided
|
||||
if ($user) {
|
||||
$query->visibleTo($user);
|
||||
}
|
||||
|
||||
$this->applyFilters($query, $filters, excludeDateFilter: true);
|
||||
|
||||
return $query->sum('holding') ?? 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get PKJ asset holdings grouped by status
|
||||
*/
|
||||
public function getHoldingsByStatus(array $filters = [], $user = null): array
|
||||
{
|
||||
$query = PKJAssetHolding::query();
|
||||
|
||||
// Apply visibility scoping if user is provided
|
||||
if ($user) {
|
||||
$query->visibleTo($user);
|
||||
}
|
||||
|
||||
$this->applyFilters($query, $filters);
|
||||
|
||||
return $query->selectRaw('status, COUNT(*) as count')
|
||||
->groupBy('status')
|
||||
->orderBy('status')
|
||||
->get()
|
||||
->toArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get PKJ asset holdings by specific status
|
||||
*/
|
||||
public function getHoldingsBySpecificStatus(string $status, array $filters = [], $user = null): array
|
||||
{
|
||||
$query = PKJAssetHolding::query();
|
||||
|
||||
// Apply visibility scoping if user is provided
|
||||
if ($user) {
|
||||
$query->visibleTo($user);
|
||||
}
|
||||
|
||||
$this->applyFilters($query, $filters);
|
||||
|
||||
$holdings = $query->where('status', $status)->paginate(10);
|
||||
|
||||
return [
|
||||
'data' => $holdings->items(),
|
||||
'pagination' => [
|
||||
'current_page' => $holdings->currentPage(),
|
||||
'per_page' => $holdings->perPage(),
|
||||
'total' => $holdings->total(),
|
||||
'last_page' => $holdings->lastPage(),
|
||||
'from' => $holdings->firstItem(),
|
||||
'to' => $holdings->lastItem()
|
||||
]
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get PKJ monthly trends
|
||||
*/
|
||||
public function getMonthlyTrends(array $filters = [], $user = null): array
|
||||
{
|
||||
$dateRange = $this->getDateRange($filters);
|
||||
|
||||
$query = PKJReport::query();
|
||||
|
||||
// Apply visibility scoping if user is provided
|
||||
if ($user) {
|
||||
$query->visibleTo($user);
|
||||
}
|
||||
|
||||
$trends = $query->selectRaw('
|
||||
TO_CHAR(created_at, \'YYYY-MM\') as month,
|
||||
COUNT(*) as total_reports
|
||||
')
|
||||
->whereBetween('created_at', [$dateRange['from'], $dateRange['to']])
|
||||
->groupBy('month')
|
||||
->orderBy('month')
|
||||
->get()
|
||||
->toArray();
|
||||
|
||||
return $trends;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get PKJ holdings by category
|
||||
*/
|
||||
public function getHoldingsByCategory(array $filters = [], $user = null): array
|
||||
{
|
||||
// Build a subquery for filtered entitlements
|
||||
// This ensures all categories are included, but only matching entitlements are summed
|
||||
$entitlementSubquery = PKJAssetEntitlement::query()
|
||||
->select('pkj_category_id', DB::raw('SUM(holding) as total_holding'))
|
||||
->groupBy('pkj_category_id');
|
||||
|
||||
// Apply visibility scoping if user is provided
|
||||
if ($user) {
|
||||
$entitlementSubquery->visibleTo($user);
|
||||
}
|
||||
|
||||
// Apply filters to entitlement subquery
|
||||
if (isset($filters['unit_id'])) {
|
||||
$entitlementSubquery->where('unit_id', $filters['unit_id']);
|
||||
}
|
||||
|
||||
// Apply government_id filter
|
||||
if (isset($filters['government_id']) && $filters['government_id']) {
|
||||
$unitIds = $this->getUnitsByGovernment($filters['government_id']);
|
||||
if (!empty($unitIds)) {
|
||||
$entitlementSubquery->whereIn('unit_id', $unitIds);
|
||||
} else {
|
||||
// If no units match, set to empty result but don't filter categories
|
||||
$entitlementSubquery->whereRaw('1 = 0');
|
||||
}
|
||||
}
|
||||
|
||||
// Apply formation_id filter
|
||||
if (isset($filters['formation_id']) && $filters['formation_id']) {
|
||||
$unitIds = Unit::where('formation_id', $filters['formation_id'])
|
||||
->pluck('id')
|
||||
->toArray();
|
||||
|
||||
if (!empty($unitIds)) {
|
||||
$entitlementSubquery->whereIn('unit_id', $unitIds);
|
||||
} else {
|
||||
// If no units match, set to empty result but don't filter categories
|
||||
$entitlementSubquery->whereRaw('1 = 0');
|
||||
}
|
||||
}
|
||||
|
||||
// Main query: Get ALL categories and LEFT JOIN with filtered entitlements
|
||||
// This ensures all categories are returned even if they have no matching entitlements
|
||||
$query = PKJCategory::query()
|
||||
->leftJoinSub($entitlementSubquery, 'filtered_entitlements', function ($join) {
|
||||
$join->on('pkj_categories.id', '=', 'filtered_entitlements.pkj_category_id');
|
||||
})
|
||||
->selectRaw('
|
||||
pkj_categories.id as category_id,
|
||||
pkj_categories.name as category_name,
|
||||
COALESCE(filtered_entitlements.total_holding, 0) as total_holding
|
||||
')
|
||||
->orderBy('pkj_categories.name');
|
||||
|
||||
return $query->get()->toArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get PKJ category metrics (KEUPAYAAN, KESIAGAAN, SERVISIBILITI)
|
||||
*/
|
||||
public function getCategoryMetrics(int $categoryId, array $filters = [], $user = null): array
|
||||
{
|
||||
// Get category name
|
||||
$category = PKJCategory::find($categoryId);
|
||||
$categoryName = $category ? $category->name : 'Unknown Category';
|
||||
|
||||
// Get entitlement and holding data for the category
|
||||
$entitlementQuery = PKJAssetEntitlement::query()
|
||||
->where('pkj_category_id', $categoryId);
|
||||
|
||||
// Apply visibility scoping if user is provided
|
||||
if ($user) {
|
||||
$entitlementQuery->visibleTo($user);
|
||||
}
|
||||
|
||||
// Apply filters
|
||||
if (isset($filters['unit_id'])) {
|
||||
$entitlementQuery->where('unit_id', $filters['unit_id']);
|
||||
}
|
||||
|
||||
$entitlementData = $entitlementQuery->selectRaw('
|
||||
SUM(entitlement) as total_entitlement,
|
||||
SUM(holding) as total_holding
|
||||
')->first();
|
||||
|
||||
// Get operational/usable assets count (BDG, BT, BP statuses) for the category
|
||||
$operationalQuery = PKJAssetHolding::query()
|
||||
->where('pkj_category_id', $categoryId)
|
||||
->whereIn('status', ['BDG', 'BT', 'BP']);
|
||||
|
||||
// Apply visibility scoping if user is provided
|
||||
if ($user) {
|
||||
$operationalQuery->visibleTo($user);
|
||||
}
|
||||
|
||||
// Apply filters
|
||||
if (isset($filters['unit_id'])) {
|
||||
$operationalQuery->where('unit_id', $filters['unit_id']);
|
||||
}
|
||||
|
||||
$operationalCount = $operationalQuery->count();
|
||||
|
||||
// Get BDG, BT, BG count specifically for servisibiliti calculation
|
||||
$bdgQuery = PKJAssetHolding::query()
|
||||
->where('pkj_category_id', $categoryId)
|
||||
->whereIn('status', ['BDG', 'BT', 'BG']);
|
||||
|
||||
// Apply visibility scoping if user is provided
|
||||
if ($user) {
|
||||
$bdgQuery->visibleTo($user);
|
||||
}
|
||||
|
||||
// Apply filters
|
||||
if (isset($filters['unit_id'])) {
|
||||
$bdgQuery->where('unit_id', $filters['unit_id']);
|
||||
}
|
||||
|
||||
$bdgCount = $bdgQuery->count();
|
||||
|
||||
$totalEntitlement = $entitlementData ? $entitlementData->total_entitlement : 0;
|
||||
$totalHolding = $entitlementData ? $entitlementData->total_holding : 0;
|
||||
|
||||
// Calculate metrics
|
||||
$keupayaan = $totalEntitlement > 0 ? ($totalHolding / $totalEntitlement) * 100 : 0;
|
||||
$kesiagaan = $totalEntitlement > 0 ? ($operationalCount / $totalEntitlement) * 100 : 0;
|
||||
$servisibiliti = $totalHolding > 0 ? ($bdgCount / $totalHolding) * 100 : 0;
|
||||
|
||||
return [
|
||||
'category_id' => $categoryId,
|
||||
'category_name' => $categoryName,
|
||||
'keupayaan' => round($keupayaan, 2),
|
||||
'kesiagaan' => round($kesiagaan, 2),
|
||||
'servisibiliti' => round($servisibiliti, 2),
|
||||
'total_entitlement' => $totalEntitlement,
|
||||
'total_holding' => $totalHolding,
|
||||
'operational_count' => $operationalCount,
|
||||
'bdg_count' => $bdgCount
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get PKJ category status breakdown
|
||||
*/
|
||||
public function getCategoryStatusBreakdown(int $categoryId, array $filters = [], $user = null): array
|
||||
{
|
||||
// Get category name
|
||||
$category = PKJCategory::find($categoryId);
|
||||
$categoryName = $category ? $category->name : 'Unknown Category';
|
||||
|
||||
$query = PKJAssetHolding::query()
|
||||
->where('pkj_category_id', $categoryId)
|
||||
->selectRaw('status, COUNT(*) as count')
|
||||
->groupBy('status')
|
||||
->orderBy('status');
|
||||
|
||||
// Apply visibility scoping if user is provided
|
||||
if ($user) {
|
||||
$query->visibleTo($user);
|
||||
}
|
||||
|
||||
// Apply filters
|
||||
if (isset($filters['unit_id'])) {
|
||||
$query->where('unit_id', $filters['unit_id']);
|
||||
}
|
||||
|
||||
$statusCounts = $query->get()->toArray();
|
||||
|
||||
return [
|
||||
'category_id' => $categoryId,
|
||||
'category_name' => $categoryName,
|
||||
'status_breakdown' => $statusCounts
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get PKJ asset details by category and status.
|
||||
*
|
||||
* When the asset has no status yet, the status column in the database is NULL.
|
||||
* Callers pass status as '' or the string 'null' to request these "no status" assets.
|
||||
*/
|
||||
public function getAssetDetailsByCategoryAndStatus(int $categoryId, string $status, array $filters = [], $user = null): array
|
||||
{
|
||||
// Handle no-status: API passes '' or 'null'; DB column is NULL for assets not yet assigned a status
|
||||
$status = trim($status ?? '');
|
||||
|
||||
$query = PKJAssetHolding::query()
|
||||
->with(['unit', 'pkjCategory', 'pkjSubcategory', 'pkjModel'])
|
||||
->where('pkj_category_id', $categoryId);
|
||||
|
||||
if ($status === '' || $status === 'null') {
|
||||
// Assets with status column NULL (not yet assigned a status)
|
||||
$query->whereNull('status');
|
||||
} else {
|
||||
// For specific status, must match exactly and NOT be null
|
||||
$query->whereNotNull('status')
|
||||
->where('status', '=', $status);
|
||||
}
|
||||
|
||||
$query->select([
|
||||
'id',
|
||||
'uuid',
|
||||
'registration_number',
|
||||
'kewpa_registration_number',
|
||||
'status',
|
||||
'unit_id',
|
||||
'pkj_category_id',
|
||||
'pkj_subcategory_id',
|
||||
'pkj_model_id',
|
||||
'purchase_date',
|
||||
'receipt_date',
|
||||
'purchase_price',
|
||||
'contract_reference',
|
||||
'country_of_manufacture',
|
||||
'economic_year',
|
||||
'economic_distance',
|
||||
'note',
|
||||
'engine_number',
|
||||
'chassis_number',
|
||||
'created_at',
|
||||
'updated_at'
|
||||
]);
|
||||
|
||||
// Apply visibility scoping if user is provided
|
||||
if ($user) {
|
||||
$query->visibleTo($user);
|
||||
}
|
||||
|
||||
// Apply filters
|
||||
if (isset($filters['unit_id'])) {
|
||||
$query->where('unit_id', $filters['unit_id']);
|
||||
}
|
||||
|
||||
$perPage = isset($filters['per_page']) ? (int) $filters['per_page'] : 10;
|
||||
$page = isset($filters['page']) ? (int) $filters['page'] : null;
|
||||
$assets = $query->paginate($perPage, ['*'], 'page', $page);
|
||||
|
||||
return [
|
||||
'data' => $assets->items(),
|
||||
'pagination' => [
|
||||
'current_page' => $assets->currentPage(),
|
||||
'per_page' => $assets->perPage(),
|
||||
'total' => $assets->total(),
|
||||
'last_page' => $assets->lastPage(),
|
||||
'from' => $assets->firstItem(),
|
||||
'to' => $assets->lastItem(),
|
||||
'has_more_pages' => $assets->hasMorePages()
|
||||
]
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply common filters to query
|
||||
*/
|
||||
private function applyFilters($query, array $filters = [], bool $excludeDateFilter = false): void
|
||||
{
|
||||
// Only apply created_at filter if the model has created_at column
|
||||
$model = $query->getModel();
|
||||
if ($model && method_exists($model, 'getTable')) {
|
||||
$schema = $model->getConnection()->getSchemaBuilder();
|
||||
$columns = $schema->getColumnListing($model->getTable());
|
||||
|
||||
if (!$excludeDateFilter && in_array('created_at', $columns)) {
|
||||
$dateRange = $this->getDateRange($filters);
|
||||
$query->whereBetween('created_at', [$dateRange['from'], $dateRange['to']]);
|
||||
}
|
||||
}
|
||||
|
||||
// Apply unit_id filter if model has unit_id column
|
||||
if (isset($filters['unit_id']) && $filters['unit_id']) {
|
||||
if ($model && method_exists($model, 'getTable')) {
|
||||
$columns = $schema->getColumnListing($model->getTable());
|
||||
if (in_array('unit_id', $columns)) {
|
||||
$query->where('unit_id', $filters['unit_id']);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Apply government_id filter if provided
|
||||
if (isset($filters['government_id']) && $filters['government_id']) {
|
||||
// Get units under the government
|
||||
$unitIds = $this->getUnitsByGovernment($filters['government_id']);
|
||||
|
||||
if ($model && method_exists($model, 'getTable')) {
|
||||
$columns = $schema->getColumnListing($model->getTable());
|
||||
if (in_array('unit_id', $columns)) {
|
||||
if (!empty($unitIds)) {
|
||||
$query->whereIn('unit_id', $unitIds);
|
||||
} else {
|
||||
// No units found for this government - return empty result
|
||||
$query->whereNull('id');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Apply formation_id filter if provided
|
||||
if (isset($filters['formation_id']) && $filters['formation_id']) {
|
||||
if ($model && method_exists($model, 'getTable')) {
|
||||
$columns = $schema->getColumnListing($model->getTable());
|
||||
if (in_array('unit_id', $columns)) {
|
||||
// Get units under this formation
|
||||
$unitIds = Unit::where('formation_id', $filters['formation_id'])
|
||||
->pluck('id')
|
||||
->toArray();
|
||||
|
||||
if (!empty($unitIds)) {
|
||||
$query->whereIn('unit_id', $unitIds);
|
||||
} else {
|
||||
// No units found for this formation - return empty result
|
||||
$query->whereNull('id');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Apply camp_id filter if provided
|
||||
if (isset($filters['camp_id']) && $filters['camp_id']) {
|
||||
if ($model && method_exists($model, 'getTable')) {
|
||||
$columns = $schema->getColumnListing($model->getTable());
|
||||
if (in_array('camp_id', $columns)) {
|
||||
$query->where('camp_id', $filters['camp_id']);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get units by government ID
|
||||
* Uses VisibilityService for consistent logic
|
||||
*/
|
||||
private function getUnitsByGovernment(int $governmentId): array
|
||||
{
|
||||
$governmentUnit = Unit::where('government_id', $governmentId)->first();
|
||||
if (!$governmentUnit) {
|
||||
// If no direct unit found, try to get from formation
|
||||
$formation = \Modules\Formation\Entities\Formation::where('government_id', $governmentId)->first();
|
||||
if ($formation) {
|
||||
$governmentUnit = Unit::where('formation_id', $formation->id)->first();
|
||||
}
|
||||
}
|
||||
|
||||
if (!$governmentUnit) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return $this->visibilityService->getUnitsUnderGovernment($governmentUnit);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get date range for filtering
|
||||
*/
|
||||
private function getDateRange(array $filters = []): array
|
||||
{
|
||||
$dateFrom = $filters['date_from'] ?? Carbon::now()->startOfYear();
|
||||
$dateTo = $filters['date_to'] ?? Carbon::now()->endOfYear();
|
||||
|
||||
return [
|
||||
'from' => Carbon::parse($dateFrom)->startOfDay(),
|
||||
'to' => Carbon::parse($dateTo)->endOfDay()
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Modules\Dashboard\Http\Controllers\DashboardController;
|
||||
use Modules\Dashboard\Http\Controllers\KJC\KJCDashboardController;
|
||||
use Modules\Dashboard\Http\Controllers\PKJ\PKJDashboardController;
|
||||
|
||||
Route::middleware(['auth:sanctum', 'single.session'])->prefix('v1')->group(function () {
|
||||
// Main dashboard endpoints
|
||||
Route::get('/dashboard/stat-cards', [DashboardController::class, 'getStatCards']);
|
||||
Route::get('/dashboard/overview', [DashboardController::class, 'getOverview']);
|
||||
|
||||
// KJC specific endpoints
|
||||
Route::prefix('dashboard/kjc')->group(function () {
|
||||
// Pie charts
|
||||
Route::get('/entitlement-vs-holdings-pie', [KJCDashboardController::class, 'getEntitlementVsHoldingsPieChart']);
|
||||
Route::get('/holdings-status-breakdown-pie', [KJCDashboardController::class, 'getHoldingsStatusBreakdownPieChart']);
|
||||
|
||||
// Bar charts
|
||||
Route::get('/historical-metrics-bar', [KJCDashboardController::class, 'getHistoricalMetricsBarChart']);
|
||||
|
||||
// Other charts
|
||||
Route::get('/unit-performance-chart', [KJCDashboardController::class, 'getUnitPerformanceChart']);
|
||||
Route::get('/monthly-trends-chart', [KJCDashboardController::class, 'getMonthlyTrendsChart']);
|
||||
|
||||
// Drill-down endpoints
|
||||
Route::get('/drill-down/entitlement-vs-holdings', [KJCDashboardController::class, 'getEntitlementVsHoldingsDetails']);
|
||||
Route::get('/drill-down/holdings-status', [KJCDashboardController::class, 'getHoldingsStatusDetails']);
|
||||
Route::get('/status/{status}/details', [KJCDashboardController::class, 'getAssetDetailsByStatus']);
|
||||
});
|
||||
|
||||
// PKJ specific endpoints
|
||||
Route::prefix('dashboard/pkj')->group(function () {
|
||||
Route::get('/entitlement-vs-holdings-pie', [PKJDashboardController::class, 'getEntitlementVsHoldingsPieChart']);
|
||||
Route::get('/holdings-status-breakdown-pie', [PKJDashboardController::class, 'getHoldingsStatusBreakdownPieChart']);
|
||||
Route::get('/monthly-trends', [PKJDashboardController::class, 'getMonthlyTrendsChart']);
|
||||
Route::get('/holdings-by-category-bar', [PKJDashboardController::class, 'getHoldingsByCategoryBarChart']);
|
||||
|
||||
// Drill-down endpoints
|
||||
Route::get('/category/{categoryId}/metrics-bar', [PKJDashboardController::class, 'getCategoryMetricsBarChart']);
|
||||
Route::get('/category/{categoryId}/status-breakdown-pie', [PKJDashboardController::class, 'getCategoryStatusBreakdownPieChart']);
|
||||
Route::get('/category/{categoryId}/status/{status}/details', [PKJDashboardController::class, 'getAssetDetailsByCategoryAndStatus']);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,486 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Dashboard\Services;
|
||||
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Modules\Unit\Entities\Unit;
|
||||
use Modules\Camp\Entities\Camp;
|
||||
use Modules\Formation\Entities\Formation;
|
||||
use App\Services\VisibilityService;
|
||||
|
||||
abstract class DashboardService
|
||||
{
|
||||
public function __construct(
|
||||
protected VisibilityService $visibilityService
|
||||
) {}
|
||||
/**
|
||||
* Get date range for filtering
|
||||
*/
|
||||
protected function getDateRange(array $filters = []): array
|
||||
{
|
||||
$dateFrom = $filters['date_from'] ?? Carbon::now()->startOfYear();
|
||||
$dateTo = $filters['date_to'] ?? Carbon::now()->endOfYear();
|
||||
|
||||
return [
|
||||
'from' => Carbon::parse($dateFrom)->startOfDay(),
|
||||
'to' => Carbon::parse($dateTo)->endOfDay()
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply common filters to query
|
||||
*/
|
||||
protected function applyCommonFilters($query, array $filters = []): void
|
||||
{
|
||||
$dateRange = $this->getDateRange($filters);
|
||||
|
||||
$query->whereBetween('created_at', [$dateRange['from'], $dateRange['to']]);
|
||||
|
||||
// Government filter: Filter by government (get all units under that government)
|
||||
if (isset($filters['government_id']) && $filters['government_id']) {
|
||||
$unitIds = $this->getUnitsByGovernment($filters['government_id']);
|
||||
|
||||
if (!empty($unitIds)) {
|
||||
$query->whereIn('unit_id', $unitIds);
|
||||
} else {
|
||||
// No units found for this government
|
||||
$query->whereNull('id');
|
||||
}
|
||||
}
|
||||
|
||||
if (isset($filters['unit_id']) && $filters['unit_id']) {
|
||||
$query->where('unit_id', $filters['unit_id']);
|
||||
}
|
||||
|
||||
if (isset($filters['camp_id']) && $filters['camp_id']) {
|
||||
$query->whereHas('unit', function ($q) use ($filters) {
|
||||
$q->where('camp_id', $filters['camp_id']);
|
||||
});
|
||||
}
|
||||
|
||||
if (isset($filters['formation_id']) && $filters['formation_id']) {
|
||||
$query->whereHas('unit', function ($q) use ($filters) {
|
||||
$q->where('formation_id', $filters['formation_id']);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply visibility scoping to query based on user permissions
|
||||
*/
|
||||
protected function applyVisibilityScoping($query, $user): void
|
||||
{
|
||||
if (!$user) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if the model has the HasVisibility trait
|
||||
if (method_exists($query->getModel(), 'scopeVisibleTo')) {
|
||||
$query->visibleTo($user);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply visibility scoping to raw database queries
|
||||
* Uses VisibilityService for consistent logic
|
||||
*/
|
||||
protected function applyRawVisibilityScoping($query, $user, string $tableName): void
|
||||
{
|
||||
if (!$user) {
|
||||
return;
|
||||
}
|
||||
|
||||
$userUnit = Unit::find($user->unit_id);
|
||||
if (!$userUnit) {
|
||||
$query->whereRaw('1 = 0');
|
||||
return;
|
||||
}
|
||||
|
||||
$unitIds = $this->visibilityService->getVisibleUnitIds($user);
|
||||
|
||||
if (empty($unitIds)) {
|
||||
$query->whereRaw('1 = 0');
|
||||
} else {
|
||||
$query->whereIn('unit_id', $unitIds);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all units by government ID
|
||||
* Uses VisibilityService for consistent logic
|
||||
*/
|
||||
protected function getUnitsByGovernment(int $governmentId): array
|
||||
{
|
||||
$governmentUnit = Unit::where('government_id', $governmentId)->first();
|
||||
if (!$governmentUnit) {
|
||||
// If no direct unit found, try to get from formation
|
||||
$formation = Formation::where('government_id', $governmentId)->first();
|
||||
if ($formation) {
|
||||
$governmentUnit = Unit::where('formation_id', $formation->id)->first();
|
||||
}
|
||||
}
|
||||
|
||||
if (!$governmentUnit) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return $this->visibilityService->getUnitsUnderGovernment($governmentUnit);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get total units count
|
||||
*/
|
||||
public function getTotalUnits(array $filters = []): int
|
||||
{
|
||||
$query = Unit::query();
|
||||
|
||||
if (isset($filters['camp_id']) && $filters['camp_id']) {
|
||||
$query->where('camp_id', $filters['camp_id']);
|
||||
}
|
||||
|
||||
if (isset($filters['formation_id']) && $filters['formation_id']) {
|
||||
$query->where('formation_id', $filters['formation_id']);
|
||||
}
|
||||
|
||||
return $query->count();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get total camps count
|
||||
*/
|
||||
public function getTotalCamps(array $filters = []): int
|
||||
{
|
||||
return Camp::count();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get total formations count
|
||||
*/
|
||||
public function getTotalFormations(array $filters = []): int
|
||||
{
|
||||
return Formation::count();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get active repairs count (to be implemented by child classes)
|
||||
*/
|
||||
abstract public function getActiveRepairs(array $filters = []): int;
|
||||
|
||||
/**
|
||||
* Get pending reports count (to be implemented by child classes)
|
||||
*/
|
||||
abstract public function getPendingReports(array $filters = []): int;
|
||||
|
||||
/**
|
||||
* Get total assets count (to be implemented by child classes)
|
||||
*/
|
||||
abstract public function getTotalAssets(array $filters = []): int;
|
||||
|
||||
/**
|
||||
* Get operational assets count (to be implemented by child classes)
|
||||
*/
|
||||
abstract public function getOperationalAssets(array $filters = []): int;
|
||||
|
||||
/**
|
||||
* Get under repair assets count (to be implemented by child classes)
|
||||
*/
|
||||
abstract public function getUnderRepairAssets(array $filters = []): int;
|
||||
|
||||
/**
|
||||
* Get maintenance due assets count (to be implemented by child classes)
|
||||
*/
|
||||
abstract public function getMaintenanceDueAssets(array $filters = []): int;
|
||||
|
||||
/**
|
||||
* Format chart data with common structure
|
||||
*/
|
||||
protected function formatChartData(
|
||||
string $chartType,
|
||||
string $title,
|
||||
array $series,
|
||||
array $categories = [],
|
||||
array $drillDown = []
|
||||
): array {
|
||||
return [
|
||||
'chart_type' => $chartType,
|
||||
'title' => $title,
|
||||
'series' => $series,
|
||||
'categories' => $categories,
|
||||
'drill_down' => $drillDown
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Format pie chart data
|
||||
*/
|
||||
protected function formatPieChartData(
|
||||
string $title,
|
||||
array $data,
|
||||
string $drillDownEndpoint = '',
|
||||
array $drillDownParameters = []
|
||||
): array {
|
||||
$total = array_sum(array_column($data, 'value'));
|
||||
$series = [];
|
||||
|
||||
foreach ($data as $item) {
|
||||
$percentage = $total > 0 ? round(($item['value'] / $total) * 100, 1) : 0;
|
||||
|
||||
$seriesItem = [
|
||||
'name' => $item['name'],
|
||||
'value' => $item['value'],
|
||||
'percentage' => $percentage
|
||||
];
|
||||
|
||||
// Preserve status_code if it exists (for drill-down functionality)
|
||||
if (isset($item['status_code'])) {
|
||||
$seriesItem['status_code'] = $item['status_code'];
|
||||
}
|
||||
|
||||
$series[] = $seriesItem;
|
||||
}
|
||||
|
||||
return $this->formatChartData(
|
||||
'pie',
|
||||
$title,
|
||||
$series,
|
||||
[],
|
||||
[
|
||||
'enabled' => !empty($drillDownEndpoint),
|
||||
'endpoint' => $drillDownEndpoint,
|
||||
'parameters' => $drillDownParameters
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Format bar chart data
|
||||
*/
|
||||
protected function formatBarChartData(
|
||||
string $title,
|
||||
array $series,
|
||||
array $categories,
|
||||
string $drillDownEndpoint = '',
|
||||
array $drillDownParameters = []
|
||||
): array {
|
||||
return $this->formatChartData(
|
||||
'bar',
|
||||
$title,
|
||||
$series,
|
||||
$categories,
|
||||
[
|
||||
'enabled' => !empty($drillDownEndpoint),
|
||||
'endpoint' => $drillDownEndpoint,
|
||||
'parameters' => $drillDownParameters
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Format line chart data
|
||||
*/
|
||||
protected function formatLineChartData(
|
||||
string $title,
|
||||
array $series,
|
||||
array $categories,
|
||||
string $drillDownEndpoint = '',
|
||||
array $drillDownParameters = []
|
||||
): array {
|
||||
return $this->formatChartData(
|
||||
'line',
|
||||
$title,
|
||||
$series,
|
||||
$categories,
|
||||
[
|
||||
'enabled' => !empty($drillDownEndpoint),
|
||||
'endpoint' => $drillDownEndpoint,
|
||||
'parameters' => $drillDownParameters
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get monthly categories for date range
|
||||
*/
|
||||
protected function getMonthlyCategories(array $filters = []): array
|
||||
{
|
||||
$dateRange = $this->getDateRange($filters);
|
||||
$categories = [];
|
||||
|
||||
$current = $dateRange['from']->copy()->startOfMonth();
|
||||
$end = $dateRange['to']->copy()->endOfMonth();
|
||||
|
||||
while ($current->lte($end)) {
|
||||
$categories[] = $current->format('M Y');
|
||||
$current->addMonth();
|
||||
}
|
||||
|
||||
return $categories;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get weekly categories for date range
|
||||
*/
|
||||
protected function getWeeklyCategories(array $filters = []): array
|
||||
{
|
||||
$dateRange = $this->getDateRange($filters);
|
||||
$categories = [];
|
||||
|
||||
$current = $dateRange['from']->copy()->startOfWeek();
|
||||
$end = $dateRange['to']->copy()->endOfWeek();
|
||||
|
||||
while ($current->lte($end)) {
|
||||
$categories[] = 'Week ' . $current->weekOfYear . ' ' . $current->year;
|
||||
$current->addWeek();
|
||||
}
|
||||
|
||||
return $categories;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get daily categories for date range
|
||||
*/
|
||||
protected function getDailyCategories(array $filters = []): array
|
||||
{
|
||||
$dateRange = $this->getDateRange($filters);
|
||||
$categories = [];
|
||||
|
||||
$current = $dateRange['from']->copy();
|
||||
$end = $dateRange['to']->copy();
|
||||
|
||||
while ($current->lte($end)) {
|
||||
$categories[] = $current->format('M d');
|
||||
$current->addDay();
|
||||
}
|
||||
|
||||
return $categories;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate percentage change
|
||||
*/
|
||||
protected function calculatePercentageChange(int $current, int $previous): float
|
||||
{
|
||||
if ($previous === 0) {
|
||||
return $current > 0 ? 100.0 : 0.0;
|
||||
}
|
||||
|
||||
return round((($current - $previous) / $previous) * 100, 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get status color mapping
|
||||
*/
|
||||
protected function getStatusColors(): array
|
||||
{
|
||||
return [
|
||||
'operational' => '#4caf50',
|
||||
'under_repair' => '#ff9800',
|
||||
'maintenance_due' => '#f44336',
|
||||
'out_of_service' => '#9e9e9e',
|
||||
'completed' => '#4caf50',
|
||||
'pending' => '#ff9800',
|
||||
'in_progress' => '#2196f3',
|
||||
'cancelled' => '#f44336'
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get priority color mapping
|
||||
*/
|
||||
protected function getPriorityColors(): array
|
||||
{
|
||||
return [
|
||||
'high' => '#f44336',
|
||||
'medium' => '#ff9800',
|
||||
'low' => '#4caf50'
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Format currency
|
||||
*/
|
||||
protected function formatCurrency(float $amount): string
|
||||
{
|
||||
return 'RM ' . number_format($amount, 2);
|
||||
}
|
||||
|
||||
/**
|
||||
* Format duration in hours
|
||||
*/
|
||||
protected function formatDuration(float $hours): string
|
||||
{
|
||||
if ($hours < 24) {
|
||||
return round($hours, 1) . ' hours';
|
||||
}
|
||||
|
||||
$days = floor($hours / 24);
|
||||
$remainingHours = $hours % 24;
|
||||
|
||||
if ($remainingHours > 0) {
|
||||
return $days . ' days ' . round($remainingHours, 1) . ' hours';
|
||||
}
|
||||
|
||||
return $days . ' days';
|
||||
}
|
||||
|
||||
/**
|
||||
* Get common drill-down parameters
|
||||
*/
|
||||
protected function getCommonDrillDownParameters(): array
|
||||
{
|
||||
return ['date_from', 'date_to', 'unit_id', 'camp_id', 'formation_id'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Build drill-down endpoint
|
||||
*/
|
||||
protected function buildDrillDownEndpoint(string $baseEndpoint, array $parameters = []): string
|
||||
{
|
||||
$endpoint = $baseEndpoint;
|
||||
|
||||
if (!empty($parameters)) {
|
||||
$endpoint .= '?' . http_build_query($parameters);
|
||||
}
|
||||
|
||||
return $endpoint;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get summary statistics for drill-down
|
||||
*/
|
||||
protected function getSummaryStatistics($query, array $filters = []): array
|
||||
{
|
||||
$total = $query->count();
|
||||
|
||||
// Get breakdown by unit
|
||||
$byUnit = $query->clone()
|
||||
->join('units', function ($join) {
|
||||
$join->on('units.id', '=', $this->getUnitIdColumn());
|
||||
})
|
||||
->selectRaw('units.name as unit_name, COUNT(*) as count')
|
||||
->groupBy('units.name')
|
||||
->get()
|
||||
->toArray();
|
||||
|
||||
return [
|
||||
'total' => $total,
|
||||
'by_unit' => $byUnit
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get unit ID column name (to be implemented by child classes)
|
||||
*/
|
||||
abstract protected function getUnitIdColumn(): string;
|
||||
|
||||
/**
|
||||
* Get asset model class (to be implemented by child classes)
|
||||
*/
|
||||
abstract protected function getAssetModelClass(): string;
|
||||
|
||||
/**
|
||||
* Get repair model class (to be implemented by child classes)
|
||||
*/
|
||||
abstract protected function getRepairModelClass(): string;
|
||||
}
|
||||
@@ -0,0 +1,315 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Dashboard\Services\KJC;
|
||||
|
||||
use Modules\Dashboard\Services\DashboardService;
|
||||
use Modules\Dashboard\Repositories\Contracts\KJCDashboardRepositoryInterface;
|
||||
use Modules\KJCRepair\Entities\KJCRepair;
|
||||
use Modules\KJCReport\Entities\KJCReport;
|
||||
use Modules\Unit\Entities\Unit;
|
||||
use App\Services\VisibilityService;
|
||||
use Carbon\Carbon;
|
||||
|
||||
class KJCDashboardService extends DashboardService
|
||||
{
|
||||
protected KJCDashboardRepositoryInterface $kjcDashboardRepository;
|
||||
|
||||
public function __construct(
|
||||
VisibilityService $visibilityService,
|
||||
KJCDashboardRepositoryInterface $kjcDashboardRepository
|
||||
) {
|
||||
parent::__construct($visibilityService);
|
||||
$this->kjcDashboardRepository = $kjcDashboardRepository;
|
||||
}
|
||||
/**
|
||||
* Get total KJC assets count
|
||||
*/
|
||||
public function getTotalAssets(array $filters = [], $user = null): int
|
||||
{
|
||||
return $this->kjcDashboardRepository->getTotalHoldings($filters, $user);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get operational KJC assets count (BP status)
|
||||
*/
|
||||
public function getOperationalAssets(array $filters = [], $user = null): int
|
||||
{
|
||||
$holdings = $this->kjcDashboardRepository->getHoldingsBySpecificStatus('BP', $filters, $user);
|
||||
return $holdings['pagination']['total'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get under repair KJC assets count (BDG status)
|
||||
*/
|
||||
public function getUnderRepairAssets(array $filters = [], $user = null): int
|
||||
{
|
||||
$holdings = $this->kjcDashboardRepository->getHoldingsBySpecificStatus('BDG', $filters, $user);
|
||||
return $holdings['pagination']['total'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get maintenance due KJC assets count (TBDG status)
|
||||
*/
|
||||
public function getMaintenanceDueAssets(array $filters = [], $user = null): int
|
||||
{
|
||||
$holdings = $this->kjcDashboardRepository->getHoldingsBySpecificStatus('TBDG', $filters, $user);
|
||||
return $holdings['pagination']['total'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get active KJC repairs count
|
||||
*/
|
||||
public function getActiveRepairs(array $filters = []): int
|
||||
{
|
||||
$query = KJCRepair::whereIn('status', ['pending', 'in_progress']);
|
||||
$this->applyCommonFilters($query, $filters);
|
||||
|
||||
return $query->count();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get pending KJC reports count
|
||||
*/
|
||||
public function getPendingReports(array $filters = []): int
|
||||
{
|
||||
$query = KJCReport::where('status', 'pending');
|
||||
$this->applyCommonFilters($query, $filters);
|
||||
|
||||
return $query->count();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get KJC entitlement vs holdings pie chart
|
||||
*/
|
||||
public function getEntitlementVsHoldingsPieChart(array $filters = [], $user = null): array
|
||||
{
|
||||
// Get total entitlement
|
||||
$totalEntitlement = $this->kjcDashboardRepository->getTotalEntitlement($filters, $user);
|
||||
|
||||
// Get total holdings
|
||||
$totalHoldings = $this->kjcDashboardRepository->getTotalHoldings($filters, $user);
|
||||
|
||||
// Prepare data for pie chart (only showing Perjawatan and Pegangan)
|
||||
$data = [
|
||||
[
|
||||
'name' => 'Perjawatan',
|
||||
'value' => $totalEntitlement,
|
||||
'color' => '#4caf50'
|
||||
],
|
||||
[
|
||||
'name' => 'Pegangan',
|
||||
'value' => $totalHoldings,
|
||||
'color' => '#2196f3'
|
||||
]
|
||||
];
|
||||
|
||||
return $this->formatPieChartData(
|
||||
'Perjawatan vs Pegangan KJC',
|
||||
$data,
|
||||
'/v1/dashboard/kjc/drill-down/entitlement-vs-holdings',
|
||||
['type']
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get KJC holdings status breakdown pie chart
|
||||
*/
|
||||
public function getHoldingsStatusBreakdownPieChart(array $filters = [], $user = null): array
|
||||
{
|
||||
$statusCounts = $this->kjcDashboardRepository->getHoldingsByStatus($filters, $user);
|
||||
|
||||
$statusNames = [
|
||||
'BP' => 'BP',
|
||||
'BDG' => 'BDG',
|
||||
'TBDG' => 'TBDG',
|
||||
'BT' => 'BT',
|
||||
'TBT' => 'TBT',
|
||||
'BG' => 'BG',
|
||||
'TBG' => 'TBG',
|
||||
];
|
||||
|
||||
$data = [];
|
||||
foreach ($statusCounts as $item) {
|
||||
$statusCode = $item['status'];
|
||||
if ($statusCode === null || $statusCode === '') {
|
||||
$statusName = 'Belum Diberi Status';
|
||||
} else {
|
||||
$statusName = $statusNames[$statusCode] ?? $statusCode;
|
||||
}
|
||||
$data[] = [
|
||||
'name' => $statusName,
|
||||
'value' => $item['count'],
|
||||
'percentage' => 0,
|
||||
'status_code' => $statusCode,
|
||||
];
|
||||
}
|
||||
|
||||
// Calculate percentages
|
||||
$total = array_sum(array_column($data, 'value'));
|
||||
foreach ($data as &$row) {
|
||||
$row['percentage'] = $total > 0 ? round(($row['value'] / $total) * 100, 2) : 0;
|
||||
}
|
||||
|
||||
return $this->formatPieChartData(
|
||||
'KJC Status Pegangan',
|
||||
$data,
|
||||
'/v1/dashboard/kjc/drill-down/holdings-status',
|
||||
['status']
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get KJC unit performance chart
|
||||
*/
|
||||
public function getUnitPerformanceChart(array $filters = []): array
|
||||
{
|
||||
$units = Unit::withCount([
|
||||
'kjcAssetHoldings as bp_count' => function ($query) use ($filters) {
|
||||
$query->where('status', 'BP');
|
||||
$this->applyCommonFilters($query, $filters);
|
||||
},
|
||||
'kjcAssetHoldings as bdg_count' => function ($query) use ($filters) {
|
||||
$query->where('status', 'BDG');
|
||||
$this->applyCommonFilters($query, $filters);
|
||||
},
|
||||
'kjcAssetHoldings as tbdg_count' => function ($query) use ($filters) {
|
||||
$query->where('status', 'TBDG');
|
||||
$this->applyCommonFilters($query, $filters);
|
||||
}
|
||||
])->get();
|
||||
|
||||
$unitNames = [];
|
||||
$bpCounts = [];
|
||||
$bdgCounts = [];
|
||||
$tbdgCounts = [];
|
||||
|
||||
foreach ($units as $unit) {
|
||||
$unitNames[] = $unit->name;
|
||||
$bpCounts[] = $unit->bp_count;
|
||||
$bdgCounts[] = $unit->bdg_count;
|
||||
$tbdgCounts[] = $unit->tbdg_count;
|
||||
}
|
||||
|
||||
return $this->formatBarChartData(
|
||||
'KJC Unit 2025',
|
||||
[
|
||||
['name' => 'Baik dalam Perhatian (BP)', 'data' => $bpCounts],
|
||||
['name' => 'Boleh Digunakan (BDG)', 'data' => $bdgCounts],
|
||||
['name' => 'Tidak Boleh Digunakan (TBDG)', 'data' => $tbdgCounts]
|
||||
],
|
||||
$unitNames,
|
||||
'/v1/dashboard/kjc/drill-down/unit-performance',
|
||||
['unit_id']
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get KJC monthly trends chart
|
||||
*/
|
||||
public function getMonthlyTrendsChart(array $filters = [], $user = null): array
|
||||
{
|
||||
$dateRange = $this->getDateRange($filters);
|
||||
$categories = $this->getMonthlyCategories($filters);
|
||||
|
||||
$monthlyData = $this->kjcDashboardRepository->getMonthlyTrends($filters, $user);
|
||||
|
||||
// Initialize data arrays
|
||||
$bpData = array_fill(0, count($categories), 0);
|
||||
$bdgData = array_fill(0, count($categories), 0);
|
||||
$tbdgData = array_fill(0, count($categories), 0);
|
||||
|
||||
// Fill data arrays
|
||||
foreach ($monthlyData as $item) {
|
||||
$index = array_search($item['month'], $categories);
|
||||
if ($index !== false) {
|
||||
switch ($item['status']) {
|
||||
case 'BP':
|
||||
$bpData[$index] = $item['count'];
|
||||
break;
|
||||
case 'BDG':
|
||||
$bdgData[$index] = $item['count'];
|
||||
break;
|
||||
case 'TBDG':
|
||||
$tbdgData[$index] = $item['count'];
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $this->formatLineChartData(
|
||||
'KJC Trend Bulanan 2025',
|
||||
[
|
||||
['name' => 'Baik dalam Perhatian (BP)', 'data' => $bpData],
|
||||
['name' => 'Boleh Digunakan (BDG)', 'data' => $bdgData],
|
||||
['name' => 'Tidak Boleh Digunakan (TBDG)', 'data' => $tbdgData]
|
||||
],
|
||||
$categories,
|
||||
'/v1/dashboard/kjc/drill-down/monthly-trends',
|
||||
['month', 'status']
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get KJC historical metrics bar chart (KEUPAYAAN, KESIAGAAN, SERVISIBILITI)
|
||||
*/
|
||||
public function getHistoricalMetricsBarChart(array $filters = [], $user = null): array
|
||||
{
|
||||
$monthlyData = $this->kjcDashboardRepository->getHistoricalMetricsByMonth($filters, $user);
|
||||
|
||||
// Extract data for chart
|
||||
$categories = [];
|
||||
$keupayaanData = [];
|
||||
$kesiagaanData = [];
|
||||
$servisibilitiData = [];
|
||||
|
||||
foreach ($monthlyData as $data) {
|
||||
$monthDate = Carbon::createFromFormat('Y-m', $data['month']);
|
||||
$categories[] = $monthDate->format('M'); // Remove year from categories
|
||||
$keupayaanData[] = $data['keupayaan'];
|
||||
$kesiagaanData[] = $data['kesiagaan'];
|
||||
$servisibilitiData[] = $data['servisibiliti'];
|
||||
}
|
||||
|
||||
// Use year from user selection (date_from/date_to) or fall back to current year
|
||||
$year = Carbon::now()->year;
|
||||
if (!empty($filters['date_from'])) {
|
||||
$year = Carbon::parse($filters['date_from'])->year;
|
||||
} elseif (!empty($filters['date_to'])) {
|
||||
$year = Carbon::parse($filters['date_to'])->year;
|
||||
}
|
||||
|
||||
return $this->formatBarChartData(
|
||||
"Metrik Tahunan KJC {$year}",
|
||||
[
|
||||
['name' => 'KEUPAYAAN (%)', 'data' => $keupayaanData],
|
||||
['name' => 'KESIAGAAN (%)', 'data' => $kesiagaanData],
|
||||
['name' => 'SERVISIBILITI (%)', 'data' => $servisibilitiData]
|
||||
],
|
||||
$categories
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get unit ID column name for KJC
|
||||
*/
|
||||
protected function getUnitIdColumn(): string
|
||||
{
|
||||
return 'kjc_asset_holdings.unit_id';
|
||||
}
|
||||
|
||||
/**
|
||||
* Get asset model class for KJC
|
||||
*/
|
||||
protected function getAssetModelClass(): string
|
||||
{
|
||||
return KJCAssetHolding::class;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get repair model class for KJC
|
||||
*/
|
||||
protected function getRepairModelClass(): string
|
||||
{
|
||||
return KJCRepair::class;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,319 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Dashboard\Services\PKJ;
|
||||
|
||||
use Modules\Dashboard\Services\DashboardService;
|
||||
use Modules\Dashboard\Repositories\Contracts\PKJDashboardRepositoryInterface;
|
||||
use Modules\PKJAssetEntitlement\Entities\PKJAssetEntitlement;
|
||||
use Modules\PKJAssetHolding\Entities\PKJAssetHolding;
|
||||
use Modules\PKJRepair\Entities\PKJRepair;
|
||||
use Modules\PKJReport\Entities\PKJReport;
|
||||
use App\Services\VisibilityService;
|
||||
use Carbon\Carbon;
|
||||
|
||||
class PKJDashboardService extends DashboardService
|
||||
{
|
||||
protected PKJDashboardRepositoryInterface $pkjDashboardRepository;
|
||||
|
||||
public function __construct(
|
||||
VisibilityService $visibilityService,
|
||||
PKJDashboardRepositoryInterface $pkjDashboardRepository
|
||||
) {
|
||||
parent::__construct($visibilityService);
|
||||
$this->pkjDashboardRepository = $pkjDashboardRepository;
|
||||
}
|
||||
/**
|
||||
* Get total PKJ assets
|
||||
*/
|
||||
public function getTotalAssets(array $filters = [], $user = null): int
|
||||
{
|
||||
return $this->pkjDashboardRepository->getTotalHoldings($filters, $user);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get operational PKJ assets (BP status)
|
||||
*/
|
||||
public function getOperationalAssets(array $filters = [], $user = null): int
|
||||
{
|
||||
$holdings = $this->pkjDashboardRepository->getHoldingsBySpecificStatus('BP', $filters, $user);
|
||||
return $holdings['pagination']['total'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get under repair PKJ assets (TBDG status)
|
||||
*/
|
||||
public function getUnderRepairAssets(array $filters = [], $user = null): int
|
||||
{
|
||||
$holdings = $this->pkjDashboardRepository->getHoldingsBySpecificStatus('TBDG', $filters, $user);
|
||||
return $holdings['pagination']['total'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get maintenance due PKJ assets (BDG status)
|
||||
*/
|
||||
public function getMaintenanceDueAssets(array $filters = [], $user = null): int
|
||||
{
|
||||
$holdings = $this->pkjDashboardRepository->getHoldingsBySpecificStatus('BDG', $filters, $user);
|
||||
return $holdings['pagination']['total'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get active PKJ repairs
|
||||
*/
|
||||
public function getActiveRepairs(array $filters = []): int
|
||||
{
|
||||
$dateRange = $this->getDateRange($filters);
|
||||
|
||||
return PKJRepair::query()
|
||||
->whereBetween('created_at', [$dateRange['from'], $dateRange['to']])
|
||||
->where('status', 'active')
|
||||
->count();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get pending PKJ reports
|
||||
*/
|
||||
public function getPendingReports(array $filters = []): int
|
||||
{
|
||||
$dateRange = $this->getDateRange($filters);
|
||||
|
||||
return PKJReport::query()
|
||||
->whereBetween('created_at', [$dateRange['from'], $dateRange['to']])
|
||||
->where('status', 'pending')
|
||||
->count();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get PKJ entitlement vs holdings pie chart
|
||||
*/
|
||||
public function getEntitlementVsHoldingsPieChart(array $filters = [], $user = null): array
|
||||
{
|
||||
$totalEntitlement = $this->pkjDashboardRepository->getTotalEntitlement($filters, $user);
|
||||
$totalHoldings = $this->pkjDashboardRepository->getTotalHoldings($filters, $user);
|
||||
|
||||
$data = [
|
||||
[
|
||||
'name' => 'Perjawatan',
|
||||
'value' => $totalEntitlement,
|
||||
'percentage' => ($totalEntitlement + $totalHoldings) > 0 ? round(($totalEntitlement / ($totalEntitlement + $totalHoldings)) * 100, 2) : 0
|
||||
],
|
||||
[
|
||||
'name' => 'Pegangan',
|
||||
'value' => $totalHoldings,
|
||||
'percentage' => ($totalEntitlement + $totalHoldings) > 0 ? round(($totalHoldings / ($totalEntitlement + $totalHoldings)) * 100, 2) : 0
|
||||
]
|
||||
];
|
||||
|
||||
return $this->formatPieChartData(
|
||||
'Perjawatan vs Pegangan PKJ',
|
||||
$data,
|
||||
'', // No drill-down
|
||||
[]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get PKJ holdings status breakdown pie chart
|
||||
*/
|
||||
public function getHoldingsStatusBreakdownPieChart(array $filters = [], $user = null): array
|
||||
{
|
||||
$statusCounts = $this->pkjDashboardRepository->getHoldingsByStatus($filters, $user);
|
||||
|
||||
// Map status codes to readable names
|
||||
$statusNames = [
|
||||
'BP' => 'Baik dalam Perhatian',
|
||||
'BDG' => 'Boleh Digunakan',
|
||||
'TBDG' => 'Tidak Boleh Digunakan',
|
||||
'BT' => 'Boleh Tembak',
|
||||
'BG' => 'Baik Guna'
|
||||
];
|
||||
|
||||
$data = [];
|
||||
foreach ($statusCounts as $status) {
|
||||
$statusName = $statusNames[$status['status']] ?? $status['status'];
|
||||
$data[] = [
|
||||
'name' => $statusName,
|
||||
'value' => $status['count'],
|
||||
'percentage' => 0 // Will be calculated after total
|
||||
];
|
||||
}
|
||||
|
||||
// Calculate percentages
|
||||
$total = array_sum(array_column($data, 'value'));
|
||||
foreach ($data as &$item) {
|
||||
$item['percentage'] = $total > 0 ? round(($item['value'] / $total) * 100, 2) : 0;
|
||||
}
|
||||
|
||||
return $this->formatPieChartData(
|
||||
'PKJ Status Pegangan',
|
||||
$data,
|
||||
'', // No drill-down
|
||||
[]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get PKJ monthly trends chart
|
||||
*/
|
||||
public function getMonthlyTrendsChart(array $filters = [], $user = null): array
|
||||
{
|
||||
$monthlyData = $this->pkjDashboardRepository->getMonthlyTrends($filters, $user);
|
||||
|
||||
$categories = [];
|
||||
$data = [];
|
||||
|
||||
foreach ($monthlyData as $trend) {
|
||||
$categories[] = Carbon::createFromFormat('Y-m', $trend['month'])->format('M Y');
|
||||
$data[] = $trend['total_reports'];
|
||||
}
|
||||
|
||||
return $this->formatBarChartData(
|
||||
'Trend Bulanan PKJ 2025',
|
||||
[
|
||||
['name' => 'Laporan', 'data' => $data]
|
||||
],
|
||||
$categories
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get PKJ holdings by category bar chart
|
||||
*/
|
||||
public function getHoldingsByCategoryBarChart(array $filters = [], $user = null): array
|
||||
{
|
||||
$categoryData = $this->pkjDashboardRepository->getHoldingsByCategory($filters, $user);
|
||||
|
||||
$categories = [];
|
||||
$categoryIds = [];
|
||||
$data = [];
|
||||
|
||||
foreach ($categoryData as $category) {
|
||||
$categories[] = $category['category_name'];
|
||||
$categoryIds[] = (int) $category['category_id'];
|
||||
$data[] = (int) $category['total_holding'];
|
||||
}
|
||||
|
||||
$chartData = $this->formatBarChartData(
|
||||
'Pegangan PKJ Mengikut Kategori',
|
||||
[
|
||||
['name' => 'Jumlah Pegangan', 'data' => $data]
|
||||
],
|
||||
$categories
|
||||
);
|
||||
|
||||
// Add category IDs to the chart data for drill-down functionality
|
||||
$chartData['category_ids'] = $categoryIds;
|
||||
|
||||
return $chartData;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get PKJ category metrics bar chart (drill-down)
|
||||
*/
|
||||
public function getCategoryMetricsBarChart(int $categoryId, array $filters = [], $user = null): array
|
||||
{
|
||||
$metrics = $this->pkjDashboardRepository->getCategoryMetrics($categoryId, $filters, $user);
|
||||
|
||||
$categories = ['KEUPAYAAN (%)', 'KESIAGAAN (%)', 'SERVISIBILITI (%)'];
|
||||
$data = [
|
||||
$metrics['keupayaan'],
|
||||
$metrics['kesiagaan'],
|
||||
$metrics['servisibiliti']
|
||||
];
|
||||
|
||||
$chartData = $this->formatBarChartData(
|
||||
'Metrik Kategori PKJ',
|
||||
[
|
||||
['name' => 'Metrics', 'data' => $data]
|
||||
],
|
||||
$categories
|
||||
);
|
||||
|
||||
// Add category information to the response
|
||||
$chartData['category_id'] = $metrics['category_id'];
|
||||
$chartData['category_name'] = $metrics['category_name'];
|
||||
|
||||
return $chartData;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get PKJ category status breakdown pie chart (drill-down)
|
||||
*/
|
||||
public function getCategoryStatusBreakdownPieChart(int $categoryId, array $filters = [], $user = null): array
|
||||
{
|
||||
$breakdown = $this->pkjDashboardRepository->getCategoryStatusBreakdown($categoryId, $filters, $user);
|
||||
|
||||
// Map status codes to readable names
|
||||
$statusNames = [
|
||||
'BP' => 'Baik dalam Perhatian',
|
||||
'BDG' => 'Boleh Digunakan',
|
||||
'TBDG' => 'Tidak Boleh Digunakan',
|
||||
'BT' => 'Boleh Tembak',
|
||||
'TBT' => 'Tidak Boleh Tembak',
|
||||
'BG' => 'Baik Guna',
|
||||
'TBG' => 'Tidak Baik Guna',
|
||||
];
|
||||
|
||||
$data = [];
|
||||
foreach ($breakdown['status_breakdown'] as $status) {
|
||||
$statusCode = $status['status'];
|
||||
|
||||
// In the breakdown, status_code is null when the asset has no status (DB column is NULL).
|
||||
if ($statusCode === null || $statusCode === '') {
|
||||
$statusName = 'Status Tidak Diketahui';
|
||||
} else {
|
||||
$statusName = $statusNames[$statusCode] ?? $statusCode;
|
||||
}
|
||||
|
||||
$data[] = [
|
||||
'name' => $statusName,
|
||||
'value' => $status['count'],
|
||||
'percentage' => 0, // Will be calculated after total
|
||||
'status_code' => $statusCode // null when DB status column is NULL (Belum Diberi Status)
|
||||
];
|
||||
}
|
||||
|
||||
// Calculate percentages
|
||||
$total = array_sum(array_column($data, 'value'));
|
||||
foreach ($data as &$item) {
|
||||
$item['percentage'] = $total > 0 ? round(($item['value'] / $total) * 100, 2) : 0;
|
||||
}
|
||||
|
||||
$chartData = $this->formatPieChartData(
|
||||
'PKJ Status Pegangan Mengikut Kategori',
|
||||
$data,
|
||||
'/v1/dashboard/pkj/category/' . $categoryId . '/status-details',
|
||||
['status']
|
||||
);
|
||||
|
||||
// Add category information to the response
|
||||
$chartData['category_id'] = $breakdown['category_id'];
|
||||
$chartData['category_name'] = $breakdown['category_name'];
|
||||
|
||||
return $chartData;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get unit ID column name for PKJ
|
||||
*/
|
||||
protected function getUnitIdColumn(): string
|
||||
{
|
||||
return 'pkj_asset_holdings.unit_id';
|
||||
}
|
||||
|
||||
/**
|
||||
* Get asset model class for PKJ
|
||||
*/
|
||||
protected function getAssetModelClass(): string
|
||||
{
|
||||
return PKJAssetHolding::class;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get repair model class for PKJ
|
||||
*/
|
||||
protected function getRepairModelClass(): string
|
||||
{
|
||||
return PKJRepair::class;
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"name": "nwidart/investment",
|
||||
"name": "nwidart/dashboard",
|
||||
"description": "",
|
||||
"authors": [
|
||||
{
|
||||
@@ -10,21 +10,19 @@
|
||||
"extra": {
|
||||
"laravel": {
|
||||
"providers": [],
|
||||
"aliases": {
|
||||
|
||||
}
|
||||
"aliases": {}
|
||||
}
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"Modules\\Investment\\": "App",
|
||||
"Modules\\Investment\\Database\\Factories\\": "database/factories/",
|
||||
"Modules\\Investment\\Database\\Seeders\\": "database/seeders/"
|
||||
"Modules\\Dashboard\\": "App",
|
||||
"Modules\\Dashboard\\Database\\Factories\\": "database/factories/",
|
||||
"Modules\\Dashboard\\Database\\Seeders\\": "database/seeders/"
|
||||
}
|
||||
},
|
||||
"autoload-dev": {
|
||||
"psr-4": {
|
||||
"Modules\\Investment\\Tests\\": "tests/"
|
||||
"Modules\\Dashboard\\Tests\\": "tests/"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"name": "Dashboard",
|
||||
"alias": "dashboard",
|
||||
"description": "",
|
||||
"keywords": [],
|
||||
"priority": 0,
|
||||
"providers": [
|
||||
"Modules\\Dashboard\\Providers\\DashboardServiceProvider"
|
||||
],
|
||||
"files": []
|
||||
}
|
||||
@@ -113,6 +113,10 @@ class ExternalSystemServiceProvider extends ServiceProvider
|
||||
*/
|
||||
protected function merge_config_from(string $path, string $key): void
|
||||
{
|
||||
if ($this->app->configurationIsCached()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$existing = config($key, []);
|
||||
$module_config = require $path;
|
||||
|
||||
|
||||
@@ -117,6 +117,10 @@ class FeedbackServiceProvider extends ServiceProvider
|
||||
*/
|
||||
protected function merge_config_from(string $path, string $key): void
|
||||
{
|
||||
if ($this->app->configurationIsCached()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$existing = config($key, []);
|
||||
$module_config = require $path;
|
||||
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
<?php
|
||||
|
||||
return [
|
||||
'name' => 'Investment',
|
||||
|
||||
'billplz' => [
|
||||
'api_key' => env('BILLPLZ_API_KEY'),
|
||||
'x_signature_key' => env('BILLPLZ_X_SIGNATURE_KEY'),
|
||||
'collection_id' => env('BILLPLZ_COLLECTION_ID'),
|
||||
'base_url' => rtrim(env('BILLPLZ_BASE_URL', 'https://www.billplz-sandbox.com/api/v3'), '/'),
|
||||
'callback_url' => env('BILLPLZ_CALLBACK_URL'),
|
||||
'redirect_url' => env('BILLPLZ_REDIRECT_URL'),
|
||||
],
|
||||
];
|
||||
-46
@@ -1,46 +0,0 @@
|
||||
<?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::create('investment_types', function (Blueprint $table) {
|
||||
$table->uuid('id')->primary();
|
||||
|
||||
$table->string('code');
|
||||
$table->index('code');
|
||||
$table->string('name');
|
||||
$table->text('description')->nullable();
|
||||
|
||||
$table->string('status')->default('ACTIVE');
|
||||
|
||||
$table->decimal('minimum_amount', 15, 2)->default(0);
|
||||
$table->decimal('maximum_amount', 15, 2)->nullable();
|
||||
$table->decimal('total_fund_limit', 15, 2)->nullable();
|
||||
$table->decimal('reserved_amount', 15, 2)->default(0);
|
||||
|
||||
$table->date('start_date')->nullable();
|
||||
$table->date('end_date')->nullable();
|
||||
|
||||
$table->boolean('allow_billplz')->default(true);
|
||||
$table->boolean('allow_salary_deduction')->default(false);
|
||||
|
||||
$table->string('billplz_collection_id')->nullable();
|
||||
|
||||
$table->foreignUuid('created_by')->nullable()->constrained('users')->nullOnDelete();
|
||||
$table->foreignUuid('updated_by')->nullable()->constrained('users')->nullOnDelete();
|
||||
|
||||
$table->timestamps();
|
||||
$table->softDeletes();
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('investment_types');
|
||||
}
|
||||
};
|
||||
-33
@@ -1,33 +0,0 @@
|
||||
<?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::create('investment_accounts', function (Blueprint $table) {
|
||||
$table->uuid('id')->primary();
|
||||
|
||||
$table->foreignUuid('user_id')->constrained('users')->restrictOnDelete();
|
||||
$table->foreignUuid('investment_type_id')->constrained('investment_types')->restrictOnDelete();
|
||||
|
||||
$table->decimal('current_balance', 15, 2)->default(0);
|
||||
$table->decimal('pending_balance', 15, 2)->default(0);
|
||||
|
||||
$table->string('status')->default('ACTIVE');
|
||||
|
||||
$table->timestamps();
|
||||
|
||||
$table->unique(['user_id', 'investment_type_id']);
|
||||
$table->index('status');
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('investment_accounts');
|
||||
}
|
||||
};
|
||||
@@ -1,47 +0,0 @@
|
||||
<?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::create('investments', function (Blueprint $table) {
|
||||
$table->uuid('id')->primary();
|
||||
|
||||
$table->string('reference_no')->unique();
|
||||
|
||||
$table->foreignUuid('user_id')->constrained('users')->restrictOnDelete();
|
||||
$table->foreignUuid('investment_account_id')->constrained('investment_accounts')->restrictOnDelete();
|
||||
$table->foreignUuid('investment_type_id')->constrained('investment_types')->restrictOnDelete();
|
||||
|
||||
$table->decimal('amount', 15, 2);
|
||||
|
||||
$table->string('source');
|
||||
$table->string('status');
|
||||
|
||||
$table->text('remarks')->nullable();
|
||||
|
||||
$table->foreignUuid('created_by')->nullable()->constrained('users')->nullOnDelete();
|
||||
$table->foreignUuid('approved_by')->nullable()->constrained('users')->nullOnDelete();
|
||||
|
||||
$table->timestamp('approved_at')->nullable();
|
||||
$table->timestamp('completed_at')->nullable();
|
||||
$table->timestamp('cancelled_at')->nullable();
|
||||
$table->timestamps();
|
||||
|
||||
$table->index('user_id');
|
||||
$table->index('investment_type_id');
|
||||
$table->index('source');
|
||||
$table->index('status');
|
||||
$table->index(['status', 'investment_type_id']);
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('investments');
|
||||
}
|
||||
};
|
||||
-50
@@ -1,50 +0,0 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('investment_ledger', function (Blueprint $table) {
|
||||
$table->uuid('id')->primary();
|
||||
|
||||
$table->foreignUuid('investment_id')->nullable()->constrained('investments')->restrictOnDelete();
|
||||
$table->foreignUuid('investment_account_id')->constrained('investment_accounts')->restrictOnDelete();
|
||||
$table->foreignUuid('user_id')->constrained('users')->restrictOnDelete();
|
||||
$table->foreignUuid('investment_type_id')->constrained('investment_types')->restrictOnDelete();
|
||||
|
||||
$table->string('transaction_type');
|
||||
|
||||
$table->decimal('credit', 15, 2)->default(0);
|
||||
$table->decimal('debit', 15, 2)->default(0);
|
||||
$table->decimal('balance_after', 15, 2);
|
||||
|
||||
$table->foreignUuid('created_by')->nullable()->constrained('users')->nullOnDelete();
|
||||
$table->timestamp('created_at')->useCurrent();
|
||||
|
||||
$table->index('investment_account_id');
|
||||
$table->index('user_id');
|
||||
$table->index('investment_type_id');
|
||||
$table->index('transaction_type');
|
||||
$table->index('created_at');
|
||||
});
|
||||
|
||||
// One INVESTMENT credit post per investment (idempotency guard).
|
||||
// Other types (ADJUSTMENT / REVERSAL / REFUND) may repeat if needed.
|
||||
DB::statement("
|
||||
CREATE UNIQUE INDEX investment_ledger_investment_investment_unique
|
||||
ON investment_ledger (investment_id)
|
||||
WHERE transaction_type = 'INVESTMENT'
|
||||
AND investment_id IS NOT NULL
|
||||
");
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('investment_ledger');
|
||||
}
|
||||
};
|
||||
-28
@@ -1,28 +0,0 @@
|
||||
<?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::create('investment_fund_summary', function (Blueprint $table) {
|
||||
$table->uuid('id')->primary();
|
||||
|
||||
$table->foreignUuid('investment_type_id')->unique()->constrained('investment_types')->restrictOnDelete();
|
||||
|
||||
$table->decimal('total_invested', 15, 2)->default(0);
|
||||
$table->decimal('reserved_amount', 15, 2)->default(0);
|
||||
$table->decimal('remaining_capacity', 15, 2)->nullable();
|
||||
|
||||
$table->timestamp('updated_at')->nullable();
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('investment_fund_summary');
|
||||
}
|
||||
};
|
||||
-25
@@ -1,25 +0,0 @@
|
||||
<?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::create('investment_limit_profiles', function (Blueprint $table) {
|
||||
$table->uuid('id')->primary();
|
||||
|
||||
$table->string('name')->unique();
|
||||
$table->text('description')->nullable();
|
||||
|
||||
$table->timestamps();
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('investment_limit_profiles');
|
||||
}
|
||||
};
|
||||
-34
@@ -1,34 +0,0 @@
|
||||
<?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::create('profile_investment_limits', function (Blueprint $table) {
|
||||
$table->uuid('id')->primary();
|
||||
|
||||
$table->foreignUuid('profile_id')
|
||||
->constrained('investment_limit_profiles')
|
||||
->cascadeOnDelete();
|
||||
$table->foreignUuid('investment_type_id')
|
||||
->constrained('investment_types')
|
||||
->restrictOnDelete();
|
||||
|
||||
$table->decimal('max_investment_amount', 15, 2)->nullable();
|
||||
$table->decimal('max_transaction_amount', 15, 2)->nullable();
|
||||
|
||||
$table->timestamps();
|
||||
|
||||
$table->unique(['profile_id', 'investment_type_id']);
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('profile_investment_limits');
|
||||
}
|
||||
};
|
||||
-41
@@ -1,41 +0,0 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('user_limit_profiles', function (Blueprint $table) {
|
||||
$table->uuid('id')->primary();
|
||||
|
||||
$table->foreignUuid('user_id')->constrained('users')->cascadeOnDelete();
|
||||
$table->foreignUuid('profile_id')
|
||||
->constrained('investment_limit_profiles')
|
||||
->restrictOnDelete();
|
||||
|
||||
$table->date('effective_date');
|
||||
$table->date('expiry_date')->nullable();
|
||||
|
||||
$table->timestamp('created_at')->useCurrent();
|
||||
|
||||
$table->index(['user_id', 'effective_date']);
|
||||
$table->index(['user_id', 'expiry_date']);
|
||||
});
|
||||
|
||||
// At most one currently active profile assignment per user.
|
||||
DB::statement('
|
||||
CREATE UNIQUE INDEX user_limit_profiles_user_active_unique
|
||||
ON user_limit_profiles (user_id)
|
||||
WHERE expiry_date IS NULL
|
||||
');
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('user_limit_profiles');
|
||||
}
|
||||
};
|
||||
-38
@@ -1,38 +0,0 @@
|
||||
<?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::create('user_investment_limits', function (Blueprint $table) {
|
||||
$table->uuid('id')->primary();
|
||||
|
||||
$table->foreignUuid('user_id')->constrained('users')->cascadeOnDelete();
|
||||
$table->foreignUuid('investment_type_id')
|
||||
->constrained('investment_types')
|
||||
->restrictOnDelete();
|
||||
|
||||
$table->decimal('max_investment_amount', 15, 2)->nullable();
|
||||
$table->decimal('max_transaction_amount', 15, 2)->nullable();
|
||||
|
||||
$table->date('effective_date');
|
||||
$table->date('expiry_date')->nullable();
|
||||
|
||||
$table->foreignUuid('created_by')->nullable()->constrained('users')->nullOnDelete();
|
||||
|
||||
$table->timestamps();
|
||||
|
||||
$table->index(['user_id', 'investment_type_id']);
|
||||
$table->index(['user_id', 'investment_type_id', 'effective_date', 'expiry_date']);
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('user_investment_limits');
|
||||
}
|
||||
};
|
||||
-48
@@ -1,48 +0,0 @@
|
||||
<?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::create('investment_payments', function (Blueprint $table) {
|
||||
$table->uuid('id')->primary();
|
||||
|
||||
$table->foreignUuid('investment_id')
|
||||
->unique()
|
||||
->constrained('investments')
|
||||
->restrictOnDelete();
|
||||
|
||||
$table->string('gateway')->default('BILLPLZ');
|
||||
|
||||
$table->decimal('amount', 15, 2);
|
||||
$table->string('currency', 3)->default('MYR');
|
||||
|
||||
$table->string('status')->default('PENDING');
|
||||
|
||||
$table->string('external_reference')->nullable();
|
||||
$table->text('failure_reason')->nullable();
|
||||
|
||||
$table->string('idempotency_key')->unique();
|
||||
|
||||
$table->text('redirect_url')->nullable();
|
||||
$table->text('callback_url')->nullable();
|
||||
|
||||
$table->timestamp('paid_at')->nullable();
|
||||
$table->timestamp('expired_at')->nullable();
|
||||
$table->timestamps();
|
||||
|
||||
$table->index('status');
|
||||
$table->index('gateway');
|
||||
$table->index('external_reference');
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('investment_payments');
|
||||
}
|
||||
};
|
||||
-50
@@ -1,50 +0,0 @@
|
||||
<?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::create('billplz_transactions', function (Blueprint $table) {
|
||||
$table->uuid('id')->primary();
|
||||
|
||||
$table->foreignUuid('payment_id')
|
||||
->constrained('investment_payments')
|
||||
->restrictOnDelete();
|
||||
|
||||
$table->string('bill_id')->unique();
|
||||
$table->string('collection_id')->nullable();
|
||||
|
||||
$table->text('bill_url')->nullable();
|
||||
|
||||
$table->string('reference_1')->nullable();
|
||||
$table->string('reference_2')->nullable();
|
||||
|
||||
$table->decimal('paid_amount', 15, 2)->nullable();
|
||||
$table->string('state')->nullable();
|
||||
$table->string('transaction_status')->default('PENDING');
|
||||
|
||||
$table->timestamp('paid_at')->nullable();
|
||||
|
||||
$table->string('x_signature')->nullable();
|
||||
$table->boolean('signature_verified')->default(false);
|
||||
|
||||
$table->json('callback_payload')->nullable();
|
||||
$table->json('redirect_payload')->nullable();
|
||||
|
||||
$table->timestamps();
|
||||
|
||||
$table->index('payment_id');
|
||||
$table->index('transaction_status');
|
||||
$table->index('reference_1');
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('billplz_transactions');
|
||||
}
|
||||
};
|
||||
-37
@@ -1,37 +0,0 @@
|
||||
<?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::create('salary_contributions', function (Blueprint $table) {
|
||||
$table->uuid('id')->primary();
|
||||
|
||||
$table->foreignUuid('user_id')->constrained('users')->restrictOnDelete();
|
||||
$table->foreignUuid('investment_type_id')->constrained('investment_types')->restrictOnDelete();
|
||||
|
||||
$table->decimal('monthly_amount', 15, 2);
|
||||
|
||||
$table->date('start_date');
|
||||
$table->date('end_date')->nullable();
|
||||
|
||||
$table->string('status')->default('ACTIVE');
|
||||
|
||||
$table->foreignUuid('created_by')->nullable()->constrained('users')->nullOnDelete();
|
||||
|
||||
$table->timestamps();
|
||||
|
||||
$table->index(['user_id', 'investment_type_id']);
|
||||
$table->index('status');
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('salary_contributions');
|
||||
}
|
||||
};
|
||||
-40
@@ -1,40 +0,0 @@
|
||||
<?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::create('salary_deduction_batches', function (Blueprint $table) {
|
||||
$table->uuid('id')->primary();
|
||||
|
||||
$table->string('batch_no')->unique();
|
||||
|
||||
$table->unsignedTinyInteger('month');
|
||||
$table->unsignedSmallInteger('year');
|
||||
|
||||
$table->unsignedInteger('total_records')->default(0);
|
||||
$table->decimal('total_amount', 15, 2)->default(0);
|
||||
|
||||
$table->string('status')->default('UPLOADED');
|
||||
|
||||
$table->foreignUuid('uploaded_by')->nullable()->constrained('users')->nullOnDelete();
|
||||
$table->foreignUuid('verified_by')->nullable()->constrained('users')->nullOnDelete();
|
||||
|
||||
$table->timestamp('uploaded_at')->nullable();
|
||||
$table->timestamp('verified_at')->nullable();
|
||||
$table->timestamps();
|
||||
|
||||
$table->unique(['month', 'year']);
|
||||
$table->index('status');
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('salary_deduction_batches');
|
||||
}
|
||||
};
|
||||
-49
@@ -1,49 +0,0 @@
|
||||
<?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::create('salary_deduction_batch_details', function (Blueprint $table) {
|
||||
$table->uuid('id')->primary();
|
||||
|
||||
$table->foreignUuid('batch_id')
|
||||
->constrained('salary_deduction_batches')
|
||||
->cascadeOnDelete();
|
||||
|
||||
$table->foreignUuid('user_id')->constrained('users')->restrictOnDelete();
|
||||
$table->foreignUuid('salary_contribution_id')
|
||||
->nullable()
|
||||
->constrained('salary_contributions')
|
||||
->nullOnDelete();
|
||||
$table->foreignUuid('investment_type_id')->constrained('investment_types')->restrictOnDelete();
|
||||
$table->foreignUuid('investment_id')
|
||||
->nullable()
|
||||
->constrained('investments')
|
||||
->nullOnDelete();
|
||||
|
||||
$table->decimal('amount', 15, 2);
|
||||
|
||||
$table->string('status')->default('PENDING');
|
||||
$table->text('remarks')->nullable();
|
||||
|
||||
$table->foreignUuid('verified_by')->nullable()->constrained('users')->nullOnDelete();
|
||||
$table->timestamp('verified_at')->nullable();
|
||||
|
||||
$table->timestamp('created_at')->useCurrent();
|
||||
|
||||
$table->index(['batch_id', 'status']);
|
||||
$table->index(['user_id', 'investment_type_id']);
|
||||
$table->index('investment_id');
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('salary_deduction_batch_details');
|
||||
}
|
||||
};
|
||||
-35
@@ -1,35 +0,0 @@
|
||||
<?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::create('salary_verification_logs', function (Blueprint $table) {
|
||||
$table->uuid('id')->primary();
|
||||
|
||||
$table->foreignUuid('batch_detail_id')
|
||||
->constrained('salary_deduction_batch_details')
|
||||
->cascadeOnDelete();
|
||||
|
||||
$table->string('old_status')->nullable();
|
||||
$table->string('new_status');
|
||||
|
||||
$table->foreignUuid('action_by')->nullable()->constrained('users')->nullOnDelete();
|
||||
|
||||
$table->text('remarks')->nullable();
|
||||
|
||||
$table->timestamp('created_at')->useCurrent();
|
||||
|
||||
$table->index('batch_detail_id');
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('salary_verification_logs');
|
||||
}
|
||||
};
|
||||
@@ -1,21 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Investment\Database\Seeders;
|
||||
|
||||
use Illuminate\Database\Seeder;
|
||||
|
||||
class InvestmentDatabaseSeeder extends Seeder
|
||||
{
|
||||
/**
|
||||
* Run the database seeds.
|
||||
*/
|
||||
public function run(): void
|
||||
{
|
||||
$this->call([
|
||||
InvestmentTypePermissionSeeder::class,
|
||||
InvestmentPermissionSeeder::class,
|
||||
InvestmentLimitPermissionSeeder::class,
|
||||
SalaryDeductionPermissionSeeder::class,
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Investment\Database\Seeders;
|
||||
|
||||
use App\Models\Permission;
|
||||
use Illuminate\Database\Seeder;
|
||||
|
||||
class InvestmentLimitPermissionSeeder extends Seeder
|
||||
{
|
||||
public function run(): void
|
||||
{
|
||||
$permissions = [
|
||||
'lihat had pelaburan',
|
||||
'tambah had pelaburan',
|
||||
'kemaskini had pelaburan',
|
||||
'hapus had pelaburan',
|
||||
];
|
||||
|
||||
foreach ($permissions as $name) {
|
||||
Permission::firstOrCreate(
|
||||
['name' => $name, 'guard_name' => 'api'],
|
||||
['name' => $name, 'guard_name' => 'api']
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Investment\Database\Seeders;
|
||||
|
||||
use App\Models\Permission;
|
||||
use Illuminate\Database\Seeder;
|
||||
|
||||
class InvestmentPermissionSeeder extends Seeder
|
||||
{
|
||||
public function run(): void
|
||||
{
|
||||
$permissions = [
|
||||
'lihat pelaburan',
|
||||
'tambah pelaburan manual',
|
||||
'tambah pelaburan billplz',
|
||||
];
|
||||
|
||||
foreach ($permissions as $name) {
|
||||
Permission::firstOrCreate(
|
||||
['name' => $name, 'guard_name' => 'api'],
|
||||
['name' => $name, 'guard_name' => 'api']
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Investment\Database\Seeders;
|
||||
|
||||
use App\Models\Permission;
|
||||
use Illuminate\Database\Seeder;
|
||||
|
||||
class InvestmentTypePermissionSeeder extends Seeder
|
||||
{
|
||||
public function run(): void
|
||||
{
|
||||
$permissions = [
|
||||
'lihat jenis pelaburan',
|
||||
'tambah jenis pelaburan',
|
||||
'kemaskini jenis pelaburan',
|
||||
'hapus jenis pelaburan',
|
||||
];
|
||||
|
||||
foreach ($permissions as $name) {
|
||||
Permission::firstOrCreate(
|
||||
['name' => $name, 'guard_name' => 'api'],
|
||||
['name' => $name, 'guard_name' => 'api']
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Investment\Database\Seeders;
|
||||
|
||||
use App\Models\Permission;
|
||||
use Illuminate\Database\Seeder;
|
||||
|
||||
class SalaryDeductionPermissionSeeder extends Seeder
|
||||
{
|
||||
public function run(): void
|
||||
{
|
||||
$permissions = [
|
||||
'lihat potongan gaji',
|
||||
'tambah potongan gaji',
|
||||
'kemaskini potongan gaji',
|
||||
'hapus potongan gaji',
|
||||
'sahkan potongan gaji',
|
||||
];
|
||||
|
||||
foreach ($permissions as $name) {
|
||||
Permission::firstOrCreate(
|
||||
['name' => $name, 'guard_name' => 'api'],
|
||||
['name' => $name, 'guard_name' => 'api']
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Investment\Entities;
|
||||
|
||||
use Illuminate\Database\Eloquent\Concerns\HasUuids;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Modules\Investment\Enums\BillplzTransactionStatus;
|
||||
|
||||
class BillplzTransaction extends Model
|
||||
{
|
||||
use HasUuids;
|
||||
|
||||
protected $table = 'billplz_transactions';
|
||||
|
||||
protected $fillable = [
|
||||
'payment_id',
|
||||
'bill_id',
|
||||
'collection_id',
|
||||
'bill_url',
|
||||
'reference_1',
|
||||
'reference_2',
|
||||
'paid_amount',
|
||||
'state',
|
||||
'transaction_status',
|
||||
'paid_at',
|
||||
'x_signature',
|
||||
'signature_verified',
|
||||
'callback_payload',
|
||||
'redirect_payload',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'paid_amount' => 'decimal:2',
|
||||
'transaction_status' => BillplzTransactionStatus::class,
|
||||
'paid_at' => 'datetime',
|
||||
'signature_verified' => 'boolean',
|
||||
'callback_payload' => 'array',
|
||||
'redirect_payload' => 'array',
|
||||
];
|
||||
}
|
||||
|
||||
public function payment(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(InvestmentPayment::class, 'payment_id');
|
||||
}
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Investment\Entities;
|
||||
|
||||
use App\Traits\HasDocuments;
|
||||
use Illuminate\Database\Eloquent\Concerns\HasUuids;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasOne;
|
||||
use Modules\Auth\Entities\User;
|
||||
use Modules\Investment\Enums\InvestmentSource;
|
||||
use Modules\Investment\Enums\InvestmentStatus;
|
||||
|
||||
class Investment extends Model
|
||||
{
|
||||
use HasDocuments, HasUuids;
|
||||
|
||||
protected $table = 'investments';
|
||||
|
||||
protected $fillable = [
|
||||
'reference_no',
|
||||
'user_id',
|
||||
'investment_account_id',
|
||||
'investment_type_id',
|
||||
'amount',
|
||||
'source',
|
||||
'status',
|
||||
'remarks',
|
||||
'created_by',
|
||||
'approved_by',
|
||||
'approved_at',
|
||||
'completed_at',
|
||||
'cancelled_at',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'amount' => 'decimal:2',
|
||||
'source' => InvestmentSource::class,
|
||||
'status' => InvestmentStatus::class,
|
||||
'approved_at' => 'datetime',
|
||||
'completed_at' => 'datetime',
|
||||
'cancelled_at' => 'datetime',
|
||||
];
|
||||
}
|
||||
|
||||
public function user(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'user_id');
|
||||
}
|
||||
|
||||
public function account(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(InvestmentAccount::class, 'investment_account_id');
|
||||
}
|
||||
|
||||
public function investmentType(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(InvestmentType::class, 'investment_type_id');
|
||||
}
|
||||
|
||||
public function createdBy(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'created_by');
|
||||
}
|
||||
|
||||
public function approvedBy(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'approved_by');
|
||||
}
|
||||
|
||||
public function ledgerEntries(): HasMany
|
||||
{
|
||||
return $this->hasMany(InvestmentLedger::class, 'investment_id');
|
||||
}
|
||||
|
||||
public function payment(): HasOne
|
||||
{
|
||||
return $this->hasOne(InvestmentPayment::class, 'investment_id');
|
||||
}
|
||||
|
||||
public function salaryDeductionDetail(): HasOne
|
||||
{
|
||||
return $this->hasOne(SalaryDeductionBatchDetail::class, 'investment_id');
|
||||
}
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Investment\Entities;
|
||||
|
||||
use Illuminate\Database\Eloquent\Concerns\HasUuids;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Modules\Auth\Entities\User;
|
||||
use Modules\Investment\Enums\InvestmentAccountStatus;
|
||||
|
||||
class InvestmentAccount extends Model
|
||||
{
|
||||
use HasUuids;
|
||||
|
||||
protected $table = 'investment_accounts';
|
||||
|
||||
protected $fillable = [
|
||||
'user_id',
|
||||
'investment_type_id',
|
||||
'current_balance',
|
||||
'pending_balance',
|
||||
'status',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'status' => InvestmentAccountStatus::class,
|
||||
'current_balance' => 'decimal:2',
|
||||
'pending_balance' => 'decimal:2',
|
||||
];
|
||||
}
|
||||
|
||||
public function user(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'user_id');
|
||||
}
|
||||
|
||||
public function investmentType(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(InvestmentType::class, 'investment_type_id');
|
||||
}
|
||||
|
||||
public function investments(): HasMany
|
||||
{
|
||||
return $this->hasMany(Investment::class, 'investment_account_id');
|
||||
}
|
||||
|
||||
public function ledgerEntries(): HasMany
|
||||
{
|
||||
return $this->hasMany(InvestmentLedger::class, 'investment_account_id');
|
||||
}
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Investment\Entities;
|
||||
|
||||
use Illuminate\Database\Eloquent\Concerns\HasUuids;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
class InvestmentFundSummary extends Model
|
||||
{
|
||||
use HasUuids;
|
||||
|
||||
public $timestamps = false;
|
||||
|
||||
protected $table = 'investment_fund_summary';
|
||||
|
||||
protected $fillable = [
|
||||
'investment_type_id',
|
||||
'total_invested',
|
||||
'reserved_amount',
|
||||
'remaining_capacity',
|
||||
'updated_at',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'total_invested' => 'decimal:2',
|
||||
'reserved_amount' => 'decimal:2',
|
||||
'remaining_capacity' => 'decimal:2',
|
||||
'updated_at' => 'datetime',
|
||||
];
|
||||
}
|
||||
|
||||
public function investmentType(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(InvestmentType::class, 'investment_type_id');
|
||||
}
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Investment\Entities;
|
||||
|
||||
use Illuminate\Database\Eloquent\Concerns\HasUuids;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Modules\Auth\Entities\User;
|
||||
use Modules\Investment\Enums\InvestmentLedgerTransactionType;
|
||||
|
||||
class InvestmentLedger extends Model
|
||||
{
|
||||
use HasUuids;
|
||||
|
||||
public $timestamps = false;
|
||||
|
||||
protected $table = 'investment_ledger';
|
||||
|
||||
protected $fillable = [
|
||||
'investment_id',
|
||||
'investment_account_id',
|
||||
'user_id',
|
||||
'investment_type_id',
|
||||
'transaction_type',
|
||||
'credit',
|
||||
'debit',
|
||||
'balance_after',
|
||||
'created_by',
|
||||
'created_at',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'transaction_type' => InvestmentLedgerTransactionType::class,
|
||||
'credit' => 'decimal:2',
|
||||
'debit' => 'decimal:2',
|
||||
'balance_after' => 'decimal:2',
|
||||
'created_at' => 'datetime',
|
||||
];
|
||||
}
|
||||
|
||||
public function investment(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Investment::class, 'investment_id');
|
||||
}
|
||||
|
||||
public function account(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(InvestmentAccount::class, 'investment_account_id');
|
||||
}
|
||||
|
||||
public function user(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'user_id');
|
||||
}
|
||||
|
||||
public function investmentType(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(InvestmentType::class, 'investment_type_id');
|
||||
}
|
||||
|
||||
public function createdBy(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'created_by');
|
||||
}
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Investment\Entities;
|
||||
|
||||
use Illuminate\Database\Eloquent\Concerns\HasUuids;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
class InvestmentLimitProfile extends Model
|
||||
{
|
||||
use HasUuids;
|
||||
|
||||
protected $table = 'investment_limit_profiles';
|
||||
|
||||
protected $fillable = [
|
||||
'name',
|
||||
'description',
|
||||
];
|
||||
|
||||
public function profileLimits(): HasMany
|
||||
{
|
||||
return $this->hasMany(ProfileInvestmentLimit::class, 'profile_id');
|
||||
}
|
||||
|
||||
public function userAssignments(): HasMany
|
||||
{
|
||||
return $this->hasMany(UserLimitProfile::class, 'profile_id');
|
||||
}
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Investment\Entities;
|
||||
|
||||
use Illuminate\Database\Eloquent\Concerns\HasUuids;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasOne;
|
||||
use Modules\Investment\Enums\InvestmentPaymentGateway;
|
||||
use Modules\Investment\Enums\InvestmentPaymentStatus;
|
||||
|
||||
class InvestmentPayment extends Model
|
||||
{
|
||||
use HasUuids;
|
||||
|
||||
protected $table = 'investment_payments';
|
||||
|
||||
protected $fillable = [
|
||||
'investment_id',
|
||||
'gateway',
|
||||
'amount',
|
||||
'currency',
|
||||
'status',
|
||||
'external_reference',
|
||||
'failure_reason',
|
||||
'idempotency_key',
|
||||
'redirect_url',
|
||||
'callback_url',
|
||||
'paid_at',
|
||||
'expired_at',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'gateway' => InvestmentPaymentGateway::class,
|
||||
'status' => InvestmentPaymentStatus::class,
|
||||
'amount' => 'decimal:2',
|
||||
'paid_at' => 'datetime',
|
||||
'expired_at' => 'datetime',
|
||||
];
|
||||
}
|
||||
|
||||
public function investment(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Investment::class, 'investment_id');
|
||||
}
|
||||
|
||||
public function billplzTransaction(): HasOne
|
||||
{
|
||||
return $this->hasOne(BillplzTransaction::class, 'payment_id');
|
||||
}
|
||||
}
|
||||
@@ -1,97 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Investment\Entities;
|
||||
|
||||
use Illuminate\Database\Eloquent\Concerns\HasUuids;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasOne;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
use Modules\Auth\Entities\User;
|
||||
use Modules\Investment\Enums\InvestmentTypeStatus;
|
||||
|
||||
class InvestmentType extends Model
|
||||
{
|
||||
use HasUuids, SoftDeletes;
|
||||
|
||||
protected $table = 'investment_types';
|
||||
|
||||
protected $fillable = [
|
||||
'code',
|
||||
'name',
|
||||
'description',
|
||||
'status',
|
||||
'minimum_amount',
|
||||
'maximum_amount',
|
||||
'total_fund_limit',
|
||||
'start_date',
|
||||
'end_date',
|
||||
'allow_billplz',
|
||||
'allow_salary_deduction',
|
||||
'billplz_collection_id',
|
||||
'created_by',
|
||||
'updated_by',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'status' => InvestmentTypeStatus::class,
|
||||
'minimum_amount' => 'decimal:2',
|
||||
'maximum_amount' => 'decimal:2',
|
||||
'total_fund_limit' => 'decimal:2',
|
||||
'reserved_amount' => 'decimal:2',
|
||||
'start_date' => 'date',
|
||||
'end_date' => 'date',
|
||||
'allow_billplz' => 'boolean',
|
||||
'allow_salary_deduction' => 'boolean',
|
||||
];
|
||||
}
|
||||
|
||||
public function createdBy(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'created_by');
|
||||
}
|
||||
|
||||
public function updatedBy(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'updated_by');
|
||||
}
|
||||
|
||||
public function accounts(): HasMany
|
||||
{
|
||||
return $this->hasMany(InvestmentAccount::class, 'investment_type_id');
|
||||
}
|
||||
|
||||
public function investments(): HasMany
|
||||
{
|
||||
return $this->hasMany(Investment::class, 'investment_type_id');
|
||||
}
|
||||
|
||||
public function ledgerEntries(): HasMany
|
||||
{
|
||||
return $this->hasMany(InvestmentLedger::class, 'investment_type_id');
|
||||
}
|
||||
|
||||
public function fundSummary(): HasOne
|
||||
{
|
||||
return $this->hasOne(InvestmentFundSummary::class, 'investment_type_id');
|
||||
}
|
||||
|
||||
public function profileInvestmentLimits(): HasMany
|
||||
{
|
||||
return $this->hasMany(ProfileInvestmentLimit::class, 'investment_type_id');
|
||||
}
|
||||
|
||||
public function userInvestmentLimits(): HasMany
|
||||
{
|
||||
return $this->hasMany(UserInvestmentLimit::class, 'investment_type_id');
|
||||
}
|
||||
|
||||
public function salaryContributions(): HasMany
|
||||
{
|
||||
return $this->hasMany(SalaryContribution::class, 'investment_type_id');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,39 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Investment\Entities;
|
||||
|
||||
use Illuminate\Database\Eloquent\Concerns\HasUuids;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
class ProfileInvestmentLimit extends Model
|
||||
{
|
||||
use HasUuids;
|
||||
|
||||
protected $table = 'profile_investment_limits';
|
||||
|
||||
protected $fillable = [
|
||||
'profile_id',
|
||||
'investment_type_id',
|
||||
'max_investment_amount',
|
||||
'max_transaction_amount',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'max_investment_amount' => 'decimal:2',
|
||||
'max_transaction_amount' => 'decimal:2',
|
||||
];
|
||||
}
|
||||
|
||||
public function profile(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(InvestmentLimitProfile::class, 'profile_id');
|
||||
}
|
||||
|
||||
public function investmentType(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(InvestmentType::class, 'investment_type_id');
|
||||
}
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Investment\Entities;
|
||||
|
||||
use Illuminate\Database\Eloquent\Concerns\HasUuids;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Modules\Auth\Entities\User;
|
||||
use Modules\Investment\Enums\SalaryContributionStatus;
|
||||
|
||||
class SalaryContribution extends Model
|
||||
{
|
||||
use HasUuids;
|
||||
|
||||
protected $table = 'salary_contributions';
|
||||
|
||||
protected $fillable = [
|
||||
'user_id',
|
||||
'investment_type_id',
|
||||
'monthly_amount',
|
||||
'start_date',
|
||||
'end_date',
|
||||
'status',
|
||||
'created_by',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'monthly_amount' => 'decimal:2',
|
||||
'start_date' => 'date',
|
||||
'end_date' => 'date',
|
||||
'status' => SalaryContributionStatus::class,
|
||||
];
|
||||
}
|
||||
|
||||
public function user(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'user_id');
|
||||
}
|
||||
|
||||
public function investmentType(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(InvestmentType::class, 'investment_type_id');
|
||||
}
|
||||
|
||||
public function createdBy(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'created_by');
|
||||
}
|
||||
|
||||
public function batchDetails(): HasMany
|
||||
{
|
||||
return $this->hasMany(SalaryDeductionBatchDetail::class, 'salary_contribution_id');
|
||||
}
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Investment\Entities;
|
||||
|
||||
use Illuminate\Database\Eloquent\Concerns\HasUuids;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Modules\Auth\Entities\User;
|
||||
use Modules\Investment\Enums\SalaryDeductionBatchStatus;
|
||||
|
||||
class SalaryDeductionBatch extends Model
|
||||
{
|
||||
use HasUuids;
|
||||
|
||||
protected $table = 'salary_deduction_batches';
|
||||
|
||||
protected $fillable = [
|
||||
'batch_no',
|
||||
'month',
|
||||
'year',
|
||||
'total_records',
|
||||
'total_amount',
|
||||
'status',
|
||||
'uploaded_by',
|
||||
'verified_by',
|
||||
'uploaded_at',
|
||||
'verified_at',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'month' => 'integer',
|
||||
'year' => 'integer',
|
||||
'total_records' => 'integer',
|
||||
'total_amount' => 'decimal:2',
|
||||
'status' => SalaryDeductionBatchStatus::class,
|
||||
'uploaded_at' => 'datetime',
|
||||
'verified_at' => 'datetime',
|
||||
];
|
||||
}
|
||||
|
||||
public function details(): HasMany
|
||||
{
|
||||
return $this->hasMany(SalaryDeductionBatchDetail::class, 'batch_id');
|
||||
}
|
||||
|
||||
public function uploadedBy(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'uploaded_by');
|
||||
}
|
||||
|
||||
public function verifiedBy(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'verified_by');
|
||||
}
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Investment\Entities;
|
||||
|
||||
use Illuminate\Database\Eloquent\Concerns\HasUuids;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Modules\Auth\Entities\User;
|
||||
use Modules\Investment\Enums\SalaryDeductionDetailStatus;
|
||||
|
||||
class SalaryDeductionBatchDetail extends Model
|
||||
{
|
||||
use HasUuids;
|
||||
|
||||
public $timestamps = false;
|
||||
|
||||
protected $table = 'salary_deduction_batch_details';
|
||||
|
||||
protected $fillable = [
|
||||
'batch_id',
|
||||
'user_id',
|
||||
'salary_contribution_id',
|
||||
'investment_type_id',
|
||||
'investment_id',
|
||||
'amount',
|
||||
'status',
|
||||
'remarks',
|
||||
'verified_by',
|
||||
'verified_at',
|
||||
'created_at',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'amount' => 'decimal:2',
|
||||
'status' => SalaryDeductionDetailStatus::class,
|
||||
'verified_at' => 'datetime',
|
||||
'created_at' => 'datetime',
|
||||
];
|
||||
}
|
||||
|
||||
public function batch(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(SalaryDeductionBatch::class, 'batch_id');
|
||||
}
|
||||
|
||||
public function user(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'user_id');
|
||||
}
|
||||
|
||||
public function salaryContribution(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(SalaryContribution::class, 'salary_contribution_id');
|
||||
}
|
||||
|
||||
public function investmentType(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(InvestmentType::class, 'investment_type_id');
|
||||
}
|
||||
|
||||
public function investment(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Investment::class, 'investment_id');
|
||||
}
|
||||
|
||||
public function verifiedBy(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'verified_by');
|
||||
}
|
||||
|
||||
public function verificationLogs(): HasMany
|
||||
{
|
||||
return $this->hasMany(SalaryVerificationLog::class, 'batch_detail_id');
|
||||
}
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Investment\Entities;
|
||||
|
||||
use Illuminate\Database\Eloquent\Concerns\HasUuids;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Modules\Auth\Entities\User;
|
||||
|
||||
class SalaryVerificationLog extends Model
|
||||
{
|
||||
use HasUuids;
|
||||
|
||||
public $timestamps = false;
|
||||
|
||||
protected $table = 'salary_verification_logs';
|
||||
|
||||
protected $fillable = [
|
||||
'batch_detail_id',
|
||||
'old_status',
|
||||
'new_status',
|
||||
'action_by',
|
||||
'remarks',
|
||||
'created_at',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'created_at' => 'datetime',
|
||||
];
|
||||
}
|
||||
|
||||
public function batchDetail(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(SalaryDeductionBatchDetail::class, 'batch_detail_id');
|
||||
}
|
||||
|
||||
public function actionBy(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'action_by');
|
||||
}
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Investment\Entities;
|
||||
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Concerns\HasUuids;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Modules\Auth\Entities\User;
|
||||
|
||||
class UserInvestmentLimit extends Model
|
||||
{
|
||||
use HasUuids;
|
||||
|
||||
protected $table = 'user_investment_limits';
|
||||
|
||||
protected $fillable = [
|
||||
'user_id',
|
||||
'investment_type_id',
|
||||
'max_investment_amount',
|
||||
'max_transaction_amount',
|
||||
'effective_date',
|
||||
'expiry_date',
|
||||
'created_by',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'max_investment_amount' => 'decimal:2',
|
||||
'max_transaction_amount' => 'decimal:2',
|
||||
'effective_date' => 'date',
|
||||
'expiry_date' => 'date',
|
||||
];
|
||||
}
|
||||
|
||||
public function user(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'user_id');
|
||||
}
|
||||
|
||||
public function investmentType(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(InvestmentType::class, 'investment_type_id');
|
||||
}
|
||||
|
||||
public function createdBy(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'created_by');
|
||||
}
|
||||
|
||||
public function scopeActive(Builder $query, $onDate = null): Builder
|
||||
{
|
||||
$date = ($onDate ?? now())->toDateString();
|
||||
|
||||
return $query
|
||||
->whereDate('effective_date', '<=', $date)
|
||||
->where(function (Builder $builder) use ($date) {
|
||||
$builder->whereNull('expiry_date')
|
||||
->orWhereDate('expiry_date', '>=', $date);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Investment\Entities;
|
||||
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Concerns\HasUuids;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Modules\Auth\Entities\User;
|
||||
|
||||
class UserLimitProfile extends Model
|
||||
{
|
||||
use HasUuids;
|
||||
|
||||
public $timestamps = false;
|
||||
|
||||
protected $table = 'user_limit_profiles';
|
||||
|
||||
protected $fillable = [
|
||||
'user_id',
|
||||
'profile_id',
|
||||
'effective_date',
|
||||
'expiry_date',
|
||||
'created_at',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'effective_date' => 'date',
|
||||
'expiry_date' => 'date',
|
||||
'created_at' => 'datetime',
|
||||
];
|
||||
}
|
||||
|
||||
public function user(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'user_id');
|
||||
}
|
||||
|
||||
public function profile(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(InvestmentLimitProfile::class, 'profile_id');
|
||||
}
|
||||
|
||||
public function scopeActive(Builder $query, $onDate = null): Builder
|
||||
{
|
||||
$date = ($onDate ?? now())->toDateString();
|
||||
|
||||
return $query
|
||||
->whereDate('effective_date', '<=', $date)
|
||||
->where(function (Builder $builder) use ($date) {
|
||||
$builder->whereNull('expiry_date')
|
||||
->orWhereDate('expiry_date', '>=', $date);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Investment\Enums;
|
||||
|
||||
enum BillplzTransactionStatus: string
|
||||
{
|
||||
case Pending = 'PENDING';
|
||||
case Paid = 'PAID';
|
||||
case Failed = 'FAILED';
|
||||
case Deleted = 'DELETED';
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Investment\Enums;
|
||||
|
||||
enum InvestmentAccountStatus: string
|
||||
{
|
||||
case Active = 'ACTIVE';
|
||||
case Frozen = 'FROZEN';
|
||||
case Closed = 'CLOSED';
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Investment\Enums;
|
||||
|
||||
enum InvestmentLedgerTransactionType: string
|
||||
{
|
||||
case Investment = 'INVESTMENT';
|
||||
case Refund = 'REFUND';
|
||||
case Adjustment = 'ADJUSTMENT';
|
||||
case Reversal = 'REVERSAL';
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Investment\Enums;
|
||||
|
||||
enum InvestmentPaymentGateway: string
|
||||
{
|
||||
case Billplz = 'BILLPLZ';
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Investment\Enums;
|
||||
|
||||
enum InvestmentPaymentStatus: string
|
||||
{
|
||||
case Pending = 'PENDING';
|
||||
case Paid = 'PAID';
|
||||
case Failed = 'FAILED';
|
||||
case Cancelled = 'CANCELLED';
|
||||
case Expired = 'EXPIRED';
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Investment\Enums;
|
||||
|
||||
enum InvestmentSource: string
|
||||
{
|
||||
case Billplz = 'BILLPLZ';
|
||||
case SalaryDeduction = 'SALARY_DEDUCTION';
|
||||
case Manual = 'MANUAL';
|
||||
case Adjustment = 'ADJUSTMENT';
|
||||
case Refund = 'REFUND';
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Investment\Enums;
|
||||
|
||||
enum InvestmentStatus: string
|
||||
{
|
||||
case Draft = 'DRAFT';
|
||||
case PendingPayment = 'PENDING_PAYMENT';
|
||||
case PendingVerification = 'PENDING_VERIFICATION';
|
||||
case Completed = 'COMPLETED';
|
||||
case Rejected = 'REJECTED';
|
||||
case Cancelled = 'CANCELLED';
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Investment\Enums;
|
||||
|
||||
enum InvestmentTypeStatus: string
|
||||
{
|
||||
case Active = 'ACTIVE';
|
||||
case Inactive = 'INACTIVE';
|
||||
case Closed = 'CLOSED';
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Investment\Enums;
|
||||
|
||||
enum SalaryContributionStatus: string
|
||||
{
|
||||
case Active = 'ACTIVE';
|
||||
case Paused = 'PAUSED';
|
||||
case Ended = 'ENDED';
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user