From d0db9ee4291bf4eaa721323f7e7701a37ba257bd Mon Sep 17 00:00:00 2001 From: Ichsan Kurniawan Date: Mon, 5 Oct 2026 19:52:11 +0700 Subject: [PATCH] Add VPS deployment automation This change adds staging and production deployment configuration for the VPS setup, including `.env.deploy.example`, `.env.staging`, and updated production environment values. It also introduces a PowerShell deployment script that builds the app, packages the Next.js artifact, uploads it to the server, and reloads PM2. Package scripts were added for staging and production deploys, and the TypeScript config now excludes legacy `.old` files. --- .env.deploy.example | 25 + .env.production | 23 +- .env.staging | 21 + .gitignore | 1 + .../AssignmentDetailComponent.tsx | 635 ++++++++++++------ .../[client_id]/[assignment_id]/loading.tsx | 38 ++ deploy.ps1 | 405 +++++++++++ package.json | 4 +- tsconfig.json | 2 +- 9 files changed, 919 insertions(+), 235 deletions(-) create mode 100644 .env.deploy.example create mode 100644 .env.staging create mode 100644 app/(dashboard)/task/client-detail/[client_id]/[assignment_id]/loading.tsx create mode 100644 deploy.ps1 diff --git a/.env.deploy.example b/.env.deploy.example new file mode 100644 index 0000000..9e37bc2 --- /dev/null +++ b/.env.deploy.example @@ -0,0 +1,25 @@ +# ============================================================================== +# HATS-APP - VPS DEPLOYMENT CONFIGURATION TEMPLATE +# ============================================================================== +# Copy this file to '.env.deploy' and adjust the values as needed. +# Do NOT commit '.env.deploy' containing real credentials to public repositories! + +# VPS Connection Credentials +VPS_HOST=36.66.3.44 +VPS_PORT=22 +VPS_USER=root +VPS_PASSWORD=your_vps_password_here +VPS_KEY_PATH= + +# Staging Environment Settings +VPS_PATH_STAGING=/home/repositories/hats-app-dev/hats-app +PM2_APP_STAGING=hats-app-dev +PM2_PORT_STAGING=7005 + +# Production Environment Settings +VPS_PATH_PRODUCTION=/home/repositories/hats-app +PM2_APP_PRODUCTION=hats-app +PM2_PORT_PRODUCTION=7002 + +# Optional Custom Post Deploy Command (defaults to auto reload or create PM2 service) +# POST_DEPLOY_CMD=pm2 reload hats-app-dev || pm2 restart hats-app-dev diff --git a/.env.production b/.env.production index 23c0a11..863a7a1 100644 --- a/.env.production +++ b/.env.production @@ -1,21 +1,11 @@ BASE_PATH = "" -NEXT_PUBLIC_APP_URL="https://his.nutech-integrasi.com" +NEXT_PUBLIC_APP_URL="http://hats.hisnutech.my.id" -# BASE_URL_API = https://hats-his.nutech-integrasi.com/presence-api/api/v1 -# BASE_URL_IMG = https://hats-his.nutech-integrasi.com/presence-api/ -# NEXTAUTH_URL = https://hats-his.nutech-integrasi.com -# NEXTAUTH_URL_INTERNAL = http://36.66.3.44:7006 +BASE_URL_API = https://api-hats.hisnutech.my.id/api/v1 +BASE_URL_IMG = https://api-hats.hisnutech.my.id/ -# BASE_URL_API = https://36.66.3.44/presence-api/api/v1 -# BASE_URL_IMG = https://36.66.3.44/presence-api/ -# NEXTAUTH_URL = https://36.66.3.44 - -BASE_URL_API = https://his.nutech-integrasi.com/presence-api/api/v1 -BASE_URL_IMG = https://his.nutech-integrasi.com/presence-api/ -NEXTAUTH_URL = https://his.nutech-integrasi.com +NEXTAUTH_URL = http://hats.hisnutech.my.id NEXTAUTH_URL_INTERNAL = http://36.66.3.44:7002 -# NEXTAUTH_URL = http://localhost:7002 -# NEXTAUTH_URL_INTERNAL = http://localhost:7002 NEXTAUTH_SECRET = 4339d50684523526005c1fcb34be0bb1 @@ -25,4 +15,7 @@ FIREBASE_APP_ID = "1:422528660020:web:db16e1cba4d357e32f1061" DEVICE_CODE = "40001" NEXT_PUBLIC_HATS_SUPPORT_NAME = "Amalia" NEXT_PUBLIC_HATS_SUPPORT_PHONE = "6285214074002" -NEXT_PUBLIC_APP_VERSION = "v1.1.0" \ No newline at end of file +NEXT_PUBLIC_APP_VERSION = "v1.2.0" +NEXT_PUBLIC_MANAGER_USER_ID = '2' + +NEXT_PUBLIC_S3_IMAGE_URL = https://cdn.hisnutech.my.id/public \ No newline at end of file diff --git a/.env.staging b/.env.staging new file mode 100644 index 0000000..c1256b2 --- /dev/null +++ b/.env.staging @@ -0,0 +1,21 @@ +BASE_PATH = "" +NEXT_PUBLIC_APP_URL="https://dev-hats.hisnutech.my.id" + +BASE_URL_API = https://api-hats-dev.hisnutech.my.id/api/v1 +BASE_URL_IMG = https://api-hats.hisnutech.my.id/ + +NEXTAUTH_URL = https://dev-hats.hisnutech.my.id +NEXTAUTH_URL_INTERNAL = http://36.66.3.44:7005 + +NEXTAUTH_SECRET = 4339d50684523526005c1fcb34be0bb1 + +FIREBASE_API_KEY = AIzaSyAEkZCHhnyatsNiZ2dpjeaz6JqXYknKKHk +FIREBASE_APP_ID = "1:422528660020:web:db16e1cba4d357e32f1061" + +DEVICE_CODE = "40001" +NEXT_PUBLIC_HATS_SUPPORT_NAME = "Amalia" +NEXT_PUBLIC_HATS_SUPPORT_PHONE = "6285214074002" +NEXT_PUBLIC_APP_VERSION = "v1.2.0" +NEXT_PUBLIC_MANAGER_USER_ID = '2' + +NEXT_PUBLIC_S3_IMAGE_URL = https://cdn.hisnutech.my.id/public \ No newline at end of file diff --git a/.gitignore b/.gitignore index b6d2405..f275121 100644 --- a/.gitignore +++ b/.gitignore @@ -32,6 +32,7 @@ yarn-error.log* # env files (can opt-in for committing if needed) # .env* +.env.deploy # vercel .vercel diff --git a/app/(dashboard)/task/client-detail/[client_id]/[assignment_id]/AssignmentDetailComponent.tsx b/app/(dashboard)/task/client-detail/[client_id]/[assignment_id]/AssignmentDetailComponent.tsx index a6c112c..b4dadf4 100644 --- a/app/(dashboard)/task/client-detail/[client_id]/[assignment_id]/AssignmentDetailComponent.tsx +++ b/app/(dashboard)/task/client-detail/[client_id]/[assignment_id]/AssignmentDetailComponent.tsx @@ -1,272 +1,471 @@ "use client" -import { motion } from 'motion/react'; -import { ArrowLeft, Briefcase, Calendar, History, UserPlus, ExternalLink, Building2, Hash, Users, Icon, FileText, CalendarRange } from 'lucide-react'; -import { Button } from '@/components/ui/button'; -import { Card, CardContent, CardHeader, CardTitle, CardDescription, Card900 } from '@/components/ui/card'; -import { Badge } from '@/components/ui/badge'; -import { cn } from '@/lib/utils'; -import { useRouter } from 'next/navigation'; -import { IClient } from '../../../types'; -import { IProjectAssignment } from '../../../type.assignment'; -import { useState } from 'react'; -import BadgeStatus from '@/components/ui/badge-status'; +/** + * Design read: internal ops detail page for staff, calm Linear-style language, + * existing shadcn + Tailwind stack, brand orange (`his`) as the single accent. + * Dials: VARIANCE 5, MOTION 4, DENSITY 5. + * + * Shape lock: surfaces rounded-2xl, inner tiles rounded-xl, small chips rounded-lg. + * Elevation comes from borders, not shadows. Accent is used only for the current + * timeline node, link hovers and the primary action. + */ + +import { useState, type ReactNode } from 'react'; import Link from 'next/link'; -import AssignedPeople from '../project-detail/[project_id]/AssignedPeople'; +import { motion, useReducedMotion } from 'motion/react'; +import { + ArrowLeft, Briefcase, CalendarDays, ChevronDown, ExternalLink, FileText, FolderGit2, + History, Mail, Phone, UserPlus, Users, +} from 'lucide-react'; +import { Button } from '@/components/ui/button'; +import { Badge } from '@/components/ui/badge'; +import { LazyImage } from '@/components/ui/lazy-image'; +import BadgeStatus from '@/components/ui/badge-status'; +import { cn } from '@/lib/utils'; +import { IClient } from '../../../types'; +import { IProjectAssignment, ProjectAssignmentWorkOrderDetail } from '../../../type.assignment'; import { ManageTeam } from '../../../component/ManageTeam'; import UpdateTimelineStatus from '../../../component/UpdateTimelineStatus'; -import { LazyImage } from '@/components/ui/lazy-image'; interface Props { client: IClient | undefined; initialAssignment: IProjectAssignment; } +const TEAM_PREVIEW_LIMIT = 6; + +const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; + +/** Deterministic dd Mon yyyy, avoids locale differences between server and browser. */ +function formatAssignmentDate(dateStr?: string | null) { + if (!dateStr) return 'N/A'; + const d = new Date(dateStr); + if (isNaN(d.getTime())) return 'N/A'; + return `${String(d.getDate()).padStart(2, '0')} ${MONTHS[d.getMonth()]} ${d.getFullYear()}`; +} + +function diffInDays(start?: string | null, end?: string | null) { + if (!start || !end) return null; + const s = new Date(start); + const e = new Date(end); + if (isNaN(s.getTime()) || isNaN(e.getTime())) return null; + return Math.max(0, Math.round((e.getTime() - s.getTime()) / 86_400_000)); +} + +function pluralDays(n: number) { + return `${n} ${n === 1 ? 'day' : 'days'}`; +} + export default function AssignmentDetail({ client, initialAssignment: assignment }: Props) { - const [action, setAction] = useState<'MANAGE_EMPLOYEE' | 'UPDATE_STATUS' | undefined>() + const [action, setAction] = useState<'MANAGE_EMPLOYEE' | 'UPDATE_STATUS' | undefined>(); + const [showAllTeam, setShowAllTeam] = useState(false); - const router = useRouter(); + const isWorkOrder = !!assignment.wo_name; + const assignmentType = isWorkOrder ? 'Work Order' : 'Internal Memo'; + const illustrationSrc = isWorkOrder + ? '/assets/illustrations/work_order.jpg' + : '/assets/illustrations/internal_memo.jpg'; - const isProject = assignment.project?.code + const assignmentName = assignment.wo_name || assignment.im_name || 'Untitled Assignment'; + const assignmentCode = assignment.wo_code || assignment.im_code; + const assignmentStartDate = assignment.wo_start_date || assignment.im_start_date; + const assignmentEndDate = assignment.wo_end_date || assignment.im_end_date; + const assignmentDesc = assignment.wo_description || assignment.im_description; + const assignmentStatus = assignment.project?.status || assignment.project_assignment_status?.name; - const assignmentType = isProject ? 'Project' : 'IM' - const assignmentName = assignment.wo_name || assignment.im_name - const assignmentCode = assignment.wo_code || assignment.im_code - const assignmentStartDate = assignment.wo_start_date || assignment.im_start_date - const assignmentEndDate = assignment.wo_end_date || assignment.im_end_date - const assignmentDesc = assignment.wo_description || assignment.im_description - const assignmentStatus = assignment.project?.status || assignment.project_assignment_status?.name + const owner = client ?? assignment.client; + const clientHref = owner?.id ? `/task/client-detail/${owner.id}` : '/task'; - const statuslist = assignment.project_assignment_status_detail?.filter(status => status.start_date) || [] + const team = assignment.project_assignment_work_order_detail ?? []; + const visibleTeam = showAllTeam ? team : team.slice(0, TEAM_PREVIEW_LIMIT); + const hiddenTeamCount = team.length - visibleTeam.length; - const handleClose = () => { - setAction(undefined) - } + const statusHistory = assignment.project_assignment_status_detail?.filter(s => s.start_date) ?? []; + const currentEntry = statusHistory.find(s => !s.end_date) ?? statusHistory[0]; - const formatDate = (date: string) => - new Date(date).toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' }); + const duration = diffInDays(assignmentStartDate, assignmentEndDate); + + const handleClose = () => setAction(undefined); return ( <> - - {/* Header */} -
-
- -
-

