Compare commits
7 Commits
e6a032e8e0
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 88353d5d06 | |||
| 0e7bb07772 | |||
| 3268a6284e | |||
| 73406d0b86 | |||
| 4c449a572a | |||
| 9022f983a2 | |||
| 6b8f9dec5d |
@@ -12,6 +12,9 @@ KYC_ENCRYPTION_KEY=
|
||||
KYC_NIK_PEPPER=
|
||||
# Absolute path for private KYC uploads (default: <cwd>/uploads/private)
|
||||
KYC_UPLOAD_DIR=
|
||||
# Absolute path for public trip image uploads (default: <cwd>/uploads/trips)
|
||||
# Pakai volume persisten — file di sini harus selamat saat redeploy/restart.
|
||||
TRIP_UPLOAD_DIR=
|
||||
|
||||
GOOGLE_CLIENT_ID="xxxxxxxx"
|
||||
GOOGLE_CLIENT_SECRET="xxxxxxxx"
|
||||
|
||||
+2
-1
@@ -36,7 +36,8 @@ yarn-error.log*
|
||||
.env.development
|
||||
.env.local
|
||||
|
||||
# private uploads (KYC: KTP / liveness). Never serve directly.
|
||||
# runtime uploads — KYC (encrypted, private) & trip images (public, served via
|
||||
# /api/trip-images). User data, not source: keep out of git, back up separately.
|
||||
/uploads/
|
||||
|
||||
# vercel
|
||||
|
||||
@@ -94,7 +94,7 @@ Alur ini menggambarkan satu peserta dari pertama kali mendaftar sampai pembayara
|
||||
### 5. Ringkasan peran data
|
||||
|
||||
| Konsep | Penyimpanan |
|
||||
|--------|-------------|
|
||||
| ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| Trip | `Trip`: judul, gunung, lokasi, tanggal, kuota, harga, status trip (`OPEN` / `FULL` / …), meeting point, itinerary, termasuk/tidak termasuk, relasi ke organizer |
|
||||
| Peserta | `TripParticipant` unik per `(tripId, userId)`: status **`PENDING`** / **`CONFIRMED`** / **`CANCELLED`**, serta **`markedPaidAt`** & **`paymentConfirmedAt`** untuk alur bayar manual |
|
||||
| Organizer (kepercayaan) | `OrganizerVerification` (1-1 ke `User`) berisi KTP, foto liveness (memegang kertas "SETRIP"), rekening, dan status (`PENDING` / `APPROVED` / `REJECTED`); badge **Verified Organizer** muncul ketika `status === "APPROVED"` (helper `lib/trust.ts → isVerifiedOrganizer`). Agregat rating & jumlah trip dihitung dari ulasan & trip. |
|
||||
@@ -128,3 +128,28 @@ Buka [http://localhost:3000](http://localhost:3000).
|
||||
|
||||
- [Next.js Documentation](https://nextjs.org/docs)
|
||||
- [Prisma Documentation](https://www.prisma.io/docs)
|
||||
|
||||
# 1. Install SEMUA dep (termasuk dev) — deterministik dari lockfile.
|
||||
|
||||
# --include=dev memaksa dev terpasang walau NODE_ENV=production ter-export.
|
||||
|
||||
npm ci --include=dev
|
||||
|
||||
# 2. Prisma: generate client + apply migrasi
|
||||
|
||||
npx prisma generate
|
||||
npx prisma migrate deploy
|
||||
|
||||
# 3. Build (butuh devDependencies)
|
||||
|
||||
npm run build
|
||||
|
||||
# 4. (Opsional) ramping-kan node_modules — buang dev SETELAH build selesai
|
||||
|
||||
npm prune --omit=dev
|
||||
|
||||
# 5. Jalankan
|
||||
|
||||
pm2 start ecosystem.config.js --env production
|
||||
|
||||
# atau restart: pm2 restart setrip --update-env
|
||||
|
||||
@@ -2,7 +2,7 @@ import { ImageResponse } from "next/og";
|
||||
import { tripService } from "@/server/services/trip.service";
|
||||
import { formatRupiah } from "@/lib/utils";
|
||||
import { formatTripCalendarDateRangeLong } from "@/lib/trip-dates";
|
||||
import { siteConfig } from "@/lib/site";
|
||||
import { siteConfig, siteUrl } from "@/lib/site";
|
||||
|
||||
export const alt = `${siteConfig.name} — Open Trip & Aktivitas Bareng`;
|
||||
export const size = { width: 1200, height: 630 };
|
||||
@@ -43,7 +43,15 @@ export default async function TripOgImage({
|
||||
);
|
||||
}
|
||||
|
||||
const cover = trip.images[0]?.url;
|
||||
// Satori (ImageResponse) mem-fetch gambar server-side dan butuh URL absolut.
|
||||
// Foto trip baru disimpan sebagai path relatif `/api/trip-images/...` —
|
||||
// prefix dengan origin. Foto lama (URL eksternal absolut) dipakai apa adanya.
|
||||
const coverRaw = trip.images[0]?.url;
|
||||
const cover = coverRaw
|
||||
? coverRaw.startsWith("http")
|
||||
? coverRaw
|
||||
: `${siteUrl}${coverRaw}`
|
||||
: undefined;
|
||||
const dateLabel = formatTripCalendarDateRangeLong(trip.date, trip.endDate);
|
||||
const price = formatRupiah(trip.price);
|
||||
|
||||
|
||||
@@ -153,7 +153,7 @@ export default async function TripsPage({ searchParams }: TripsPageProps) {
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{trips.map((trip) => (
|
||||
{trips.map((trip, index) => (
|
||||
<TripCard
|
||||
key={trip.id}
|
||||
id={trip.id}
|
||||
@@ -170,6 +170,9 @@ export default async function TripsPage({ searchParams }: TripsPageProps) {
|
||||
organizerName={trip.organizer.name}
|
||||
status={trip.status}
|
||||
coverImage={trip.images[0]?.url}
|
||||
// Baris pertama (3 kartu) di atas fold — muat segera supaya
|
||||
// tidak jadi LCP yang lambat.
|
||||
priority={index < 3}
|
||||
isVerifiedOrganizer={
|
||||
trip.organizer.organizerVerification?.status === "APPROVED"
|
||||
}
|
||||
|
||||
@@ -62,7 +62,11 @@ async function getJobSummary(jobName: string): Promise<JobSummary> {
|
||||
}
|
||||
|
||||
// Daftar cron yang dipantau. Tambah entry baru saat menambah cron route handler.
|
||||
const TRACKED_JOBS = ["auto-complete-trips", "process-email-jobs"] as const;
|
||||
const TRACKED_JOBS = [
|
||||
"auto-complete-trips",
|
||||
"process-email-jobs",
|
||||
"cleanup-trip-images",
|
||||
] as const;
|
||||
|
||||
function healthOf(summary: JobSummary): "ok" | "stale" | "failed" {
|
||||
if (summary.lastRun?.status === "FAILED") return "failed";
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { runCron } from "@/lib/cron-runner";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import {
|
||||
deleteTripImage,
|
||||
listTripImageNames,
|
||||
tripImageMtime,
|
||||
TRIP_IMAGE_URL_PREFIX,
|
||||
} from "@/lib/trip-image-storage";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** File yang lebih tua dari ini & tak direferensikan DB dianggap yatim. */
|
||||
const ORPHAN_AGE_MS = 24 * 60 * 60 * 1000;
|
||||
|
||||
/**
|
||||
* Cron — hapus file gambar trip yatim.
|
||||
*
|
||||
* Form create-trip multi-step mengunggah foto SEBELUM trip tersimpan; kalau
|
||||
* user menutup form di tengah jalan, file menggantung di disk tanpa pernah
|
||||
* jadi `TripImage`. Sweep ini menghapus file >24 jam yang tidak direferensikan
|
||||
* `TripImage` mana pun. Idempotent — aman dijalankan berulang.
|
||||
*
|
||||
* Trigger: lihat docs/CRON_SETUP.md. Header wajib `Authorization: Bearer ${CRON_SECRET}`.
|
||||
*/
|
||||
export async function GET(req: NextRequest) {
|
||||
const secret = process.env.CRON_SECRET;
|
||||
if (!secret) {
|
||||
console.error("[cron/cleanup-trip-images] CRON_SECRET tidak di-set");
|
||||
return NextResponse.json(
|
||||
{ error: "Server misconfigured" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
if (req.headers.get("authorization") !== `Bearer ${secret}`) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
const outcome = await runCron("cleanup-trip-images", async () => {
|
||||
const names = await listTripImageNames();
|
||||
if (names.length === 0) return { scanned: 0, deleted: 0 };
|
||||
|
||||
const referenced = await prisma.tripImage.findMany({
|
||||
where: { url: { startsWith: TRIP_IMAGE_URL_PREFIX } },
|
||||
select: { url: true },
|
||||
});
|
||||
const referencedNames = new Set(
|
||||
referenced.map((r) => r.url.slice(TRIP_IMAGE_URL_PREFIX.length))
|
||||
);
|
||||
|
||||
const now = Date.now();
|
||||
let deleted = 0;
|
||||
for (const name of names) {
|
||||
if (referencedNames.has(name)) continue;
|
||||
const mtime = await tripImageMtime(name);
|
||||
// File baru di-upload tapi trip belum tersimpan → beri tenggang 24 jam.
|
||||
if (!mtime || now - mtime.getTime() < ORPHAN_AGE_MS) continue;
|
||||
await deleteTripImage(name);
|
||||
deleted++;
|
||||
}
|
||||
return { scanned: names.length, deleted };
|
||||
});
|
||||
|
||||
if (!outcome.ok) {
|
||||
console.error("[cron/cleanup-trip-images] gagal", outcome.error);
|
||||
return NextResponse.json(
|
||||
{ error: "Gagal menjalankan cleanup" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
console.log("[cron/cleanup-trip-images] selesai", outcome.payload);
|
||||
return NextResponse.json({ ok: true, ...outcome.payload });
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { isValidTripImageName, readTripImage } from "@/lib/trip-image-storage";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
|
||||
interface RouteCtx {
|
||||
params: Promise<{ name: string }>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sajikan gambar trip dari disk lokal. Publik — gambar trip memang tampil ke
|
||||
* semua pengunjung. Di-cache `immutable` selama setahun: nama file
|
||||
* content-addressed (hex acak), jadi konten untuk satu nama tidak pernah
|
||||
* berubah. Beban render = baca file kecil dari disk, tanpa fetch eksternal.
|
||||
*/
|
||||
export async function GET(_req: NextRequest, ctx: RouteCtx) {
|
||||
const { name } = await ctx.params;
|
||||
if (!isValidTripImageName(name)) {
|
||||
return NextResponse.json({ error: "Tidak ditemukan" }, { status: 404 });
|
||||
}
|
||||
|
||||
let data: Buffer;
|
||||
try {
|
||||
data = await readTripImage(name);
|
||||
} catch {
|
||||
return NextResponse.json({ error: "Tidak ditemukan" }, { status: 404 });
|
||||
}
|
||||
|
||||
return new NextResponse(new Uint8Array(data), {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Content-Type": "image/webp",
|
||||
"Content-Length": String(data.length),
|
||||
"Cache-Control": "public, max-age=31536000, immutable",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { getServerSession } from "next-auth";
|
||||
import { authOptions } from "@/lib/auth";
|
||||
import { requireActiveUser } from "@/lib/auth-guards";
|
||||
import {
|
||||
ALLOWED_TRIP_IMAGE_MIME,
|
||||
MAX_TRIP_IMAGE_UPLOAD_BYTES,
|
||||
processAndSaveTripImage,
|
||||
} from "@/lib/trip-image-storage";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/**
|
||||
* Upload satu foto trip. Dipanggil dari form create-trip saat user memilih
|
||||
* file — gambar langsung dikompres & disimpan, route mengembalikan URL publik
|
||||
* yang nanti ikut disubmit bersama data trip.
|
||||
*
|
||||
* File yatim (di-upload tapi trip batal dibuat) dibersihkan cron
|
||||
* `/api/cron/cleanup-trip-images`.
|
||||
*/
|
||||
export async function POST(req: NextRequest) {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session?.user) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
try {
|
||||
await requireActiveUser(session.user.id);
|
||||
} catch (err) {
|
||||
return NextResponse.json(
|
||||
{ error: (err as Error).message },
|
||||
{ status: 403 }
|
||||
);
|
||||
}
|
||||
|
||||
let form: FormData;
|
||||
try {
|
||||
form = await req.formData();
|
||||
} catch {
|
||||
return NextResponse.json(
|
||||
{ error: "Body bukan multipart/form-data" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const file = form.get("file");
|
||||
if (!(file instanceof File)) {
|
||||
return NextResponse.json({ error: "File wajib diisi" }, { status: 400 });
|
||||
}
|
||||
if (!ALLOWED_TRIP_IMAGE_MIME.has(file.type)) {
|
||||
return NextResponse.json(
|
||||
{ error: "Hanya menerima JPG, PNG, atau WebP" },
|
||||
{ status: 415 }
|
||||
);
|
||||
}
|
||||
if (file.size > MAX_TRIP_IMAGE_UPLOAD_BYTES) {
|
||||
return NextResponse.json(
|
||||
{ error: "Ukuran file maksimal 12MB" },
|
||||
{ status: 413 }
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const buf = Buffer.from(await file.arrayBuffer());
|
||||
const saved = await processAndSaveTripImage(buf);
|
||||
return NextResponse.json({ url: saved.url, size: saved.size });
|
||||
} catch (err) {
|
||||
return NextResponse.json(
|
||||
{ error: (err as Error).message || "Gagal memproses gambar" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ Aplikasi punya beberapa endpoint cron yang harus di-trigger periodik dari luar.
|
||||
|---|---|---|---|---|
|
||||
| 1 | `GET /api/cron/auto-complete-trips` | `0 18 * * *` | Daily 01:00 WIB (18:00 UTC) | Flip trip yang sudah lewat tanggal selesai dari `OPEN`/`FULL` ke `COMPLETED`. Setelah itu, release payout HELD yang sudah lewat `heldUntil`. |
|
||||
| 2 | `GET /api/cron/process-email-jobs` | `*/5 * * * *` | Setiap 5 menit | Drain retry queue email — pick `EmailJob` status `PENDING`/`FAILED` (attempts<5), retry via Resend dengan exponential backoff. |
|
||||
| 3 | `GET /api/cron/cleanup-trip-images` | `30 18 * * *` | Daily 01:30 WIB (18:30 UTC) | Hapus file gambar trip yatim — foto yang di-upload di form create-trip tapi trip-nya batal dibuat. Hanya file >24 jam yang tak direferensikan `TripImage`. |
|
||||
|
||||
Semua cron pakai pola yang sama: header `Authorization: Bearer ${CRON_SECRET}`, idempotent, auto-log ke `CronRun`. Tambah cron baru = tambah baris di tabel ini + tabel `TRACKED_JOBS` di [app/admin/system/page.tsx](../app/admin/system/page.tsx).
|
||||
|
||||
@@ -67,6 +68,9 @@ Tambah baris berikut (ganti `https://your-domain.com` dan `<CRON_SECRET>` sesuai
|
||||
|
||||
# 2. Drain email retry queue (setiap 5 menit)
|
||||
*/5 * * * * curl -fsS -H "Authorization: Bearer <CRON_SECRET>" https://your-domain.com/api/cron/process-email-jobs >> /var/log/setrip-cron.log 2>&1
|
||||
|
||||
# 3. Bersihkan gambar trip yatim (daily 01:30 WIB)
|
||||
30 18 * * * curl -fsS -H "Authorization: Bearer <CRON_SECRET>" https://your-domain.com/api/cron/cleanup-trip-images >> /var/log/setrip-cron.log 2>&1
|
||||
```
|
||||
|
||||
Verifikasi crontab tersimpan:
|
||||
@@ -120,6 +124,7 @@ curl -fsS -H "Authorization: Bearer $CRON_SECRET" https://your-domain.com/api/cr
|
||||
|---|---|---|
|
||||
| `auto-complete-trips` | `{"ok":true,"completed":0,"ids":[],"payoutsReleased":[]}` | `{"ok":true,"completed":2,"ids":["clx...","cly..."],"payoutsReleased":["..."]}` |
|
||||
| `process-email-jobs` | `{"ok":true,"picked":0,"succeeded":0,"failed":0}` | `{"ok":true,"picked":5,"succeeded":5,"failed":0}` |
|
||||
| `cleanup-trip-images` | `{"ok":true,"scanned":0,"deleted":0}` | `{"ok":true,"scanned":12,"deleted":3}` |
|
||||
|
||||
**Error response:**
|
||||
- **401** — `CRON_SECRET` di env tidak match dengan header. Cek `pm2 env <id>`.
|
||||
|
||||
@@ -3,7 +3,10 @@
|
||||
import { useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Check } from "lucide-react";
|
||||
import { retryEmailJobAction, resendEmailAction } from "@/features/email/actions";
|
||||
import {
|
||||
retryEmailJobAction,
|
||||
resendEmailAction,
|
||||
} from "@/features/email/actions";
|
||||
|
||||
const BTN_CLS =
|
||||
"rounded-lg border border-primary-200 bg-primary-50 px-2.5 py-1 text-[11px] font-semibold text-primary-700 transition-colors hover:bg-primary-100 disabled:cursor-not-allowed disabled:opacity-50";
|
||||
@@ -37,7 +40,7 @@ export function RetryEmailButton({ jobId }: { jobId: string }) {
|
||||
{loading ? "Mengirim…" : "Kirim ulang"}
|
||||
</button>
|
||||
{error && (
|
||||
<p className="mt-1 max-w-[200px] text-[10px] text-red-600">{error}</p>
|
||||
<p className="mt-1 max-w-50 text-[10px] text-red-600">{error}</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
@@ -100,7 +103,7 @@ export function ResendEmailButton({
|
||||
)}
|
||||
</button>
|
||||
{error && (
|
||||
<p className="mt-1 max-w-[200px] text-[10px] text-red-600">{error}</p>
|
||||
<p className="mt-1 max-w-50 text-[10px] text-red-600">{error}</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -28,7 +28,7 @@ export function RefundPolicySection() {
|
||||
{tiers.map((t) => (
|
||||
<li key={t.minDaysBefore} className="flex items-baseline gap-2">
|
||||
<span
|
||||
className={`inline-flex min-w-[3rem] justify-center rounded-full px-2 py-0.5 text-[10px] font-bold ${
|
||||
className={`inline-flex min-w-12 justify-center rounded-full px-2 py-0.5 text-[10px] font-bold ${
|
||||
t.refundPercentage >= 80
|
||||
? "bg-primary-100 text-primary-700"
|
||||
: t.refundPercentage >= 50
|
||||
|
||||
@@ -12,7 +12,7 @@ import {
|
||||
} from "lucide-react";
|
||||
import { DateRangeField, TimeField } from "@/components/shared/date-picker";
|
||||
import { createTripAction } from "@/features/trip/actions";
|
||||
import { ImageUrlInput } from "@/features/trip/components/image-url-input";
|
||||
import { TripImageUpload } from "@/features/trip/components/trip-image-upload";
|
||||
import { formatLocalCalendarYmd } from "@/lib/trip-dates";
|
||||
import { ACTIVITY_CATEGORIES, categoryMeta } from "@/lib/activity-category";
|
||||
import { VIBES, vibeMeta } from "@/lib/vibe";
|
||||
@@ -61,7 +61,7 @@ const INITIAL_STATE: FormState = {
|
||||
itineraryDays: [],
|
||||
whatsIncluded: "",
|
||||
whatsExcluded: "",
|
||||
imageUrls: [""],
|
||||
imageUrls: [],
|
||||
maxParticipants: "",
|
||||
priceDisplay: "",
|
||||
};
|
||||
@@ -152,18 +152,11 @@ export function CreateTripForm({ isVerifiedOrganizer }: CreateTripFormProps) {
|
||||
return null;
|
||||
}
|
||||
if (target === 3) {
|
||||
const hasInvalidUrl = state.imageUrls
|
||||
.map((u) => u.trim())
|
||||
.filter(Boolean)
|
||||
.some((u) => {
|
||||
try {
|
||||
const parsed = new URL(u);
|
||||
return parsed.protocol !== "http:" && parsed.protocol !== "https:";
|
||||
} catch {
|
||||
return true;
|
||||
// Foto divalidasi saat upload (route + komponen). Di sini cukup cek
|
||||
// batas jumlah supaya tidak melampaui kapasitas.
|
||||
if (state.imageUrls.length > LIMITS.MAX_IMAGE_URLS) {
|
||||
return `Maksimal ${LIMITS.MAX_IMAGE_URLS} foto`;
|
||||
}
|
||||
});
|
||||
if (hasInvalidUrl) return "Ada URL foto yang tidak valid (harus http/https)";
|
||||
|
||||
for (let d = 0; d < state.itineraryDays.length; d++) {
|
||||
const dayItems = state.itineraryDays[d];
|
||||
@@ -338,6 +331,7 @@ export function CreateTripForm({ isVerifiedOrganizer }: CreateTripFormProps) {
|
||||
whatsExcluded={state.whatsExcluded}
|
||||
imageUrls={state.imageUrls}
|
||||
onChange={update}
|
||||
onError={setStepError}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -698,6 +692,7 @@ function StepDetail({
|
||||
whatsExcluded,
|
||||
imageUrls,
|
||||
onChange,
|
||||
onError,
|
||||
}: {
|
||||
meetingPoint: string;
|
||||
itineraryDays: ItineraryDays;
|
||||
@@ -705,6 +700,7 @@ function StepDetail({
|
||||
whatsExcluded: string;
|
||||
imageUrls: string[];
|
||||
onChange: <K extends keyof FormState>(key: K, value: FormState[K]) => void;
|
||||
onError: (msg: string) => void;
|
||||
}) {
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
@@ -777,9 +773,10 @@ function StepDetail({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ImageUrlInput
|
||||
<TripImageUpload
|
||||
value={imageUrls}
|
||||
onChange={(urls) => onChange("imageUrls", urls)}
|
||||
onError={onError}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
"use client";
|
||||
|
||||
import Image from "next/image";
|
||||
import { useState } from "react";
|
||||
import { Mountain } from "lucide-react";
|
||||
import { useEffect, useState } from "react";
|
||||
import { Mountain, Maximize2, X, ChevronLeft, ChevronRight } from "lucide-react";
|
||||
|
||||
interface TripImage {
|
||||
id: string;
|
||||
@@ -12,6 +12,38 @@ interface TripImage {
|
||||
|
||||
export function ImageGallery({ images }: { images: TripImage[] }) {
|
||||
const [activeIndex, setActiveIndex] = useState(0);
|
||||
const [lightboxOpen, setLightboxOpen] = useState(false);
|
||||
const hasMultiple = images.length > 1;
|
||||
|
||||
function showPrev() {
|
||||
setActiveIndex((i) => (i - 1 + images.length) % images.length);
|
||||
}
|
||||
function showNext() {
|
||||
setActiveIndex((i) => (i + 1) % images.length);
|
||||
}
|
||||
|
||||
// Saat lightbox terbuka: kunci scroll body + dukung keyboard (Esc tutup,
|
||||
// panah kiri/kanan untuk ganti foto).
|
||||
useEffect(() => {
|
||||
if (!lightboxOpen) return;
|
||||
function onKey(e: KeyboardEvent) {
|
||||
// Logika prev/next di-inline (bukan panggil showPrev/showNext) supaya
|
||||
// effect tidak bergantung pada fungsi yang dibuat ulang tiap render.
|
||||
if (e.key === "Escape") setLightboxOpen(false);
|
||||
else if (e.key === "ArrowLeft") {
|
||||
setActiveIndex((i) => (i - 1 + images.length) % images.length);
|
||||
} else if (e.key === "ArrowRight") {
|
||||
setActiveIndex((i) => (i + 1) % images.length);
|
||||
}
|
||||
}
|
||||
document.addEventListener("keydown", onKey);
|
||||
const prevOverflow = document.body.style.overflow;
|
||||
document.body.style.overflow = "hidden";
|
||||
return () => {
|
||||
document.removeEventListener("keydown", onKey);
|
||||
document.body.style.overflow = prevOverflow;
|
||||
};
|
||||
}, [lightboxOpen, images.length]);
|
||||
|
||||
if (images.length === 0) {
|
||||
return (
|
||||
@@ -30,18 +62,25 @@ export function ImageGallery({ images }: { images: TripImage[] }) {
|
||||
|
||||
return (
|
||||
<div>
|
||||
{/* Main Image */}
|
||||
<div className="relative h-44 bg-neutral-900 sm:h-56 lg:h-72">
|
||||
{/* Main Image — klik untuk lihat ukuran penuh */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setLightboxOpen(true)}
|
||||
aria-label="Lihat foto ukuran penuh"
|
||||
className="group relative block h-44 w-full cursor-zoom-in bg-neutral-900 sm:h-56 lg:h-72"
|
||||
>
|
||||
<Image
|
||||
src={activeImage.url}
|
||||
alt={activeImage.caption || "Foto trip"}
|
||||
fill
|
||||
className="object-cover"
|
||||
// `object-contain` — tampilkan gambar utuh tanpa terpotong; rasio
|
||||
// foto bebas, sisi yang tak terisi jadi bar gelap (bg-neutral-900).
|
||||
className="object-contain"
|
||||
sizes="(max-width: 768px) 100vw, 768px"
|
||||
priority
|
||||
/>
|
||||
{activeImage.caption && (
|
||||
<div className="absolute bottom-0 left-0 right-0 bg-linear-to-t from-black/60 to-transparent px-3 pb-2.5 pt-6 sm:px-4 sm:pb-3 sm:pt-8">
|
||||
<div className="absolute bottom-0 left-0 right-0 bg-linear-to-t from-black/60 to-transparent px-3 pb-2.5 pt-6 text-left sm:px-4 sm:pb-3 sm:pt-8">
|
||||
<p className="text-xs font-medium text-white sm:text-sm">
|
||||
{activeImage.caption}
|
||||
</p>
|
||||
@@ -51,14 +90,20 @@ export function ImageGallery({ images }: { images: TripImage[] }) {
|
||||
<div className="absolute right-2 top-2 rounded-full bg-black/50 px-2 py-0.5 text-[10px] font-medium text-white backdrop-blur-sm sm:right-3 sm:top-3 sm:px-2.5 sm:py-1 sm:text-xs">
|
||||
{activeIndex + 1} / {images.length}
|
||||
</div>
|
||||
</div>
|
||||
{/* Petunjuk perbesar */}
|
||||
<span className="absolute left-2 top-2 inline-flex items-center gap-1 rounded-full bg-black/50 px-2 py-0.5 text-[10px] font-medium text-white backdrop-blur-sm transition-colors group-hover:bg-black/70 sm:left-3 sm:top-3 sm:px-2.5 sm:py-1 sm:text-xs">
|
||||
<Maximize2 size={11} strokeWidth={2} aria-hidden />
|
||||
Lihat penuh
|
||||
</span>
|
||||
</button>
|
||||
|
||||
{/* Thumbnails */}
|
||||
{images.length > 1 && (
|
||||
{hasMultiple && (
|
||||
<div className="flex gap-1 overflow-x-auto bg-neutral-100 p-1.5 sm:gap-1.5 sm:p-2">
|
||||
{images.map((img, i) => (
|
||||
<button
|
||||
key={img.id}
|
||||
type="button"
|
||||
onClick={() => setActiveIndex(i)}
|
||||
className={`relative h-11 w-16 shrink-0 overflow-hidden rounded-md transition-all sm:h-14 sm:w-20 sm:rounded-lg ${
|
||||
i === activeIndex
|
||||
@@ -77,6 +122,111 @@ export function ImageGallery({ images }: { images: TripImage[] }) {
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Lightbox — penampil foto ukuran penuh */}
|
||||
{lightboxOpen && (
|
||||
<div
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label="Penampil foto trip"
|
||||
className="fixed inset-0 z-50 flex flex-col bg-black/95"
|
||||
>
|
||||
{/* Top bar */}
|
||||
<div className="flex items-center justify-between px-4 py-3 text-white">
|
||||
<span className="text-sm font-medium tabular-nums">
|
||||
{activeIndex + 1} / {images.length}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setLightboxOpen(false)}
|
||||
aria-label="Tutup"
|
||||
className="flex h-9 w-9 items-center justify-center rounded-full bg-white/10 transition-colors hover:bg-white/20"
|
||||
>
|
||||
<X size={20} strokeWidth={2} aria-hidden />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Area gambar — klik latar untuk menutup */}
|
||||
<div
|
||||
className="relative flex-1"
|
||||
onClick={() => setLightboxOpen(false)}
|
||||
>
|
||||
<div
|
||||
className="relative h-full w-full"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<Image
|
||||
src={activeImage.url}
|
||||
alt={activeImage.caption || "Foto trip"}
|
||||
fill
|
||||
className="object-contain"
|
||||
sizes="100vw"
|
||||
quality={90}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{hasMultiple && (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
showPrev();
|
||||
}}
|
||||
aria-label="Foto sebelumnya"
|
||||
className="absolute left-2 top-1/2 flex h-11 w-11 -translate-y-1/2 items-center justify-center rounded-full bg-white/10 text-white transition-colors hover:bg-white/25 sm:left-4"
|
||||
>
|
||||
<ChevronLeft size={24} strokeWidth={2} aria-hidden />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
showNext();
|
||||
}}
|
||||
aria-label="Foto berikutnya"
|
||||
className="absolute right-2 top-1/2 flex h-11 w-11 -translate-y-1/2 items-center justify-center rounded-full bg-white/10 text-white transition-colors hover:bg-white/25 sm:right-4"
|
||||
>
|
||||
<ChevronRight size={24} strokeWidth={2} aria-hidden />
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{activeImage.caption && (
|
||||
<p className="px-4 py-3 text-center text-sm text-white/80">
|
||||
{activeImage.caption}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{/* Thumbnail strip di dalam lightbox */}
|
||||
{hasMultiple && (
|
||||
<div className="flex justify-center gap-1.5 overflow-x-auto px-4 pb-4">
|
||||
{images.map((img, i) => (
|
||||
<button
|
||||
key={img.id}
|
||||
type="button"
|
||||
onClick={() => setActiveIndex(i)}
|
||||
aria-label={`Lihat foto ${i + 1}`}
|
||||
className={`relative h-12 w-16 shrink-0 overflow-hidden rounded-md transition-all ${
|
||||
i === activeIndex
|
||||
? "ring-2 ring-primary-400 ring-offset-1 ring-offset-black"
|
||||
: "opacity-50 hover:opacity-100"
|
||||
}`}
|
||||
>
|
||||
<Image
|
||||
src={img.url}
|
||||
alt=""
|
||||
fill
|
||||
className="object-cover"
|
||||
sizes="64px"
|
||||
/>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,84 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { Plus, X } from "lucide-react";
|
||||
import { LIMITS } from "@/lib/limits";
|
||||
|
||||
interface ImageUrlInputProps {
|
||||
value: string[];
|
||||
onChange: (urls: string[]) => void;
|
||||
}
|
||||
|
||||
export function ImageUrlInput({ value, onChange }: ImageUrlInputProps) {
|
||||
const urls = value.length > 0 ? value : [""];
|
||||
const max = LIMITS.MAX_IMAGE_URLS;
|
||||
|
||||
function addField() {
|
||||
if (urls.length < max) {
|
||||
onChange([...urls, ""]);
|
||||
}
|
||||
}
|
||||
|
||||
function removeField(index: number) {
|
||||
const next = urls.filter((_, i) => i !== index);
|
||||
onChange(next.length > 0 ? next : [""]);
|
||||
}
|
||||
|
||||
function updateField(index: number, next: string) {
|
||||
const updated = [...urls];
|
||||
updated[index] = next;
|
||||
onChange(updated);
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<label className="mb-2 flex items-center justify-between">
|
||||
<span className="text-sm font-semibold text-neutral-700">
|
||||
Foto Trip (URL)
|
||||
</span>
|
||||
<span className="text-xs text-neutral-400">
|
||||
{urls.length}/{max}
|
||||
</span>
|
||||
</label>
|
||||
<div className="space-y-2">
|
||||
{urls.map((url, i) => (
|
||||
<div key={i} className="flex gap-2">
|
||||
<input
|
||||
type="url"
|
||||
value={url}
|
||||
onChange={(e) => updateField(i, e.target.value)}
|
||||
className="flex-1 rounded-xl border border-neutral-200 bg-neutral-50 px-4 py-2.5 text-sm text-neutral-800 placeholder:text-neutral-400 focus:bg-white"
|
||||
placeholder={
|
||||
i === 0
|
||||
? "URL foto utama (cover)"
|
||||
: `URL foto ${i + 1} (opsional)`
|
||||
}
|
||||
/>
|
||||
{urls.length > 1 && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => removeField(i)}
|
||||
aria-label={`Hapus foto ${i + 1}`}
|
||||
className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl border border-neutral-200 text-neutral-400 hover:bg-red-50 hover:text-red-500"
|
||||
>
|
||||
<X size={16} strokeWidth={2} aria-hidden />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{urls.length < max && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={addField}
|
||||
className="mt-2 flex items-center gap-1 rounded-lg px-2 py-1 text-sm font-medium text-secondary-600 hover:bg-secondary-50"
|
||||
>
|
||||
<Plus size={15} strokeWidth={2} aria-hidden />
|
||||
Tambah foto
|
||||
</button>
|
||||
)}
|
||||
<p className="mt-1.5 text-xs text-neutral-400">
|
||||
Upload foto ke hosting (imgur, imgbb, dll) lalu paste URL-nya di sini.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -56,7 +56,7 @@ export function OrganizerTrustPanel({
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-1 flex-wrap gap-3 border-t border-neutral-100 pt-3 sm:border-t-0 sm:border-l sm:pl-4 sm:pt-0">
|
||||
<div className="min-w-[100px] rounded-lg bg-white/80 px-3 py-2 shadow-sm ring-1 ring-neutral-100">
|
||||
<div className="min-w-25 rounded-lg bg-white/80 px-3 py-2 shadow-sm ring-1 ring-neutral-100">
|
||||
<p className="text-[10px] font-medium text-neutral-500 sm:text-xs">
|
||||
Trip selesai
|
||||
</p>
|
||||
@@ -69,7 +69,7 @@ export function OrganizerTrustPanel({
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="min-w-[100px] rounded-lg bg-white/80 px-3 py-2 shadow-sm ring-1 ring-neutral-100">
|
||||
<div className="min-w-25 rounded-lg bg-white/80 px-3 py-2 shadow-sm ring-1 ring-neutral-100">
|
||||
<p className="text-[10px] font-medium text-neutral-500 sm:text-xs">
|
||||
Peserta dilayani
|
||||
</p>
|
||||
@@ -77,7 +77,7 @@ export function OrganizerTrustPanel({
|
||||
{trust.totalParticipantsServed}
|
||||
</p>
|
||||
</div>
|
||||
<div className="min-w-[100px] rounded-lg bg-white/80 px-3 py-2 shadow-sm ring-1 ring-neutral-100">
|
||||
<div className="min-w-25 rounded-lg bg-white/80 px-3 py-2 shadow-sm ring-1 ring-neutral-100">
|
||||
<p className="text-[10px] font-medium text-neutral-500 sm:text-xs">
|
||||
Rating organizer
|
||||
</p>
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
"use client";
|
||||
|
||||
import { useRef, useState } from "react";
|
||||
import Image from "next/image";
|
||||
import { ImagePlus, X, Loader2 } from "lucide-react";
|
||||
import { LIMITS } from "@/lib/limits";
|
||||
|
||||
interface TripImageUploadProps {
|
||||
/** URL gambar yang sudah terunggah (path `/api/trip-images/...`). */
|
||||
value: string[];
|
||||
onChange: (urls: string[]) => void;
|
||||
/** Lapor error ke form (mis. file terlalu besar / gagal upload). */
|
||||
onError?: (msg: string) => void;
|
||||
}
|
||||
|
||||
const ACCEPT_MIME = "image/jpeg,image/png,image/webp";
|
||||
/** Sinkron dengan MAX_TRIP_IMAGE_UPLOAD_BYTES di lib/trip-image-storage.ts. */
|
||||
const MAX_BYTES = 12 * 1024 * 1024;
|
||||
|
||||
/**
|
||||
* Pengganti input URL foto: user memilih file dari perangkatnya, tiap file
|
||||
* langsung di-upload & dikompres server-side. Form hanya menyimpan URL hasil.
|
||||
*/
|
||||
export function TripImageUpload({
|
||||
value,
|
||||
onChange,
|
||||
onError,
|
||||
}: TripImageUploadProps) {
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const [uploadingCount, setUploadingCount] = useState(0);
|
||||
const max = LIMITS.MAX_IMAGE_URLS;
|
||||
const usedSlots = value.length + uploadingCount;
|
||||
const remaining = max - usedSlots;
|
||||
|
||||
async function uploadOne(file: File): Promise<string | null> {
|
||||
if (!ACCEPT_MIME.split(",").includes(file.type)) {
|
||||
onError?.(`"${file.name}" harus JPG, PNG, atau WebP`);
|
||||
return null;
|
||||
}
|
||||
if (file.size > MAX_BYTES) {
|
||||
onError?.(`"${file.name}" melebihi 12MB`);
|
||||
return null;
|
||||
}
|
||||
const fd = new FormData();
|
||||
fd.set("file", file);
|
||||
try {
|
||||
const res = await fetch("/api/upload/trip-image", {
|
||||
method: "POST",
|
||||
body: fd,
|
||||
});
|
||||
const json = await res.json();
|
||||
if (!res.ok) {
|
||||
onError?.(json.error ?? `Gagal mengunggah "${file.name}"`);
|
||||
return null;
|
||||
}
|
||||
return json.url as string;
|
||||
} catch {
|
||||
onError?.(`Gagal mengunggah "${file.name}"`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function handlePick(e: React.ChangeEvent<HTMLInputElement>) {
|
||||
const files = Array.from(e.target.files ?? []);
|
||||
e.target.value = "";
|
||||
if (files.length === 0) return;
|
||||
|
||||
if (remaining <= 0) {
|
||||
onError?.(`Maksimal ${max} foto`);
|
||||
return;
|
||||
}
|
||||
const picked = files.slice(0, remaining);
|
||||
if (files.length > remaining) {
|
||||
onError?.(`Hanya ${remaining} foto pertama diunggah (maks ${max})`);
|
||||
}
|
||||
|
||||
setUploadingCount((c) => c + picked.length);
|
||||
// `value` di-snapshot saat handler dibuat; upload sekuensial supaya urutan
|
||||
// foto stabil, lalu hasil yang berhasil ditambahkan sekali di akhir.
|
||||
const uploaded: string[] = [];
|
||||
for (const file of picked) {
|
||||
const url = await uploadOne(file);
|
||||
setUploadingCount((c) => c - 1);
|
||||
if (url) uploaded.push(url);
|
||||
}
|
||||
if (uploaded.length > 0) onChange([...value, ...uploaded]);
|
||||
}
|
||||
|
||||
function removeAt(index: number) {
|
||||
onChange(value.filter((_, i) => i !== index));
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<label className="mb-2 flex items-center justify-between">
|
||||
<span className="text-sm font-semibold text-neutral-700">
|
||||
Foto Trip
|
||||
</span>
|
||||
<span className="text-xs text-neutral-400">
|
||||
{value.length}/{max}
|
||||
</span>
|
||||
</label>
|
||||
|
||||
<div className="grid grid-cols-3 gap-2 sm:grid-cols-4">
|
||||
{value.map((url, i) => (
|
||||
<div
|
||||
key={url}
|
||||
className="group relative aspect-square overflow-hidden rounded-xl border border-neutral-200 bg-neutral-100"
|
||||
>
|
||||
<Image
|
||||
src={url}
|
||||
alt={i === 0 ? "Foto cover" : `Foto ${i + 1}`}
|
||||
fill
|
||||
className="object-cover"
|
||||
sizes="(max-width: 640px) 33vw, 160px"
|
||||
/>
|
||||
{i === 0 && (
|
||||
<span className="absolute left-1 top-1 rounded-md bg-primary-600/90 px-1.5 py-0.5 text-[10px] font-bold text-white">
|
||||
Cover
|
||||
</span>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => removeAt(i)}
|
||||
aria-label={`Hapus foto ${i + 1}`}
|
||||
className="absolute right-1 top-1 flex h-6 w-6 items-center justify-center rounded-full bg-black/55 text-white transition-colors hover:bg-red-600"
|
||||
>
|
||||
<X size={13} strokeWidth={2.5} aria-hidden />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{Array.from({ length: uploadingCount }).map((_, i) => (
|
||||
<div
|
||||
key={`uploading-${i}`}
|
||||
className="flex aspect-square items-center justify-center rounded-xl border border-dashed border-neutral-300 bg-neutral-50"
|
||||
>
|
||||
<Loader2
|
||||
size={20}
|
||||
strokeWidth={2}
|
||||
aria-hidden
|
||||
className="animate-spin text-neutral-400"
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{remaining > 0 && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => inputRef.current?.click()}
|
||||
className="flex aspect-square flex-col items-center justify-center gap-1 rounded-xl border border-dashed border-neutral-300 bg-neutral-50/60 text-neutral-500 transition-colors hover:border-primary-400 hover:text-primary-600"
|
||||
>
|
||||
<ImagePlus size={20} strokeWidth={1.75} aria-hidden />
|
||||
<span className="text-[11px] font-semibold">Tambah</span>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="file"
|
||||
accept={ACCEPT_MIME}
|
||||
multiple
|
||||
onChange={handlePick}
|
||||
className="sr-only"
|
||||
/>
|
||||
|
||||
<p className="mt-1.5 text-xs text-neutral-400">
|
||||
Unggah langsung dari galeri/kamera — JPG, PNG, atau WebP, maks 12MB per
|
||||
foto. Foto pertama jadi cover. Gambar besar otomatis dikompres tanpa
|
||||
mengorbankan kualitas.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -9,13 +9,21 @@ import {
|
||||
} from "@/lib/trip-dates";
|
||||
import { isValidTimeFormat, timeToMinutes } from "@/lib/itinerary";
|
||||
|
||||
/**
|
||||
* Foto trip sekarang adalah file yang diunggah ke server sendiri, bukan URL
|
||||
* eksternal. Nilai yang valid hanya path terkelola `/api/trip-images/<hex>.webp`
|
||||
* yang dihasilkan route upload — regex ini sengaja ketat supaya URL arbitrary
|
||||
* (yang dulu sering tidak reachable dari server) tidak bisa lolos lagi.
|
||||
*/
|
||||
export const tripImageUrlsSchema = z
|
||||
.array(
|
||||
z
|
||||
.string()
|
||||
.trim()
|
||||
.max(LIMITS.MAX_URL_LENGTH, "URL terlalu panjang")
|
||||
.url("Setiap URL gambar harus valid (http/https)")
|
||||
.regex(
|
||||
/^\/api\/trip-images\/[a-f0-9]{32}\.webp$/,
|
||||
"Foto trip tidak valid — silakan unggah ulang fotonya"
|
||||
)
|
||||
)
|
||||
.max(LIMITS.MAX_IMAGE_URLS, `Maksimal ${LIMITS.MAX_IMAGE_URLS} foto`);
|
||||
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
import { promises as fs } from "node:fs";
|
||||
import path from "node:path";
|
||||
import crypto from "node:crypto";
|
||||
import sharp from "sharp";
|
||||
|
||||
/**
|
||||
* Penyimpanan gambar trip — publik, di disk lokal.
|
||||
*
|
||||
* Beda dengan `secure-storage.ts` (KYC): gambar trip TIDAK dienkripsi karena
|
||||
* memang tampil ke semua pengunjung. Tiap gambar dikompres SEKALI saat upload
|
||||
* (resize + WebP), jadi saat render server tinggal serve file statik kecil —
|
||||
* tidak ada fetch URL eksternal, tidak ada masalah DNS.
|
||||
*/
|
||||
|
||||
/** Batas ukuran file mentah dari user (sebelum kompresi). */
|
||||
export const MAX_TRIP_IMAGE_UPLOAD_BYTES = 12 * 1024 * 1024;
|
||||
|
||||
/** MIME yang diterima saat upload. Output selalu dikonversi ke WebP. */
|
||||
export const ALLOWED_TRIP_IMAGE_MIME = new Set([
|
||||
"image/jpeg",
|
||||
"image/png",
|
||||
"image/webp",
|
||||
]);
|
||||
|
||||
/** Prefix URL publik untuk gambar trip yang dikelola sendiri. */
|
||||
export const TRIP_IMAGE_URL_PREFIX = "/api/trip-images/";
|
||||
|
||||
/** Sisi terpanjang hasil kompresi — cukup tajam untuk hero & cukup ringan. */
|
||||
const MAX_DIMENSION = 1920;
|
||||
/** Kualitas WebP — 80 = sweet spot kualitas/ukuran. */
|
||||
const WEBP_QUALITY = 80;
|
||||
|
||||
/** Nama file valid di disk: `<32-hex>.webp`. Dipakai untuk cegah path traversal. */
|
||||
const FILE_NAME_RE = /^[a-f0-9]{32}\.webp$/;
|
||||
|
||||
function rootDir(): string {
|
||||
const fromEnv = process.env.TRIP_UPLOAD_DIR;
|
||||
if (fromEnv && fromEnv.trim().length > 0) return fromEnv;
|
||||
return path.join(process.cwd(), "uploads", "trips");
|
||||
}
|
||||
|
||||
export function isValidTripImageName(name: string): boolean {
|
||||
return FILE_NAME_RE.test(name);
|
||||
}
|
||||
|
||||
/** Resolve nama file ke path absolut di dalam upload dir. Throw kalau mencurigakan. */
|
||||
function resolveName(name: string): string {
|
||||
if (!isValidTripImageName(name)) {
|
||||
throw new Error("Nama file gambar tidak valid");
|
||||
}
|
||||
const dir = rootDir();
|
||||
const abs = path.join(dir, name);
|
||||
if (!abs.startsWith(dir + path.sep)) {
|
||||
throw new Error("Nama file keluar dari direktori upload");
|
||||
}
|
||||
return abs;
|
||||
}
|
||||
|
||||
export type StoredTripImage = {
|
||||
/** Nama file di disk, mis. `ab12…ef.webp`. */
|
||||
name: string;
|
||||
/** URL publik yang disimpan ke `TripImage.url`. */
|
||||
url: string;
|
||||
/** Ukuran file hasil kompresi (byte). */
|
||||
size: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Kompres + simpan satu gambar trip. Input mentah (JPG/PNG/WebP) di-resize agar
|
||||
* muat dalam {@link MAX_DIMENSION}², dikonversi ke WebP, dan metadata (EXIF/GPS)
|
||||
* dibuang. Gambar 10MB+ dari kamera HP biasanya menyusut jadi ratusan KB tanpa
|
||||
* kehilangan kualitas yang terlihat.
|
||||
*
|
||||
* `sharp` melempar kalau buffer bukan gambar valid — itu jadi lapis validasi
|
||||
* konten yang lebih kuat dari sekadar percaya `file.type`.
|
||||
*/
|
||||
export async function processAndSaveTripImage(
|
||||
data: Buffer
|
||||
): Promise<StoredTripImage> {
|
||||
if (data.length === 0) throw new Error("File kosong");
|
||||
if (data.length > MAX_TRIP_IMAGE_UPLOAD_BYTES) {
|
||||
throw new Error("File terlalu besar");
|
||||
}
|
||||
|
||||
let optimized: Buffer;
|
||||
try {
|
||||
optimized = await sharp(data)
|
||||
// `.rotate()` tanpa argumen menerapkan orientasi dari EXIF lalu membuang
|
||||
// metadata — foto HP tidak miring & lokasi GPS user tidak ikut tersimpan.
|
||||
.rotate()
|
||||
.resize({
|
||||
width: MAX_DIMENSION,
|
||||
height: MAX_DIMENSION,
|
||||
fit: "inside",
|
||||
withoutEnlargement: true,
|
||||
})
|
||||
.webp({ quality: WEBP_QUALITY })
|
||||
.toBuffer();
|
||||
} catch {
|
||||
throw new Error("File bukan gambar yang valid");
|
||||
}
|
||||
|
||||
const name = `${crypto.randomBytes(16).toString("hex")}.webp`;
|
||||
const abs = resolveName(name);
|
||||
await fs.mkdir(path.dirname(abs), { recursive: true });
|
||||
await fs.writeFile(abs, optimized, { mode: 0o644 });
|
||||
|
||||
return {
|
||||
name,
|
||||
url: `${TRIP_IMAGE_URL_PREFIX}${name}`,
|
||||
size: optimized.length,
|
||||
};
|
||||
}
|
||||
|
||||
export async function readTripImage(name: string): Promise<Buffer> {
|
||||
return fs.readFile(resolveName(name));
|
||||
}
|
||||
|
||||
export async function deleteTripImage(name: string): Promise<void> {
|
||||
await fs.rm(resolveName(name), { force: true });
|
||||
}
|
||||
|
||||
/** True kalau URL menunjuk gambar trip yang dikelola sendiri (bukan URL eksternal lama). */
|
||||
export function isManagedTripImageUrl(url: string): boolean {
|
||||
if (!url.startsWith(TRIP_IMAGE_URL_PREFIX)) return false;
|
||||
return isValidTripImageName(url.slice(TRIP_IMAGE_URL_PREFIX.length));
|
||||
}
|
||||
|
||||
/** List semua nama file gambar yang ada di disk (untuk cron cleanup). */
|
||||
export async function listTripImageNames(): Promise<string[]> {
|
||||
try {
|
||||
const entries = await fs.readdir(rootDir());
|
||||
return entries.filter(isValidTripImageName);
|
||||
} catch (err) {
|
||||
if ((err as NodeJS.ErrnoException).code === "ENOENT") return [];
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/** mtime file. Null kalau file tidak ada. */
|
||||
export async function tripImageMtime(name: string): Promise<Date | null> {
|
||||
try {
|
||||
const st = await fs.stat(resolveName(name));
|
||||
return st.mtime;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,8 @@ const nextConfig: NextConfig = {
|
||||
dangerouslyAllowSVG: true,
|
||||
// AVIF didahulukan — ~30% lebih kecil dari WebP, didukung browser modern.
|
||||
formats: ["image/avif", "image/webp"],
|
||||
// 75 = default (kartu/thumbnail); 90 = lightbox foto trip ukuran penuh.
|
||||
qualities: [75, 90],
|
||||
// Cache hasil optimasi minimal 1 hari supaya tidak re-optimize tiap request.
|
||||
minimumCacheTTL: 86400,
|
||||
remotePatterns: [
|
||||
|
||||
Generated
+5
-1051
File diff suppressed because it is too large
Load Diff
+7
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "setrip",
|
||||
"version": "0.16.9",
|
||||
"version": "0.16.12",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
@@ -29,6 +29,7 @@
|
||||
"react-datepicker": "^9.1.0",
|
||||
"react-dom": "19.2.4",
|
||||
"resend": "^6.12.3",
|
||||
"sharp": "^0.34.5",
|
||||
"zod": "^4.3.6"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -43,5 +44,10 @@
|
||||
"tailwindcss": "^4",
|
||||
"tsx": "^4.21.0",
|
||||
"typescript": "^5"
|
||||
},
|
||||
"//overrides": "Patch sub-dependency transitif yang kena advisory npm audit, tanpa men-downgrade framework. Lepas saat versi induknya (next / prisma) sudah membawa versi aman sendiri.",
|
||||
"overrides": {
|
||||
"postcss": "^8.5.14",
|
||||
"@hono/node-server": "^1.19.13"
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user