diff --git a/src/app/(admin)/admin/(panel)/[resource]/[id]/page.tsx b/src/app/(admin)/admin/(panel)/[resource]/[id]/page.tsx new file mode 100644 index 0000000..a37cbaf --- /dev/null +++ b/src/app/(admin)/admin/(panel)/[resource]/[id]/page.tsx @@ -0,0 +1,33 @@ +import { notFound } from 'next/navigation'; +import { loadOptions, loadRows, optionSources } from '@/app/lib/admin/load'; +import { RESOURCE_BY_SLUG, type AdminRow } from '@/app/lib/admin/resources'; +import ResourceForm from '@/app/lib/admin/resource-form'; +import { PageHeader } from '@/app/lib/admin/ui'; + +export const dynamic = 'force-dynamic'; + +export default async function EditResourcePage({ + params, +}: { + params: Promise<{ resource: string; id: string }>; +}) { + const { resource: slug, id } = await params; + const resource = RESOURCE_BY_SLUG[slug]; + + if (!resource) notFound(); + + const rows = await loadRows(resource.slug); + const row: AdminRow | undefined = rows.find((entry) => String(entry.id) === id); + + if (!row) notFound(); + + const options = await loadOptions(optionSources(resource)); + + return ( + <> + + + + + ); +} \ No newline at end of file diff --git a/src/app/(admin)/admin/(panel)/[resource]/new/page.tsx b/src/app/(admin)/admin/(panel)/[resource]/new/page.tsx new file mode 100644 index 0000000..c3ab0a7 --- /dev/null +++ b/src/app/(admin)/admin/(panel)/[resource]/new/page.tsx @@ -0,0 +1,32 @@ +import { notFound } from 'next/navigation'; +import { loadOptions, optionSources } from '@/app/lib/admin/load'; +import { RESOURCE_BY_SLUG } from '@/app/lib/admin/resources'; +import ResourceForm from '@/app/lib/admin/resource-form'; +import { Alert, PageHeader } from '@/app/lib/admin/ui'; + +export const dynamic = 'force-dynamic'; + +export default async function NewResourcePage({ + params, +}: { + params: Promise<{ resource: string }>; +}) { + const { resource: slug } = await params; + const resource = RESOURCE_BY_SLUG[slug]; + + if (!resource || !resource.supportsCreate) notFound(); + + const options = await loadOptions(optionSources(resource)); + + return ( + <> + + + {Object.keys(options).length === 0 ? ( + هیچ گزینه‌ای برای انتخاب وجود ندارد. + ) : null} + + + + ); +} \ No newline at end of file diff --git a/src/app/(admin)/admin/(panel)/[resource]/page.tsx b/src/app/(admin)/admin/(panel)/[resource]/page.tsx new file mode 100644 index 0000000..a2f80c8 --- /dev/null +++ b/src/app/(admin)/admin/(panel)/[resource]/page.tsx @@ -0,0 +1,87 @@ +import Link from 'next/link'; +import { notFound } from 'next/navigation'; +import { deleteResourceAction } from '@/app/lib/admin/actions'; +import { cellValue, RESOURCE_BY_SLUG, type AdminRow } from '@/app/lib/admin/resources'; +import { loadRows } from '@/app/lib/admin/load'; +import { Card, EmptyState, PageHeader } from '@/app/lib/admin/ui'; + +export const dynamic = 'force-dynamic'; + +export default async function ResourceListPage({ + params, +}: { + params: Promise<{ resource: string }>; +}) { + const { resource: slug } = await params; + const resource = RESOURCE_BY_SLUG[slug]; + + if (!resource) notFound(); + + let rows: AdminRow[] = []; + + try { + rows = await loadRows(resource.slug); + } catch { + rows = []; + } + + return ( + <> + + افزودن {resource.singular} + + ) : undefined + } + /> + + {rows.length === 0 ? ( + + ) : ( +
+ {rows.map((row) => ( + +
+ {resource.listColumns.map((column) => ( +

+ {column.label}: + {cellValue(row, column.key) || '—'} +

+ ))} +
+ +
+ + ویرایش + + + {resource.supportsDelete ? ( +
+ + + +
+ ) : null} +
+
+ ))} +
+ )} + + ); +} \ No newline at end of file diff --git a/src/app/(admin)/admin/(panel)/layout.tsx b/src/app/(admin)/admin/(panel)/layout.tsx new file mode 100644 index 0000000..08e1688 --- /dev/null +++ b/src/app/(admin)/admin/(panel)/layout.tsx @@ -0,0 +1,18 @@ +import { redirect } from 'next/navigation'; +import { currentAdmin } from '@/app/lib/admin/api'; +import AdminNav from './nav'; + +export const dynamic = 'force-dynamic'; + +export default async function PanelLayout({ children }: { children: React.ReactNode }) { + const admin = await currentAdmin(); + + if (!admin) redirect('/admin/login'); + + return ( +
+ +
{children}
+
+ ); +} \ No newline at end of file diff --git a/src/app/(admin)/admin/(panel)/nav.tsx b/src/app/(admin)/admin/(panel)/nav.tsx new file mode 100644 index 0000000..2c0ceb3 --- /dev/null +++ b/src/app/(admin)/admin/(panel)/nav.tsx @@ -0,0 +1,53 @@ +import Link from 'next/link'; +import { logoutAction } from '@/app/lib/admin/actions'; +import { RESOURCES } from '@/app/lib/admin/resources'; + +export default function AdminNav({ email }: { email: string }) { + return ( + + ); +} \ No newline at end of file diff --git a/src/app/(admin)/admin/(panel)/page.tsx b/src/app/(admin)/admin/(panel)/page.tsx new file mode 100644 index 0000000..2d41966 --- /dev/null +++ b/src/app/(admin)/admin/(panel)/page.tsx @@ -0,0 +1,54 @@ +import Link from 'next/link'; +import { loadRows } from '@/app/lib/admin/load'; +import { RESOURCES } from '@/app/lib/admin/resources'; +import { Card, PageHeader } from '@/app/lib/admin/ui'; + +export const dynamic = 'force-dynamic'; + +export default async function AdminDashboardPage() { + const counts = await Promise.all( + RESOURCES.map(async (resource) => { + try { + const rows = await loadRows(resource.slug); + return { resource, total: rows.length }; + } catch { + return { resource, total: -1 }; + } + }), + ); + + const draftPosts = await (async () => { + try { + const rows = await loadRows('posts'); + return rows.filter((row) => !row.published_at).length; + } catch { + return -1; + } + })(); + + return ( + <> + + +
+ {counts.map(({ resource, total }) => ( + + +

{resource.title}

+

+ {total === -1 ? '—' : total.toLocaleString('fa-IR')} +

+
+ + ))} +
+ + +

نوشته‌های پیش‌نویس

+

+ {draftPosts === -1 ? '—' : draftPosts.toLocaleString('fa-IR')} +

+
+ + ); +} \ No newline at end of file diff --git a/src/app/(admin)/admin/layout.tsx b/src/app/(admin)/admin/layout.tsx new file mode 100644 index 0000000..8ae3134 --- /dev/null +++ b/src/app/(admin)/admin/layout.tsx @@ -0,0 +1,13 @@ +import type { Metadata } from 'next'; +import type { ReactNode } from 'react'; + +export const metadata: Metadata = { + title: 'پنل مدیریت', + robots: { index: false, follow: false, nocache: true }, +}; + +export default function AdminLayout({ children }: { children: ReactNode }) { + return ( +
{children}
+ ); +} \ No newline at end of file diff --git a/src/app/(admin)/admin/login/page.tsx b/src/app/(admin)/admin/login/page.tsx new file mode 100644 index 0000000..1b90aec --- /dev/null +++ b/src/app/(admin)/admin/login/page.tsx @@ -0,0 +1,25 @@ +import { redirect } from 'next/navigation'; +import { currentAdmin } from '@/app/lib/admin/api'; +import LoginForm from '@/app/lib/admin/login-form'; +import { Card } from '@/app/lib/admin/ui'; + +export const dynamic = 'force-dynamic'; + +export default async function AdminLoginPage() { + if (await currentAdmin()) redirect('/admin'); + + return ( +
+ +
+

پنل مدیریت

+

+ برای مدیریت محتوای سایت وارد شوید. +

+
+ + +
+
+ ); +} \ No newline at end of file diff --git a/src/app/lib/admin/actions.ts b/src/app/lib/admin/actions.ts new file mode 100644 index 0000000..6810dd9 --- /dev/null +++ b/src/app/lib/admin/actions.ts @@ -0,0 +1,121 @@ +'use server'; + +import { revalidatePath } from 'next/cache'; +import { redirect } from 'next/navigation'; +import { AdminApiError, adminFetch, currentAdmin, loginAdmin, logoutAdmin } from './api'; +import { RESOURCE_BY_SLUG, type ResourceDef } from './resources'; +import type { FormState } from './format'; + +function message(error: unknown): string { + if (error instanceof AdminApiError) return error.message; + + return 'خطای پیش‌بینی‌نشده رخ داد.'; +} + +function require(slug: string): ResourceDef { + const resource = RESOURCE_BY_SLUG[slug]; + + if (!resource) throw new AdminApiError('منبع نامعتبر است.', 404); + + return resource; +} + +/** Fields the API requires that the form should not make the author supply. */ +function implicitFields(resource: ResourceDef, adminId: number): Record { + if (resource.slug === 'posts') return { author_id: adminId }; + + return {}; +} + +function collect(formData: FormData, resource: ResourceDef, adminId: number): Record { + const payload: Record = implicitFields(resource, adminId); + + for (const field of resource.fields) { + if (field.kind === 'multiselect') { + const values = formData.getAll(field.name).map(Number).filter((id) => Number.isFinite(id)); + + if (values.length > 0) payload[field.name] = values; + continue; + } + + const raw = formData.get(field.name); + + if (raw === null || raw === '') continue; + + const value = typeof raw === 'string' ? raw.trim() : raw; + + if (field.kind === 'number') { + payload[field.name] = Number(value); + continue; + } + + if (field.kind === 'datetime') { + payload[field.name] = new Date(String(value)).toISOString(); + continue; + } + + payload[field.name] = value; + } + + return payload; +} + +export async function loginAction(_previous: FormState, formData: FormData): Promise { + const email = String(formData.get('email') ?? '').trim(); + const password = String(formData.get('password') ?? ''); + const remember = formData.get('remember') === 'on'; + + if (!email || !password) return { error: 'ایمیل و گذرواژه الزامی است.' }; + + try { + await loginAdmin(email, password, remember); + } catch (error) { + return { error: message(error) }; + } + + redirect('/admin'); +} + +export async function logoutAction(): Promise { + await logoutAdmin(); + redirect('/admin/login'); +} + +export async function saveResourceAction( + _previous: FormState, + formData: FormData, +): Promise { + const resource = require(String(formData.get('__resource') ?? '')); + const recordId = String(formData.get('__id') ?? ''); + + const admin = await currentAdmin(); + + if (!admin) return { error: 'نشست مدیریتی برقرار نیست.' }; + + const payload = collect(formData, resource, admin.id); + const isUpdate = recordId !== ''; + + try { + await adminFetch(isUpdate ? `${resource.basePath}/${recordId}` : resource.basePath, { + method: isUpdate ? 'PUT' : 'POST', + body: payload, + }); + } catch (error) { + return { error: message(error) }; + } + + revalidatePath('/admin', 'layout'); + redirect(`/admin/${resource.slug}`); +} + +export async function deleteResourceAction(formData: FormData): Promise { + const resource = require(String(formData.get('__resource') ?? '')); + const recordId = String(formData.get('__id') ?? ''); + + if (!recordId || !resource.supportsDelete) return; + + await adminFetch(`${resource.basePath}/${recordId}`, { method: 'DELETE' }); + + revalidatePath('/admin', 'layout'); + redirect(`/admin/${resource.slug}`); +} \ No newline at end of file diff --git a/src/app/lib/admin/api.ts b/src/app/lib/admin/api.ts new file mode 100644 index 0000000..e0d420c --- /dev/null +++ b/src/app/lib/admin/api.ts @@ -0,0 +1,179 @@ +import { cookies } from 'next/headers'; + +export const ADMIN_COOKIE = 'parsaaghayi_admin_session'; + +const BACKEND = process.env.NEXT_PUBLIC_BACK_URL || 'https://backend.parsaaghayi.ir'; + +export type AdminUser = { + id: number; + name: string; + email: string; + is_admin: boolean; + created_at: string; + updated_at: string; +}; + +export class AdminApiError extends Error { + status: number; + + constructor(message: string, status: number) { + super(message); + this.name = 'AdminApiError'; + this.status = status; + } +} + +export function cookieDomain(): string | undefined { + const host = (() => { + try { + return new URL(process.env.NEXT_PUBLIC_FRONT_URL || 'https://parsaaghayi.ir').hostname; + } catch { + return ''; + } + })(); + + if (!host || host === 'localhost' || host === '127.0.0.1') return undefined; + + return host.startsWith('www.') ? `.${host.slice(4)}` : `.${host}`; +} + +export async function adminToken(): Promise { + const jar = await cookies(); + return jar.get(ADMIN_COOKIE)?.value ?? null; +} + +function readSetCookie(response: Response, name: string): string | null { + const lines = + typeof response.headers.getSetCookie === 'function' ? response.headers.getSetCookie() : []; + const line = lines.find((entry) => entry.startsWith(`${name}=`)); + + if (!line) return null; + + return decodeURIComponent(line.slice(name.length + 1).split(';')[0] ?? ''); +} + +function messageFrom(payload: unknown, fallback: string): string { + if (payload && typeof payload === 'object') { + const errors = (payload as { errors?: Record }).errors; + const first = errors ? Object.values(errors)[0]?.[0] : undefined; + + if (first) return first; + + const message = (payload as { message?: string }).message; + if (message) return message; + } + + return fallback; +} + +type AdminFetchOptions = { + method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'; + body?: unknown; +}; + +export async function adminFetch(path: string, options: AdminFetchOptions = {}): Promise { + const { method = 'GET', body } = options; + const token = await adminToken(); + + if (!token) throw new AdminApiError('نشست مدیریتی برقرار نیست.', 401); + + const headers: Record = { + Accept: 'application/json', + Authorization: `Bearer ${token}`, + }; + + if (body !== undefined) headers['Content-Type'] = 'application/json'; + + const response = await fetch(`${BACKEND}/api${path}`, { + method, + headers, + body: body === undefined ? undefined : JSON.stringify(body), + cache: 'no-store', + }); + + const text = await response.text(); + const payload: unknown = text ? safeJson(text) : null; + + if (!response.ok) { + throw new AdminApiError(messageFrom(payload, `درخواست با خطا مواجه شد (${response.status}).`), response.status); + } + + return payload as T; +} + +function safeJson(text: string): unknown { + try { + return JSON.parse(text); + } catch { + return null; + } +} + +export async function listRows(path: string): Promise { + const payload = await adminFetch<{ data?: T[] } | T[]>(path); + return Array.isArray(payload) ? payload : (payload?.data ?? []); +} + +export async function loginAdmin(email: string, password: string, remember: boolean): Promise { + const response = await fetch(`${BACKEND}/api/auth/login`, { + method: 'POST', + headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, + body: JSON.stringify({ email, password, remember }), + cache: 'no-store', + }); + + const text = await response.text(); + const payload: unknown = text ? safeJson(text) : null; + + if (!response.ok) { + throw new AdminApiError( + messageFrom(payload, 'ورود ناموفق بود. ایمیل یا گذرواژه نادرست است.'), + response.status, + ); + } + + const token = readSetCookie(response, ADMIN_COOKIE); + + if (!token) throw new AdminApiError('توکن نشست از سمت سرور دریافت نشد.', 500); + + const jar = await cookies(); + jar.set(ADMIN_COOKIE, token, { + httpOnly: true, + secure: process.env.NODE_ENV === 'production', + sameSite: 'lax', + path: '/', + domain: cookieDomain(), + maxAge: remember ? 60 * 60 * 24 * 14 : undefined, + }); + + return (payload as { user: AdminUser }).user; +} + +export async function logoutAdmin(): Promise { + try { + await adminFetch('/auth/logout', { method: 'POST' }); + } finally { + const jar = await cookies(); + jar.delete(ADMIN_COOKIE); + } +} + +export async function currentAdmin(): Promise { + const token = await adminToken(); + + if (!token) return null; + + try { + const response = await fetch(`${BACKEND}/api/auth/me`, { + headers: { Accept: 'application/json', Authorization: `Bearer ${token}` }, + cache: 'no-store', + }); + + if (!response.ok) return null; + + const payload = (await response.json()) as { user: AdminUser }; + return payload.user ?? null; + } catch { + return null; + } +} \ No newline at end of file diff --git a/src/app/lib/admin/format.ts b/src/app/lib/admin/format.ts new file mode 100644 index 0000000..26e04dc --- /dev/null +++ b/src/app/lib/admin/format.ts @@ -0,0 +1,36 @@ +export type FormState = { error: string | null }; + +export const EMPTY_STATE: FormState = { error: null }; + +export function toDateTimeInput(value: unknown): string { + if (typeof value !== 'string' || value === '') return ''; + + const parsed = new Date(value); + + if (Number.isNaN(parsed.getTime())) return ''; + + const pad = (input: number) => String(input).padStart(2, '0'); + + return `${parsed.getFullYear()}-${pad(parsed.getMonth() + 1)}-${pad(parsed.getDate())}T${pad( + parsed.getHours(), + )}:${pad(parsed.getMinutes())}`; +} + +export function formatDate(value: unknown): string { + if (typeof value !== 'string' || value === '') return '—'; + + const parsed = new Date(value); + if (Number.isNaN(parsed.getTime())) return String(value); + + return new Intl.DateTimeFormat('fa-IR', { dateStyle: 'medium' }).format(parsed); +} + +export function textValue(value: unknown): string { + if (value === null || value === undefined) return ''; + + if (Array.isArray(value)) return value.join('، '); + + if (typeof value === 'object') return JSON.stringify(value); + + return String(value); +} \ No newline at end of file diff --git a/src/app/lib/admin/load.ts b/src/app/lib/admin/load.ts new file mode 100644 index 0000000..1d3c5b5 --- /dev/null +++ b/src/app/lib/admin/load.ts @@ -0,0 +1,38 @@ +import { listRows } from './api'; +import { + RESOURCE_BY_SLUG, + optionLabel, + type AdminRow, + type OptionRow, + type ResourceDef, +} from './resources'; + +export async function loadRows(slug: string): Promise { + return listRows(`/admin/resources/${slug}`); +} + +export function optionSources(resource: ResourceDef): string[] { + const sources = resource.fields + .map((field) => field.optionsFrom) + .filter((source): source is NonNullable => Boolean(source)); + + return Array.from(new Set(sources)); +} + +export async function loadOptions(sources: string[]): Promise> { + const entries = await Promise.all( + sources.map(async (source) => { + const rows = await loadRows(source); + const definition = RESOURCE_BY_SLUG[source]; + + const options = rows.map((row) => ({ + id: row.id, + label: definition ? optionLabel(row, definition) : String(row.id), + })); + + return [source, options] as const; + }), + ); + + return Object.fromEntries(entries); +} \ No newline at end of file diff --git a/src/app/lib/admin/login-form.tsx b/src/app/lib/admin/login-form.tsx new file mode 100644 index 0000000..9f8c05c --- /dev/null +++ b/src/app/lib/admin/login-form.tsx @@ -0,0 +1,49 @@ +'use client'; + +import { useActionState } from 'react'; +import { loginAction } from './actions'; +import { EMPTY_STATE } from './format'; +import { Alert, Button, Field, inputClass } from './ui'; + +export default function LoginForm() { + const [state, formAction, isPending] = useActionState(loginAction, EMPTY_STATE); + + return ( +
+ {state.error ? {state.error} : null} + + + + + + + + + + + + +
+ ); +} \ No newline at end of file diff --git a/src/app/lib/admin/resource-form.tsx b/src/app/lib/admin/resource-form.tsx new file mode 100644 index 0000000..6a11266 --- /dev/null +++ b/src/app/lib/admin/resource-form.tsx @@ -0,0 +1,168 @@ +'use client'; + +import { useActionState } from 'react'; +import { EMPTY_STATE, toDateTimeInput } from './format'; +import { saveResourceAction } from './actions'; +import type { AdminRow, FieldDef, OptionRow, ResourceDef } from './resources'; +import { Alert, Button, Field, inputClass } from './ui'; + +const LOCALE_TITLES: Record = { + fa: 'نسخه فارسی', + en: 'English version', +}; + +function initialValue(row: AdminRow | null, field: FieldDef): string | string[] { + if (!row) return field.kind === 'multiselect' ? [] : ''; + + if (field.kind === 'multiselect') { + const selected = row[field.name]; + + if (Array.isArray(selected)) { + return selected.map((entry) => + String(typeof entry === 'object' && entry !== null ? (entry as { id: number }).id : entry), + ); + } + + return []; + } + + if (field.localeGroup) { + const translations = (row.translations ?? {}) as Record | undefined>; + const key = field.name.replace(/_(fa|en)$/, ''); + + return String(translations[key]?.[field.localeGroup] ?? ''); + } + + const value = row[field.name]; + + if (field.kind === 'datetime') return toDateTimeInput(value); + + if (value === null || value === undefined) return ''; + + if (Array.isArray(value)) return value.join('، '); + + if (typeof value === 'object') return JSON.stringify(value); + + return String(value); +} + +export default function ResourceForm({ + resource, + row, + options, +}: { + resource: ResourceDef; + row: AdminRow | null; + options: Record; +}) { + const [state, formAction, isPending] = useActionState(saveResourceAction, EMPTY_STATE); + + const ungrouped = resource.fields.filter((field) => !field.localeGroup); + const locales = Array.from( + new Set(resource.fields.map((field) => field.localeGroup).filter(Boolean)), + ) as string[]; + + const renderField = (field: FieldDef) => { + const id = `field-${field.name}`; + const value = initialValue(row, field); + + if (field.kind === 'select') { + return ( + + + + ); + } + + if (field.kind === 'multiselect') { + return ( + + + + ); + } + + if (field.kind === 'textarea') { + return ( + +