Assignment Detail

- {!isProject && {assignmentType}} -
-
-
- -
-
+
+ + + + Back to {owner?.name ?? 'tasks'} + + -
- -
- - {/*
*/} -
-
- - {isProject ? 'Project' : 'Internal Memo'} - - + {/* Header: identity, status, primary action, key facts */} + +
+
+
+
+
-
-
-
- {isProject ? : } -
-
-

{isProject ? 'Work Order' : 'Internal Memo'}

-

- {assignmentName} -

-

{assignmentDesc}

-
+
+
+ + {isWorkOrder ? : } + {assignmentType} + + {assignmentStatus ? : null} + {assignmentCode ? ( + + {assignmentCode} + + ) : null}
-
- {/* Quick meta row */} -
- - - - +

+ {assignmentName} +

+ + {assignmentDesc ? ( +

+ {assignmentDesc} +

+ ) : null}
- -
- - +
- {isProject && ( - -
- Project context +
+ + + + +
+
+
+ +
+ {/* Main column */} +
+ + +
+ +
-
- -

{assignment.project?.name}

- - - Year {assignment.project?.year} - - -
-
- # Code: {assignment.project?.code} - - - {formatDate(assignment.project?.start_date!)} → {`${assignment.project?.end_date ? formatDate(assignment.project.end_date) : 'N/A'}`} - -
-

{assignment.project?.description ?? 'No description available.'}

- - )} +
+
- {!assignment.wo_name ? - - - No work orders defined for this assignment. - - - : null - } - - - -
-
- Team -
- -
- - - -
-
- -
- - {/* Right Column: Status History */} -
- - - - Assignment Timeline - - Timeline of status changes - - -
- {statuslist?.map((history, idx) => -
-
-
-
- - {history.project_assignment_status.name} - - - {history.start_date ? new Date(history.start_date).toLocaleDateString() : 'N/A'} - {history.end_date ? new Date(history.end_date).toLocaleDateString() : 'Present'} - -
-

- Recorded: {new Date(history.end_date!).toLocaleString()} -

-
+ {assignment.project?.id ? ( + + + +
+
- )} - {(!statuslist || statuslist.length === 0) && -

No history recorded yet.

- } -
- - +
+
+

+ {assignment.project.name} +

+ {assignment.project.code ? ( + {assignment.project.code} + ) : null} + {assignment.project.year ? ( + Year {assignment.project.year} + ) : null} +
+

+ + {formatAssignmentDate(assignment.project.start_date)} - {formatAssignmentDate(assignment.project.end_date)} +

+

+ {assignment.project.description || 'No description available.'} +

+
+ + + + + ) : null} + + {assignment.note ? ( + + +

+ {assignment.note} +

+
+
+ ) : null} + + + 0 ? `${team.length}` : undefined} + action={ + + } + > + {team.length === 0 ? ( +
+
+ +
+
+

Nobody is assigned yet

+

+ Add people from the team directory to start tracking who works on this assignment. +

+
+
+ ) : ( + <> +
    + {visibleTeam.map(member => ( + + ))} +
+ {team.length > TEAM_PREVIEW_LIMIT ? ( + + ) : null} + + )} +
+
+ + {/* Side rail: status history */} + + + {statusHistory.length === 0 ? ( +

+ No status changes recorded yet. Use Update status to log the first one. +

+ ) : ( +
    + {statusHistory.map(entry => { + const isCurrent = entry.id === currentEntry?.id; + const days = diffInDays(entry.start_date, entry.end_date); + return ( +
  1. + +
    + {isCurrent ? ( + + ) : ( + + {entry.project_assignment_status.name} + + )} + {isCurrent ? Current : null} +
    +

    + {formatAssignmentDate(entry.start_date)} - {entry.end_date ? formatAssignmentDate(entry.end_date) : 'Present'} +

    + {days !== null ? ( +

    {pluralDays(days)}

    + ) : null} +
  2. + ); + })} +
+ )} +
+
- +
- {action === 'UPDATE_STATUS' ? + {action === 'UPDATE_STATUS' ? ( - : null - } + ) : null} - {action === 'MANAGE_EMPLOYEE' ? + {action === 'MANAGE_EMPLOYEE' ? ( - : null - } + ) : null} ); } - -function MetaTile({ icon: Icon, label, value }: { icon: typeof Briefcase; label: string; value: string }) { +/** Entry reveal. Honors prefers-reduced-motion by rendering static. */ +function Reveal({ children, delay = 0, className }: { children: ReactNode; delay?: number; className?: string }) { + const reduce = useReducedMotion(); return ( -
-

- {label} -

-

{value}

+ + {children} + + ); +} + +function Surface({ + title, meta, action, children, +}: { title: string; meta?: string; action?: ReactNode; children: ReactNode }) { + return ( +
+
+

+ {title} + {meta ? ( + {meta} + ) : null} +

+ {action} +
+ {children} +
+ ); +} + +function Fact({ label, value }: { label: string; value: string }) { + return ( +
+
{label}
+
{value}
); } +function initials(name?: string) { + return (name ?? '') + .split(' ') + .map(n => n[0]) + .filter(Boolean) + .slice(0, 2) + .join('') + .toUpperCase(); +} -function PartyCard({ label, party, accent }: { label: string; party: any; accent: string }) { - function initials(name: string) { - return name?.split(" ").map((n) => n[0]).filter(Boolean).slice(0, 2).join("").toUpperCase(); - } +function PartyRow({ + role, party, href, +}: { role: string; party?: { name?: string; photo?: string; description?: string | null; code?: string } | null; href?: string }) { + const body = ( + <> +
+ {party?.photo ? ( + + ) : ( +
+ {initials(party?.name) || '-'} +
+ )} +
+
+

{role}

+

+ {party?.name ?? 'Not set'} +

+ {party?.description ? ( +

{party.description}

+ ) : null} +
+ + ); - return ( - -
- {label} -
-
-
- {party?.photo ? - - : -
- {initials(party?.name)} -
- } -
-
-

{party?.name}

-

{party?.description ?? 'No description available.'}

-
-
-
+ const className = 'group flex items-center gap-4 py-4 first:pt-0 last:pb-0'; + + return href ? ( + + {body} + + + ) : ( +
{body}
+ ); +} + +function TeamMember({ member }: { member: ProjectAssignmentWorkOrderDetail }) { + const user = member.user; + const name = user?.fullname || user?.name || 'Unnamed member'; + return ( +
  • + +
    +

    {name}

    + {user?.position?.name ? ( +

    {user.position.name}

    + ) : null} +
    + {user?.email ? ( + + + {user.email} + + ) : null} + {user?.phone_number ? ( + + + {user.phone_number} + + ) : null} +
    + {member.start_date ? ( +

    + {formatAssignmentDate(member.start_date)} - {member.end_date ? formatAssignmentDate(member.end_date) : 'Open'} +

    + ) : null} +
    +
  • ); } diff --git a/app/(dashboard)/task/client-detail/[client_id]/[assignment_id]/loading.tsx b/app/(dashboard)/task/client-detail/[client_id]/[assignment_id]/loading.tsx new file mode 100644 index 0000000..3daf51c --- /dev/null +++ b/app/(dashboard)/task/client-detail/[client_id]/[assignment_id]/loading.tsx @@ -0,0 +1,38 @@ +export default function Loading() { + return ( +
    +
    + +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + {Array.from({ length: 4 }).map((_, i) => ( +
    +
    +
    +
    + ))} +
    +
    + +
    +
    +
    +
    +
    +
    +
    +
    + ); +} diff --git a/deploy.ps1 b/deploy.ps1 new file mode 100644 index 0000000..8293e4f --- /dev/null +++ b/deploy.ps1 @@ -0,0 +1,405 @@ +<# +.SYNOPSIS + Script Deployment Otomatis untuk hats-app (Next.js 16 / React 19) dari Windows ke Server VPS. +.DESCRIPTION + 1. Membaca konfigurasi kredensial VPS dari .env.deploy atau parameter CLI. + 2. Menjalankan proses build: Next.js build dengan environment target (staging / production). + 3. Menyesuaikan path di '.next/required-server-files.json' agar kompatibel dengan lingkungan Linux VPS. + 4. Mengompresi folder .next, public, package.json, dan next.config.ts menjadi arsip .tar.gz (mengecualikan cache & dev artifacts). + 5. Mengunggah arsip ke /tmp di VPS via SCP dengan autentikasi Password / Key non-interaktif. + 6. Mengekstrak arsip di server VPS ke direktori target (/home/repositories/...). + 7. Mereload service PM2 (hats-app / hats-app-dev) di VPS dan membersihkan file arsip sementara. +.PARAMETER Target + Target environment: 'staging' (default) atau 'production'. +.PARAMETER ConfigFile + Path ke file konfigurasi deploy (default: .env.deploy). +.PARAMETER SkipBuild + Lewati langkah build jika folder .next sudah siap. +.PARAMETER UploadEnv + Unggah file environment (.env.staging / .env.production) ke VPS. +.PARAMETER InstallDeps + Jalankan 'npm install --legacy-peer-deps' di VPS jika ada perubahan package dependencies. +.PARAMETER GitPull + Mode alternatif: Jalankan git pull & restart PM2 langsung di VPS tanpa build lokal. +.PARAMETER Force + Abaikan validasi branch master saat deployment ke production. +.EXAMPLE + .\deploy.ps1 staging + .\deploy.ps1 production + .\deploy.ps1 staging -SkipBuild + .\deploy.ps1 staging -InstallDeps + .\deploy.ps1 staging -GitPull + .\deploy.ps1 production -Force +#> + +[CmdletBinding()] +param ( + [Parameter(Position = 0)] + [ValidateSet("staging", "stag", "dev", "development", "production", "prod")] + [string]$Target = "staging", + + [string]$ConfigFile = ".env.deploy", + [string]$HostOverride = "", + [string]$UserOverride = "", + [string]$PasswordOverride = "", + [switch]$SkipBuild, + [switch]$UploadEnv, + [switch]$InstallDeps, + [switch]$GitPull, + [switch]$Force +) + +$ErrorActionPreference = "Stop" + +# Pindah ke direktori root hats-app +$ScriptRoot = Split-Path -Parent $MyInvocation.MyCommand.Path +Set-Location $ScriptRoot + +Write-Host "=======================================================" -ForegroundColor Cyan +Write-Host "[DEPLOYER] HATS-APP - WINDOWS VPS AUTO DEPLOYER (NEXT.JS)" -ForegroundColor Cyan +Write-Host "=======================================================" -ForegroundColor Cyan + +# 1. Cek & Muat Konfigurasi .env.deploy +if (-not (Test-Path $ConfigFile)) { + if (Test-Path ".env.deploy.example") { + Write-Host "[WARN] File konfigurasi '$ConfigFile' belum ditemukan." -ForegroundColor Yellow + Write-Host " Menyalin template '.env.deploy.example' ke '$ConfigFile'..." -ForegroundColor Yellow + Copy-Item ".env.deploy.example" $ConfigFile + Write-Host "[STOP] Silakan buka '$ConfigFile' dan sesuaikan kredensial VPS Anda!" -ForegroundColor Red + exit 1 + } else { + Write-Host "[ERROR] File konfigurasi '$ConfigFile' tidak ditemukan." -ForegroundColor Red + exit 1 + } +} + +# Parsing file konfigurasi key=value +$config = @{} +Get-Content $ConfigFile | ForEach-Object { + $line = $_.Trim() + if ($line -and -not $line.StartsWith("#") -and $line -match "^([^=]+)=(.*)$") { + $key = $matches[1].Trim() + $val = $matches[2].Trim().Trim('"').Trim("'") + $config[$key] = $val + } +} + +# Helper untuk mendapatkan nilai dengan fallback ke env variable +function Get-ConfigValue($key, $defaultValue = "") { + $envVal = [System.Environment]::GetEnvironmentVariable($key) + if ($envVal) { return $envVal } + if ($config.ContainsKey($key) -and $config[$key]) { return $config[$key] } + return $defaultValue +} + +# Parameter mapping +$isProd = ($Target -in @("production", "prod")) +$targetName = if ($isProd) { "production" } else { "staging" } +$targetEnvFile = if ($isProd) { ".env.production" } else { ".env.staging" } + +$vpsHost = if ($HostOverride) { $HostOverride } else { Get-ConfigValue "VPS_HOST" "36.66.3.44" } +$vpsPort = Get-ConfigValue "VPS_PORT" "22" +$vpsUser = if ($UserOverride) { $UserOverride } else { Get-ConfigValue "VPS_USER" "root" } +$vpsPassword = if ($PasswordOverride) { $PasswordOverride } else { Get-ConfigValue "VPS_PASSWORD" "" } +$vpsKeyPath = Get-ConfigValue "VPS_KEY_PATH" "" + +# Target path di VPS +$defaultStagingPath = "/home/repositories/hats-app-dev/hats-app" +$defaultProductionPath = "/home/repositories/hats-app" + +$vpsBasePath = if ($isProd) { + Get-ConfigValue "VPS_PATH_PRODUCTION" $defaultProductionPath +} else { + Get-ConfigValue "VPS_PATH_STAGING" $defaultStagingPath +} + +# Nama aplikasi PM2 +$defaultPm2App = if ($isProd) { "hats-app" } else { "hats-app-dev" } +$pm2AppName = if ($isProd) { + Get-ConfigValue "PM2_APP_PRODUCTION" $defaultPm2App +} else { + Get-ConfigValue "PM2_APP_STAGING" $defaultPm2App +} + +$targetPort = if ($isProd) { + Get-ConfigValue "PM2_PORT_PRODUCTION" "7002" +} else { + Get-ConfigValue "PM2_PORT_STAGING" "7005" +} + +$customPostDeploy = Get-ConfigValue "POST_DEPLOY_CMD" "" +$postDeployCmd = if ($customPostDeploy) { + $customPostDeploy +} else { + "if pm2 describe $pm2AppName > /dev/null 2>&1; then echo '[PM2] Mereload service $pm2AppName...' && (pm2 reload $pm2AppName --update-env || pm2 restart $pm2AppName --update-env); else echo '[PM2] Service $pm2AppName tidak ditemukan. Mendaftarkan service PM2 baru...' && cd '$vpsBasePath' && pm2 start npm --name '$pm2AppName' -- start && pm2 save; fi" +} + +# Validasi Kredensial +if (-not $vpsHost) { + Write-Host "[ERROR] Host VPS belum ditentukan di '$ConfigFile' (VPS_HOST)." -ForegroundColor Red + exit 1 +} +if (-not $vpsPassword -and -not $vpsKeyPath) { + Write-Host "[ERROR] Password VPS (VPS_PASSWORD) atau SSH Key (VPS_KEY_PATH) belum diisi di '$ConfigFile'." -ForegroundColor Red + exit 1 +} + +# Cek Git Branch Saat Ini +$currentBranch = "" +try { + $currentBranch = (git branch --show-current 2>$null).Trim() + if (-not $currentBranch) { + $currentBranch = (git rev-parse --abbrev-ref HEAD 2>$null).Trim() + } +} catch { + $currentBranch = "unknown" +} + +Write-Host ("[INFO] Target Environment : " + $targetName.ToUpper()) -ForegroundColor Green +Write-Host ("[INFO] Current Git Branch : " + $currentBranch) -ForegroundColor Green +Write-Host ("[INFO] Target Env File : " + $targetEnvFile) -ForegroundColor Green +Write-Host ("[INFO] Target App Port : " + $targetPort) -ForegroundColor Green +Write-Host ("[INFO] VPS Host : " + $vpsHost + ":" + $vpsPort) -ForegroundColor Green +Write-Host ("[INFO] SSH User : " + $vpsUser) -ForegroundColor Green +Write-Host ("[INFO] Target Path di VPS : " + $vpsBasePath) -ForegroundColor Green +Write-Host ("[INFO] PM2 Service Name : " + $pm2AppName) -ForegroundColor Green +Write-Host "=======================================================" -ForegroundColor Cyan + +# Validasi Branch Khusus Target Production +if ($isProd -and $currentBranch -ne "master") { + if ($Force) { + Write-Host "[WARN] TARGET ADALAH PRODUCTION DAN BRANCH BUKAN 'master' ('$currentBranch')!" -ForegroundColor Yellow + Write-Host " Melanjutkan proses karena flag -Force aktif..." -ForegroundColor Yellow + } else { + Write-Host "=======================================================" -ForegroundColor Red + Write-Host "[BLOCKED] DEPLOYMENT KE PRODUCTION DIBATALKAN!" -ForegroundColor Red + Write-Host " Branch git aktif : '$currentBranch'" -ForegroundColor Yellow + Write-Host " Deployment production HANYA diperbolehkan dari branch 'master'." -ForegroundColor Yellow + Write-Host " Silakan pindah atau merge ke branch 'master' terlebih dahulu:" -ForegroundColor Yellow + Write-Host " git checkout master" -ForegroundColor Cyan + Write-Host " git merge $currentBranch" -ForegroundColor Cyan + Write-Host " (Atau gunakan flag -Force jika benar-benar berniat mem-bypass)" -ForegroundColor Gray + Write-Host "=======================================================" -ForegroundColor Red + exit 1 + } +} + +# Setup Autentikasi Non-Interaktif Windows OpenSSH +$tempAskPass = [System.IO.Path]::GetTempFileName() + ".bat" +"@echo $vpsPassword" | Out-File -FilePath $tempAskPass -Encoding ascii -Force + +$env:SSH_ASKPASS = $tempAskPass +$env:SSH_ASKPASS_REQUIRE = "force" +$env:DISPLAY = "dummy:0" +$env:VPS_PASSWORD = $vpsPassword + +$sshOptions = @( + "-P", $vpsPort, + "-o", "StrictHostKeyChecking=no", + "-o", "UserKnownHostsFile=/dev/null", + "-o", "LogLevel=ERROR" +) + +$sshCmdOptions = @( + "-p", $vpsPort, + "-o", "StrictHostKeyChecking=no", + "-o", "UserKnownHostsFile=/dev/null", + "-o", "LogLevel=ERROR" +) + +if ($vpsKeyPath -and (Test-Path $vpsKeyPath)) { + $sshOptions += @("-i", $vpsKeyPath) + $sshCmdOptions += @("-i", $vpsKeyPath) +} + +$remoteUserHost = "$vpsUser@$vpsHost" +$archiveFile = "hats_app_build_" + (Get-Date -Format "yyyyMMdd_HHmmss") + ".tar.gz" +$serverFilesJson = ".next\required-server-files.json" +$serverFilesBak = ".next\required-server-files.json.bak" +$pkgJsonPath = "package.json" +$pkgJsonBak = "package.json.bak" +$tempEnvProdLocal = ".env.production.local" +$hasTempEnv = $false + +try { + # Mode Alternatif: Git Pull langsung di VPS + if ($GitPull) { + Write-Host "[GIT] Mode -GitPull aktif: Menjalankan git pull & restart PM2 di server..." -ForegroundColor Yellow + $gitCmd = "cd '$vpsBasePath' && git pull" + if ($InstallDeps) { + $gitCmd += " && npm install --legacy-peer-deps" + } + $gitCmd += " && $postDeployCmd && pm2 status $pm2AppName" + & ssh.exe @sshCmdOptions $remoteUserHost $gitCmd + if ($LASTEXITCODE -ne 0) { + throw "Gagal menjalankan git pull atau reload PM2 di server (Exit code: $LASTEXITCODE)" + } + Write-Host "[SUCCESS] Git pull dan reload service berhasil!" -ForegroundColor Green + return + } + + # Step 1: Build Application (Next.js build) + if (-not $SkipBuild) { + Write-Host "[BUILD] [1/4] Menjalankan build Next.js untuk $targetName..." -ForegroundColor Yellow + + # Persiapkan environment file untuk build + if (-not $isProd -and (Test-Path $targetEnvFile)) { + Write-Host " Menyiapkan '$targetEnvFile' -> '$tempEnvProdLocal' untuk build staging..." -ForegroundColor Cyan + Copy-Item $targetEnvFile $tempEnvProdLocal -Force + $hasTempEnv = $true + } + + $buildStart = Get-Date + + # Jalankan build melalui npm.cmd (menghindari restriction PowerShell execution policy) + cmd /c "npm run build" + if ($LASTEXITCODE -ne 0) { + throw "Build Next.js gagal! Silakan periksa pesan error di atas." + } + + $buildDuration = (Get-Date) - $buildStart + $seconds = [math]::Round($buildDuration.TotalSeconds, 1) + Write-Host "[OK] Build Next.js berhasil dalam $seconds detik." -ForegroundColor Green + } else { + Write-Host "[SKIP] [1/4] Melewati proses build (--SkipBuild aktif)." -ForegroundColor Gray + } + + # Verifikasi folder .next + if (-not (Test-Path ".next")) { + throw "Folder '.next' tidak ditemukan! Pastikan proses build berhasil." + } + + # Step 2: Normalisasi path untuk runtime Linux & Kompresi Artifact + Write-Host "[PREP] [2/4] Menyesuaikan konfigurasi runtime server Next.js..." -ForegroundColor Yellow + + if (Test-Path $serverFilesJson) { + Copy-Item $serverFilesJson $serverFilesBak -Force + node -e "const fs = require('fs'); const p = process.argv[1]; const target = process.argv[2]; if (fs.existsSync(p)) { const d = JSON.parse(fs.readFileSync(p, 'utf8')); d.appDir = target; if (d.config && d.config.turbopack) d.config.turbopack.root = target; d.files = (d.files || []).map(f => f.replace(/\\\\/g, '/')); fs.writeFileSync(p, JSON.stringify(d, null, 2)); }" $serverFilesJson $vpsBasePath + Write-Host " Konfigurasi path di '$serverFilesJson' disesuaikan untuk Linux." -ForegroundColor Gray + } + + if (Test-Path $pkgJsonPath) { + Copy-Item $pkgJsonPath $pkgJsonBak -Force + node -e "const fs = require('fs'); const p = process.argv[1]; const port = process.argv[2]; if (fs.existsSync(p)) { const pkg = JSON.parse(fs.readFileSync(p, 'utf8')); if (pkg.scripts) { pkg.scripts.start = 'next start -p ' + port; fs.writeFileSync(p, JSON.stringify(pkg, null, 2)); } }" $pkgJsonPath $targetPort + Write-Host " Script start pada '$pkgJsonPath' disesuaikan ke port $targetPort." -ForegroundColor Gray + } + + Write-Host "[ZIP] [2/4] Mengompresi build artifact menjadi '$archiveFile'..." -ForegroundColor Yellow + if (Test-Path $archiveFile) { Remove-Item $archiveFile -Force } + + $tarItems = @(".next", "public", "package.json") + if (Test-Path "next.config.ts") { $tarItems += "next.config.ts" } + if (Test-Path "next.config.mjs") { $tarItems += "next.config.mjs" } + if (Test-Path "next.config.js") { $tarItems += "next.config.js" } + + # Jika user memilih -UploadEnv, sertakan env yang sesuai + if ($UploadEnv -and (Test-Path $targetEnvFile)) { + Write-Host " Menyertakan $targetEnvFile dalam arsip..." -ForegroundColor Cyan + $tarItems += $targetEnvFile + } + + # Buat arsip tar.gz dengan exclude cache, dev, dan diagnostics + tar.exe -czf $archiveFile ` + --exclude=".next/cache" ` + --exclude=".next\cache" ` + --exclude=".next/dev" ` + --exclude=".next\dev" ` + --exclude=".next/diagnostics" ` + --exclude=".next\diagnostics" ` + --exclude="*.log" ` + @tarItems + + if ($LASTEXITCODE -ne 0 -or -not (Test-Path $archiveFile)) { + throw "Gagal mengompresi artifact ke $archiveFile!" + } + + $archiveSize = [math]::Round((Get-Item $archiveFile).Length / 1MB, 2) + Write-Host "[OK] Berhasil dikompresi: $archiveSize MB" -ForegroundColor Green + + # Step 3: Upload archive ke Server VPS + $remoteTempArchive = "/tmp/hats_app_build_" + (Get-Date -Format "yyyyMMdd_HHmmss") + ".tar.gz" + Write-Host "[UPLOAD] [3/4] Mengunggah $archiveFile ke $vpsHost`:$remoteTempArchive..." -ForegroundColor Yellow + + $remoteDest = "$remoteUserHost`:$remoteTempArchive" + $uploadStart = Get-Date + & scp.exe @sshOptions $archiveFile $remoteDest + if ($LASTEXITCODE -ne 0) { + throw "Gagal mentransfer file melalui SCP (Exit code: $LASTEXITCODE)" + } + $uploadDuration = (Get-Date) - $uploadStart + $uploadSeconds = [math]::Round($uploadDuration.TotalSeconds, 1) + Write-Host "[OK] Upload selesai dalam $uploadSeconds detik." -ForegroundColor Green + + # Step 4: Ekstrak arsip di Server VPS & Restart PM2 + Write-Host "[EXTRACT] [4/4] Mengekstrak file ke $vpsBasePath di server VPS..." -ForegroundColor Yellow + + $remoteCommands = @( + "mkdir -p '$vpsBasePath'", + "tar -xzf '$remoteTempArchive' -C '$vpsBasePath'", + "rm -f '$remoteTempArchive'" + ) + + if ($UploadEnv -and (Test-Path $targetEnvFile)) { + $envFilename = Split-Path -Leaf $targetEnvFile + $remoteCommands += "cp -f '$vpsBasePath/$envFilename' '$vpsBasePath/.env.production'" + } + + if ($InstallDeps) { + Write-Host "[DEPS] Menjalankan npm install di server..." -ForegroundColor Yellow + $remoteCommands += "cd '$vpsBasePath' && npm install --legacy-peer-deps" + } + + if ($postDeployCmd) { + Write-Host "[RELOAD] Menjalankan reload service PM2 ($pm2AppName)..." -ForegroundColor Yellow + $remoteCommands += $postDeployCmd + } + + $fullRemoteCmd = $remoteCommands -join " && " + & ssh.exe @sshCmdOptions $remoteUserHost $fullRemoteCmd + if ($LASTEXITCODE -ne 0) { + throw "Gagal mengekstrak atau mereload service di server remote (Exit code: $LASTEXITCODE)" + } + Write-Host "[OK] File berhasil diekstrak dan service direload." -ForegroundColor Green + + # Tampilkan status PM2 + Write-Host "[STATUS] Memeriksa status proses PM2..." -ForegroundColor Yellow + $statusCmd = "pm2 status $pm2AppName" + & ssh.exe @sshCmdOptions $remoteUserHost $statusCmd + +} catch { + Write-Host "[ERROR] Terjadi error saat deployment: $_" -ForegroundColor Red + exit 1 +} finally { + # 1. Pulihkan required-server-files.json lokal jika tadi di-backup + if (Test-Path $serverFilesBak) { + Copy-Item $serverFilesBak $serverFilesJson -Force + Remove-Item $serverFilesBak -Force -ErrorAction SilentlyContinue + } + # 2. Pulihkan package.json lokal jika tadi disesuaikan + if (Test-Path $pkgJsonBak) { + Copy-Item $pkgJsonBak $pkgJsonPath -Force + Remove-Item $pkgJsonBak -Force -ErrorAction SilentlyContinue + } + # 3. Hapus temporary .env.production.local + if ($hasTempEnv -and (Test-Path $tempEnvProdLocal)) { + Remove-Item $tempEnvProdLocal -Force -ErrorAction SilentlyContinue + } + # 3. Hapus arsip lokal + if (Test-Path $archiveFile) { + Remove-Item $archiveFile -Force -ErrorAction SilentlyContinue + } + # 4. Hapus askpass bat dan bersihkan environment variables + if (Test-Path $tempAskPass) { + Remove-Item $tempAskPass -Force -ErrorAction SilentlyContinue + } + Remove-Item Env:\SSH_ASKPASS -ErrorAction SilentlyContinue + Remove-Item Env:\SSH_ASKPASS_REQUIRE -ErrorAction SilentlyContinue + Remove-Item Env:\VPS_PASSWORD -ErrorAction SilentlyContinue + Remove-Item Env:\DISPLAY -ErrorAction SilentlyContinue +} + +Write-Host "=======================================================" -ForegroundColor Cyan +Write-Host "[SUCCESS] DEPLOYMENT HATS-APP SELESAI DENGAN SUKSES!" -ForegroundColor Green +Write-Host "[PATH] Server Path : $vpsBasePath" -ForegroundColor Green +Write-Host "[PM2] App Name : $pm2AppName" -ForegroundColor Green +Write-Host "=======================================================" -ForegroundColor Cyan diff --git a/package.json b/package.json index 4a63416..c31d804 100644 --- a/package.json +++ b/package.json @@ -18,7 +18,9 @@ "start": "next start -p 7002", "lint": "eslint", "install:clean": "git pull origin master && rm -rf node_modules package-lock.json .next && npm install --legacy-peer-deps", - "build:prod": "git pull origin master && rm -rf .next/ package-lock.json && pm2 stop 6 && npm run build && pm2 restart 6" + "build:prod": "git pull origin master && rm -rf .next/ package-lock.json && pm2 stop 6 && npm run build && pm2 restart 6", + "deploy:staging": "powershell -ExecutionPolicy Bypass -File ./deploy.ps1 -Target staging", + "deploy:prod": "powershell -ExecutionPolicy Bypass -File ./deploy.ps1 -Target production" }, "dependencies": { "@bprogress/next": "^3.2.12", diff --git a/tsconfig.json b/tsconfig.json index 3a13f90..7ca0f21 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -30,5 +30,5 @@ ".next/dev/types/**/*.ts", "**/*.mts" ], - "exclude": ["node_modules"] + "exclude": ["node_modules", "**/*.old.tsx", "**/*.old.ts"] }