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.
This commit is contained in:
Ichsan Kurniawan
2026-10-05 19:52:11 +07:00
parent ffcf3c6e58
commit d0db9ee429
9 changed files with 919 additions and 235 deletions
+25
View File
@@ -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
+8 -15
View File
@@ -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"
NEXT_PUBLIC_APP_VERSION = "v1.2.0"
NEXT_PUBLIC_MANAGER_USER_ID = '2'
NEXT_PUBLIC_S3_IMAGE_URL = https://cdn.hisnutech.my.id/public
+21
View File
@@ -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
+1
View File
@@ -32,6 +32,7 @@ yarn-error.log*
# env files (can opt-in for committing if needed)
# .env*
.env.deploy
# vercel
.vercel
@@ -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 (
<>
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
className="flex-1 space-y-8 p-6 sm:p-8 pt-6"
<div className="mx-auto w-full max-w-7xl flex-1 space-y-6 p-6 pt-6 sm:p-8">
<Reveal>
<Link
href={clientHref}
className="group inline-flex items-center gap-1.5 text-sm text-muted-foreground transition-colors hover:text-foreground"
>
{/* Header */}
<div className="flex flex-col md:flex-row md:items-center justify-between gap-6">
<div className="space-y-2">
<Button variant="ghost" size="sm" onClick={() => router.back()} className="p-0 h-auto hover:bg-transparent text-muted-foreground mb-2">
<ArrowLeft className="w-4 h-4 mr-1" />
Back to {client?.name}
</Button>
<div className="flex items-center gap-3">
<h1 className="text-4xl font-bold tracking-tight">Assignment Detail</h1>
{!isProject && <Badge variant={'info'} className="text-lg px-3 py-0">{assignmentType}</Badge>}
</div>
</div>
<div className="flex gap-3">
<Button onClick={() => setAction('UPDATE_STATUS')} className="gap-2">
<History className="w-4 h-4" />
Update Assignment Status
</Button>
</div>
<ArrowLeft className="h-4 w-4 transition-transform duration-300 group-hover:-translate-x-0.5" />
<span>Back to {owner?.name ?? 'tasks'}</span>
</Link>
</Reveal>
{/* Header: identity, status, primary action, key facts */}
<Reveal delay={0.04}>
<section aria-labelledby="assignment-title" className="rounded-2xl border border-border bg-card p-5 sm:p-7">
<div className="flex flex-col gap-6 md:flex-row md:items-start md:justify-between">
<div className="flex min-w-0 items-start gap-4 sm:gap-5">
<div className="flex h-20 w-20 shrink-0 items-center justify-center overflow-hidden rounded-2xl border border-border bg-zinc-50 p-1 sm:h-24 sm:w-24 dark:bg-zinc-100">
<LazyImage
src={illustrationSrc}
alt={`${assignmentType} emblem`}
className="h-full w-full bg-transparent"
imgClassName="object-contain"
/>
</div>
<div className="grid gap-8 lg:grid-cols-3">
<div className="lg:col-span-2 space-y-8">
<Card900 className={`relative overflow-hidden border-border bg-card p-6 md:p-8`}>
{/* <div className={`pointer-events-none absolute inset-0 bg-linear-to-br from-his/25 via-his/5 to-transparent`} /> */}
<div className="relative">
<div className="flex flex-wrap items-center gap-2 text-[11px] font-bold uppercase tracking-[0.2em]">
<Badge variant={isProject ? 'default' : 'info'}>
{isProject ? 'Project' : 'Internal Memo'}
<div className="min-w-0 space-y-2.5">
<div className="flex flex-wrap items-center gap-2">
<Badge variant="outline" className="gap-1 rounded-lg px-2 py-0.5 text-xs font-medium">
{isWorkOrder ? <Briefcase className="h-3 w-3" /> : <FileText className="h-3 w-3" />}
{assignmentType}
</Badge>
<BadgeStatus status={assignmentStatus} />
{assignmentStatus ? <BadgeStatus status={assignmentStatus} /> : null}
{assignmentCode ? (
<span className="rounded-lg border border-border bg-muted/50 px-2 py-0.5 font-mono text-xs text-muted-foreground">
{assignmentCode}
</span>
) : null}
</div>
<div className="mt-4 flex flex-col gap-5 md:flex-row md:items-start md:justify-between">
<div className="flex items-start gap-4">
<div className={`flex h-12 sm:h-16 w-12 sm:w-16 shrink-0 items-center justify-center rounded-2xl border border-border bg-background/60 ${isProject ? 'text-his' : 'text-type-memo'}`}>
{isProject ? <Briefcase className="h-5 w-5 sm:h-8 sm:w-8" /> : <FileText className="h-5 w-5 sm:h-8 sm:w-8" />}
</div>
<div className="min-w-0">
<p className={`text-xs font-bold uppercase tracking-[0.2em] ${isProject ? 'text-his' : 'text-type-memo'}`}>{isProject ? 'Work Order' : 'Internal Memo'}</p>
<h1 className="mt-1 text-3xl font-bold tracking-tight text-foreground md:text-4xl">
<h1 id="assignment-title" className="text-balance text-2xl font-semibold tracking-tight text-foreground md:text-3xl">
{assignmentName}
</h1>
<p className="mt-2 max-w-2xl text-sm text-muted-foreground">{assignmentDesc}</p>
</div>
{assignmentDesc ? (
<p className="max-w-[65ch] text-sm leading-relaxed text-muted-foreground">
{assignmentDesc}
</p>
) : null}
</div>
</div>
{/* Quick meta row */}
<div className="mt-6 grid grid-cols-2 gap-3 sm:grid-cols-4">
<MetaTile icon={Hash} label={`${isProject ? 'WO' : 'IM'} Code`} value={assignmentCode} />
<MetaTile icon={Calendar} label="Start" value={new Date(assignmentStartDate).toLocaleDateString()} />
<MetaTile icon={Calendar} label="End" value={assignmentEndDate ? new Date(assignmentEndDate).toLocaleDateString() : 'N/A'} />
<MetaTile icon={Users} label="Team" value={`${assignment.project_assignment_work_order_detail?.length} People`} />
</div>
</div>
</Card900>
<div className="grid gap-5 md:grid-cols-2">
<PartyCard label="Client" party={client} accent="ring-primary/30" />
<PartyCard label="End User" party={assignment.end_user} accent="ring-primary/30" />
</div>
{isProject && (
<Card900 className="p-6 gap-5">
<div className="flex items-center gap-1.5 text-[10px] font-bold uppercase tracking-[0.18em] text-muted-foreground">
<FileText className="h-3 w-3" /> Project context
</div>
<div className='transition duration-300'>
<Link href={`/task/client-detail/${client?.id}/project-detail/${assignment.project?.id}`} className='flex group hover:space-x-3'>
<h2 className="font-semibold text-foreground group-hover:underline duration-300 hover:text-his">{assignment.project?.name}</h2>
<Button size="icon" variant="secondary" className="h-5 w-5 rounded-full opacity-0 group-hover:opacity-100 transition-opacity cursor-pointer duration-300">
<ExternalLink className="w-4 h-4" />
<Button
onClick={() => setAction('UPDATE_STATUS')}
className="w-full shrink-0 gap-2 transition-transform active:scale-[0.98] md:w-auto"
>
<History className="h-4 w-4" />
Update status
</Button>
<span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-muted text-muted-foreground">
Year {assignment.project?.year}
</span>
</div>
<dl className="mt-7 grid grid-cols-2 gap-x-6 gap-y-5 border-t border-border/70 pt-6 sm:grid-cols-4">
<Fact label="Start" value={formatAssignmentDate(assignmentStartDate)} />
<Fact label="End" value={formatAssignmentDate(assignmentEndDate)} />
<Fact label="Duration" value={duration === null ? 'N/A' : pluralDays(duration)} />
<Fact label="Team" value={team.length === 1 ? '1 person' : `${team.length} people`} />
</dl>
</section>
</Reveal>
<div className="grid items-start gap-6 lg:grid-cols-[minmax(0,1fr)_360px]">
{/* Main column */}
<div className="min-w-0 space-y-6">
<Reveal delay={0.08}>
<Surface title="Client and end user">
<div className="divide-y divide-border/70">
<PartyRow
role="Client"
party={owner}
href={owner?.id ? clientHref : undefined}
/>
<PartyRow role="End user" party={assignment.end_user} />
</div>
</Surface>
</Reveal>
{assignment.project?.id ? (
<Reveal delay={0.12}>
<Surface title="Project">
<Link
href={`/task/client-detail/${owner?.id}/project-detail/${assignment.project.id}`}
className="group flex items-start gap-4 rounded-xl p-2 -m-2 transition-colors hover:bg-muted/40"
>
<div className="flex h-11 w-11 shrink-0 items-center justify-center rounded-xl border border-border bg-muted/40 text-muted-foreground transition-colors group-hover:text-his">
<FolderGit2 className="h-5 w-5" />
</div>
<div className="min-w-0 flex-1 space-y-1.5">
<div className="flex flex-wrap items-center gap-x-2.5 gap-y-1">
<p className="font-medium text-foreground transition-colors group-hover:text-his">
{assignment.project.name}
</p>
{assignment.project.code ? (
<span className="font-mono text-xs text-muted-foreground">{assignment.project.code}</span>
) : null}
{assignment.project.year ? (
<span className="text-xs text-muted-foreground">Year {assignment.project.year}</span>
) : null}
</div>
<p className="flex items-center gap-1.5 text-xs text-muted-foreground">
<CalendarDays className="h-3.5 w-3.5" />
{formatAssignmentDate(assignment.project.start_date)} - {formatAssignmentDate(assignment.project.end_date)}
</p>
<p className="line-clamp-3 max-w-[65ch] text-sm leading-relaxed text-muted-foreground">
{assignment.project.description || 'No description available.'}
</p>
</div>
<ExternalLink className="mt-1 h-4 w-4 shrink-0 text-muted-foreground/60 transition-colors group-hover:text-his" />
</Link>
</div>
<div className="flex items-center gap-4 text-sm">
<span className="text-muted-foreground"># Code: <span className="text-foreground/80">{assignment.project?.code}</span></span>
<span className="inline-flex items-center gap-1.5 text-muted-foreground">
<CalendarRange size={16} />
{formatDate(assignment.project?.start_date!)} → {`${assignment.project?.end_date ? formatDate(assignment.project.end_date) : 'N/A'}`}
</span>
</div>
<p className='text-muted-foreground text-xs sm:text-sm'>{assignment.project?.description ?? 'No description available.'}</p>
</Card900>
)}
</Surface>
</Reveal>
) : null}
{!assignment.wo_name ?
<Card className="border-dashed bg-accent/10">
<CardContent className="py-10 text-center text-muted-foreground">
No work orders defined for this assignment.
</CardContent>
</Card>
: null
}
{assignment.note ? (
<Reveal delay={0.14}>
<Surface title="Notes">
<p className="max-w-[65ch] whitespace-pre-line text-sm leading-relaxed text-foreground/90">
{assignment.note}
</p>
</Surface>
</Reveal>
) : null}
<Card900 className="overflow-hidden border-l-4 border-l-primary">
<CardContent className="p-6 pt-2">
<div className='flex items-center justify-between mb-6 sm:mb-8'>
<div className="flex items-center gap-1.5 text-xs font-bold uppercase tracking-[0.18em] text-muted-foreground">
<Users className="h-4 w-4" /> Team
</div>
<Button onClick={() => setAction('MANAGE_EMPLOYEE')} className="gap-2" size='sm'>
<UserPlus className="w-4 h-4" />
Manage Team
<Reveal delay={0.16}>
<Surface
title="Team"
meta={team.length > 0 ? `${team.length}` : undefined}
action={
<Button
onClick={() => setAction('MANAGE_EMPLOYEE')}
variant="outline"
size="sm"
className="gap-1.5 transition-transform active:scale-[0.98]"
>
<UserPlus className="h-4 w-4" />
Manage team
</Button>
}
>
{team.length === 0 ? (
<div className="flex flex-col items-center gap-3 rounded-xl border border-dashed border-border bg-muted/20 px-6 py-10 text-center">
<div className="flex h-10 w-10 items-center justify-center rounded-xl bg-muted text-muted-foreground">
<Users className="h-5 w-5" />
</div>
<AssignedPeople people={assignment.project_assignment_work_order_detail} defaultOpen={false} />
</CardContent>
</Card900>
</div>
{/* Right Column: Status History */}
<div className="space-y-8">
<Card900>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<History className="w-5 h-5 text-primary" /> Assignment Timeline
</CardTitle>
<CardDescription>Timeline of status changes</CardDescription>
</CardHeader>
<CardContent>
<div className="relative space-y-8 before:absolute before:inset-0 before:ml-2.5 before:h-full before:w-0.5 before:-translate-x-px before:bg-accent">
{statuslist?.map((history, idx) =>
<div key={history.id} className="relative flex items-start gap-4 pl-8">
<div className={cn(
"absolute left-0 mt-1 w-5 h-5 rounded-full border-4 border-background z-10",
idx === 0 ? "bg-primary" : "bg-muted-foreground/30"
)} />
<div className="flex-1 space-y-1">
<div className="flex items-center justify-between">
<Badge variant={idx === 0 ? "default" : "outline"} className="text-[10px] h-5">
{history.project_assignment_status.name}
</Badge>
<span className="text-xs text-muted-foreground font-mono">
{history.start_date ? new Date(history.start_date).toLocaleDateString() : 'N/A'} - {history.end_date ? new Date(history.end_date).toLocaleDateString() : 'Present'}
</span>
</div>
<p className="text-xs text-muted-foreground">
Recorded: {new Date(history.end_date!).toLocaleString()}
<div className="space-y-1">
<p className="text-sm font-medium text-foreground">Nobody is assigned yet</p>
<p className="max-w-xs text-sm text-muted-foreground">
Add people from the team directory to start tracking who works on this assignment.
</p>
</div>
</div>
) : (
<>
<ul className="grid gap-3 sm:grid-cols-2">
{visibleTeam.map(member => (
<TeamMember key={member.id} member={member} />
))}
</ul>
{team.length > TEAM_PREVIEW_LIMIT ? (
<Button
variant="ghost"
size="sm"
onClick={() => setShowAllTeam(v => !v)}
className="mt-3 gap-1.5 text-muted-foreground"
aria-expanded={showAllTeam}
>
<ChevronDown className={cn('h-4 w-4 transition-transform duration-300', showAllTeam && 'rotate-180')} />
{showAllTeam ? 'Show fewer' : `Show ${hiddenTeamCount} more`}
</Button>
) : null}
</>
)}
{(!statuslist || statuslist.length === 0) &&
<p className="text-sm text-muted-foreground italic pl-8">No history recorded yet.</p>
}
</Surface>
</Reveal>
</div>
</CardContent>
</Card900>
</div>
</div>
</motion.div>
{action === 'UPDATE_STATUS' ?
<UpdateTimelineStatus assignmentId={assignment.id} onClose={handleClose} />
: null
}
{action === 'MANAGE_EMPLOYEE' ?
<ManageTeam
assignmentId={assignment.id} onClose={handleClose}
startDate={assignment.wo_start_date || assignment.im_start_date} endDate={assignment.wo_end_date || assignment.im_end_date}
{/* Side rail: status history */}
<Reveal delay={0.12} className="lg:sticky lg:top-6">
<Surface title="Status history">
{statusHistory.length === 0 ? (
<p className="text-sm leading-relaxed text-muted-foreground">
No status changes recorded yet. Use Update status to log the first one.
</p>
) : (
<ol className="relative space-y-6 before:absolute before:bottom-2 before:left-[7px] before:top-2 before:w-px before:bg-border">
{statusHistory.map(entry => {
const isCurrent = entry.id === currentEntry?.id;
const days = diffInDays(entry.start_date, entry.end_date);
return (
<li key={entry.id} className="relative pl-7">
<span
aria-hidden
className={cn(
'absolute left-0 top-1 h-[15px] w-[15px] rounded-full border-[3px] border-card',
isCurrent ? 'bg-his' : 'bg-muted-foreground/40'
)}
/>
: null
}
<div className="flex flex-wrap items-center gap-x-2 gap-y-1">
{isCurrent ? (
<BadgeStatus status={entry.project_assignment_status.name} />
) : (
<span className="text-sm font-medium text-foreground/80">
{entry.project_assignment_status.name}
</span>
)}
{isCurrent ? <span className="text-xs text-muted-foreground">Current</span> : null}
</div>
<p className="mt-1.5 font-mono text-xs text-muted-foreground">
{formatAssignmentDate(entry.start_date)} - {entry.end_date ? formatAssignmentDate(entry.end_date) : 'Present'}
</p>
{days !== null ? (
<p className="mt-0.5 text-xs text-muted-foreground/80">{pluralDays(days)}</p>
) : null}
</li>
);
})}
</ol>
)}
</Surface>
</Reveal>
</div>
</div>
{action === 'UPDATE_STATUS' ? (
<UpdateTimelineStatus assignmentId={assignment.id} onClose={handleClose} />
) : null}
{action === 'MANAGE_EMPLOYEE' ? (
<ManageTeam
assignmentId={assignment.id}
onClose={handleClose}
startDate={assignment.wo_start_date || assignment.im_start_date}
endDate={assignment.wo_end_date || assignment.im_end_date}
/>
) : 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 (
<div className="p-3">
<p className="flex items-center gap-1 text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
<Icon className="h-3 w-3" /> {label}
</p>
<p className="mt-1 truncate text-sm md:text-base font-semibold text-foreground">{value}</p>
<motion.div
className={className}
initial={reduce ? false : { opacity: 0, y: 12 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.45, delay, ease: [0.16, 1, 0.3, 1] }}
>
{children}
</motion.div>
);
}
function Surface({
title, meta, action, children,
}: { title: string; meta?: string; action?: ReactNode; children: ReactNode }) {
return (
<section className="rounded-2xl border border-border bg-card p-5 sm:p-6">
<div className="mb-4 flex items-center justify-between gap-3">
<h2 className="flex items-center gap-2 text-base font-semibold tracking-tight text-foreground">
{title}
{meta ? (
<span className="rounded-lg bg-muted px-1.5 py-0.5 font-mono text-xs font-medium text-muted-foreground">{meta}</span>
) : null}
</h2>
{action}
</div>
{children}
</section>
);
}
function Fact({ label, value }: { label: string; value: string }) {
return (
<div className="min-w-0 sm:border-l sm:border-border/70 sm:pl-5 sm:first:border-l-0 sm:first:pl-0">
<dt className="text-xs text-muted-foreground">{label}</dt>
<dd className="mt-1 truncate font-mono text-sm font-medium text-foreground">{value}</dd>
</div>
);
}
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();
}
return (
<Card900 className="p-5 -space-y-2">
<div className="flex items-center gap-1.5 text-[10px] font-bold uppercase tracking-[0.18em] text-muted-foreground">
<Building2 className="h-3 w-3" /> {label}
function PartyRow({
role, party, href,
}: { role: string; party?: { name?: string; photo?: string; description?: string | null; code?: string } | null; href?: string }) {
const body = (
<>
<div className="relative h-12 w-12 shrink-0 overflow-hidden rounded-xl border border-border bg-background">
{party?.photo ? (
<LazyImage src={party.photo} alt={party.name ?? role} className="h-full w-full bg-transparent" imgClassName="object-contain p-1" />
) : (
<div className="flex h-full w-full items-center justify-center text-sm font-semibold text-muted-foreground">
{initials(party?.name) || '-'}
</div>
<div className="flex items-center gap-4">
<div className={`relative h-14 w-14 shrink-0 overflow-hidden rounded-xl border border-border bg-background ring-1 ${accent}`}>
{party?.photo ?
<LazyImage src={party.photo} alt={party?.name} className="h-full w-full object-contain" />
:
<div className="flex h-full w-full items-center justify-center text-base font-bold text-foreground/80">
{initials(party?.name)}
</div>
}
)}
</div>
<div className="min-w-0 flex-1">
<p className="truncate text-base font-semibold text-foreground">{party?.name}</p>
<p className="mt-0.5 flex items-center truncate text-xs text-muted-foreground">{party?.description ?? 'No description available.'}</p>
<p className="text-xs text-muted-foreground">{role}</p>
<p className={cn('truncate font-medium text-foreground', href && 'transition-colors group-hover:text-his')}>
{party?.name ?? 'Not set'}
</p>
{party?.description ? (
<p className="mt-0.5 line-clamp-1 text-xs text-muted-foreground">{party.description}</p>
) : null}
</div>
</div>
</Card900>
</>
);
const className = 'group flex items-center gap-4 py-4 first:pt-0 last:pb-0';
return href ? (
<Link href={href} className={cn(className, 'rounded-xl')}>
{body}
<ExternalLink className="h-4 w-4 shrink-0 text-muted-foreground/60 transition-colors group-hover:text-his" />
</Link>
) : (
<div className={className}>{body}</div>
);
}
function TeamMember({ member }: { member: ProjectAssignmentWorkOrderDetail }) {
const user = member.user;
const name = user?.fullname || user?.name || 'Unnamed member';
return (
<li className="flex min-w-0 items-start gap-3 rounded-xl border border-border/70 bg-muted/20 p-3 transition-colors hover:border-border hover:bg-muted/40">
<LazyImage
src={user?.avatar ? `${process.env.BASE_URL_IMG}/${user.avatar}` : '/assets/no-avatar.jpg'}
alt={name}
className="h-10 w-10 shrink-0 rounded-full border border-border"
/>
<div className="min-w-0 flex-1 space-y-1">
<p className="truncate text-sm font-medium text-foreground">{name}</p>
{user?.position?.name ? (
<p className="truncate text-xs text-muted-foreground">{user.position.name}</p>
) : null}
<div className="flex flex-col gap-0.5 pt-0.5 text-xs text-muted-foreground">
{user?.email ? (
<a
href={`mailto:${user.email}`}
referrerPolicy="no-referrer"
className="inline-flex min-w-0 items-center gap-1.5 transition-colors hover:text-his"
>
<Mail className="h-3 w-3 shrink-0" />
<span className="truncate">{user.email}</span>
</a>
) : null}
{user?.phone_number ? (
<span className="inline-flex items-center gap-1.5">
<Phone className="h-3 w-3 shrink-0" />
<span className="font-mono">{user.phone_number}</span>
</span>
) : null}
</div>
{member.start_date ? (
<p className="pt-1 font-mono text-[11px] text-muted-foreground/80">
{formatAssignmentDate(member.start_date)} - {member.end_date ? formatAssignmentDate(member.end_date) : 'Open'}
</p>
) : null}
</div>
</li>
);
}
@@ -0,0 +1,38 @@
export default function Loading() {
return (
<div
className="mx-auto w-full max-w-7xl flex-1 space-y-6 p-6 pt-6 sm:p-8"
role="status"
aria-label="Loading assignment"
>
<div className="h-5 w-40 animate-pulse rounded-lg bg-muted" />
<div className="rounded-2xl border border-border bg-card p-5 sm:p-7">
<div className="flex items-start gap-5">
<div className="h-24 w-24 shrink-0 animate-pulse rounded-2xl bg-muted" />
<div className="w-full space-y-3">
<div className="h-5 w-48 animate-pulse rounded-lg bg-muted" />
<div className="h-8 w-3/4 animate-pulse rounded-lg bg-muted" />
<div className="h-4 w-full max-w-md animate-pulse rounded-lg bg-muted" />
</div>
</div>
<div className="mt-7 grid grid-cols-2 gap-6 border-t border-border/70 pt-6 sm:grid-cols-4">
{Array.from({ length: 4 }).map((_, i) => (
<div key={i} className="space-y-2">
<div className="h-3 w-12 animate-pulse rounded bg-muted" />
<div className="h-4 w-24 animate-pulse rounded bg-muted" />
</div>
))}
</div>
</div>
<div className="grid items-start gap-6 lg:grid-cols-[minmax(0,1fr)_360px]">
<div className="space-y-6">
<div className="h-44 animate-pulse rounded-2xl border border-border bg-card" />
<div className="h-64 animate-pulse rounded-2xl border border-border bg-card" />
</div>
<div className="h-80 animate-pulse rounded-2xl border border-border bg-card" />
</div>
</div>
);
}
+405
View File
@@ -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
+3 -1
View File
@@ -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",
+1 -1
View File
@@ -30,5 +30,5 @@
".next/dev/types/**/*.ts",
"**/*.mts"
],
"exclude": ["node_modules"]
"exclude": ["node_modules", "**/*.old.tsx", "**/*.old.ts"]
}