feat: monorepo with NestJS API, admin panel and DB-driven website

Restructure the repo into a pnpm + Turborepo monorepo:

- apps/web: Nuxt 4 site, now server-rendered and reading all content
  from the API; pages cached with SWR and purged on content changes
- apps/api: NestJS 12 + Prisma 7 + PostgreSQL. Auth with short-lived
  access tokens and rotating httpOnly refresh cookies, roles (ADMIN,
  EDITOR), catalog, editable site sections, media upload to S3-compatible
  storage (converted to WebP), contact messages, audit log
- apps/admin: Vue 3 admin panel (Ant Design Vue, Pinia, Tailwind) for
  products, categories, site sections, messages, media and users
- packages/shared: Zod schemas and types shared by API and admin

Also:
- seed script that loads the original 8 categories / 89 products and
  section content
- Docker images for api (with a one-off migrate service), web, admin,
  and an nginx gateway for both domains
- dev and production compose files, daily database backup service
- API e2e tests

Removes the committed static out/ build and the old root Dockerfile.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
S. Esmaeili
2026-10-21 20:31:05 +03:30
co-authored by Claude Opus 5.5
parent 31076174e2
commit 789d224ea0
395 changed files with 19070 additions and 11592 deletions
+132
View File
@@ -0,0 +1,132 @@
<script setup lang="ts">
import {
ArrowDownOutlined,
ArrowUpOutlined,
DeleteOutlined,
EditOutlined,
ExportOutlined,
PlusOutlined,
} from "@ant-design/icons-vue";
import { message } from "ant-design-vue";
import { onMounted, ref } from "vue";
import { api, errorMessage } from "@/api/http";
import type { AdminCategory } from "@/api/types";
import PageHeader from "@/components/PageHeader.vue";
import { faNumber, SITE_URL } from "@/utils/format";
const rows = ref<AdminCategory[]>([]);
const loading = ref(false);
async function load() {
loading.value = true;
try {
rows.value = await api<AdminCategory[]>("/admin/categories");
} catch (e) {
void message.error(errorMessage(e));
} finally {
loading.value = false;
}
}
async function move(index: number, d: -1 | 1) {
const list = [...rows.value];
const [row] = list.splice(index, 1);
list.splice(index + d, 0, row!);
rows.value = list;
try {
await api("/admin/categories/reorder", { method: "POST", body: { ids: list.map((r) => r.id) } });
} catch (e) {
void message.error(errorMessage(e));
await load();
}
}
async function remove(row: AdminCategory) {
try {
await api(`/admin/categories/${row.id}`, { method: "DELETE" });
void message.success("دسته حذف شد");
await load();
} catch (e) {
void message.error(errorMessage(e));
}
}
const columns = [
{ title: "تصویر", key: "cover", width: 80 },
{ title: "نام", key: "name" },
{ title: "کد", dataIndex: "code", width: 100 },
{ title: "محصولات", key: "products", width: 100 },
{ title: "وضعیت", key: "status", width: 110 },
{ title: "ترتیب", key: "order", width: 100 },
{ title: "", key: "actions", width: 170 },
];
onMounted(load);
</script>
<template>
<PageHeader title="دسته‌بندی‌ها" subtitle="ترتیب دسته‌ها همان ترتیب نمایش در سایت است">
<RouterLink :to="{ name: 'category-new' }">
<a-button type="primary">
<template #icon><PlusOutlined /></template>
دسته جدید
</a-button>
</RouterLink>
</PageHeader>
<a-card :body-style="{ padding: 0 }">
<a-table :columns="columns" :data-source="rows" :loading="loading" row-key="id" :pagination="false" :scroll="{ x: 800 }">
<template #bodyCell="{ column, record, index }">
<template v-if="column.key === 'cover'">
<img v-if="record.coverImage" :src="record.coverImage.url" alt="" class="size-12 rounded object-cover" />
</template>
<template v-else-if="column.key === 'name'">
<RouterLink :to="{ name: 'category-edit', params: { id: record.id } }" class="font-bold">
{{ record.name }}
</RouterLink>
<div class="text-xs text-gray-400" dir="ltr">{{ record.slug }}</div>
</template>
<template v-else-if="column.key === 'products'">
<RouterLink :to="{ name: 'products', query: { categoryId: record.id } }">
{{ faNumber(record.productCount) }}
</RouterLink>
</template>
<template v-else-if="column.key === 'status'">
<a-tag :color="record.isPublished ? 'green' : 'default'">
{{ record.isPublished ? "منتشرشده" : "مخفی" }}
</a-tag>
</template>
<template v-else-if="column.key === 'order'">
<a-space :size="4">
<a-button size="small" :disabled="index === 0" @click="move(index, -1)">
<template #icon><ArrowUpOutlined /></template>
</a-button>
<a-button size="small" :disabled="index === rows.length - 1" @click="move(index, 1)">
<template #icon><ArrowDownOutlined /></template>
</a-button>
</a-space>
</template>
<template v-else-if="column.key === 'actions'">
<a-space :size="4">
<RouterLink :to="{ name: 'category-edit', params: { id: record.id } }">
<a-button size="small"><template #icon><EditOutlined /></template></a-button>
</RouterLink>
<a :href="`${SITE_URL}/categories/${record.slug}`" target="_blank" rel="noopener">
<a-button size="small" title="مشاهده در سایت"><template #icon><ExportOutlined /></template></a-button>
</a>
<a-popconfirm
title="این دسته حذف شود؟"
ok-text="حذف"
cancel-text="انصراف"
@confirm="remove(record as AdminCategory)"
>
<a-button size="small" danger :disabled="record.productCount > 0" :title="record.productCount > 0 ? 'ابتدا محصولات این دسته را حذف یا جابه‌جا کنید' : 'حذف'">
<template #icon><DeleteOutlined /></template>
</a-button>
</a-popconfirm>
</a-space>
</template>
</template>
</a-table>
</a-card>
</template>
+203
View File
@@ -0,0 +1,203 @@
<script setup lang="ts">
import { SaveOutlined } from "@ant-design/icons-vue";
import { categoryInputSchema, type MediaDto } from "@imen/shared";
import { message } from "ant-design-vue";
import { computed, onMounted, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import type { z } from "zod";
import { api, errorMessage } from "@/api/http";
import type { AdminCategoryDetail } from "@/api/types";
import FormField from "@/components/FormField.vue";
import IconSelect from "@/components/IconSelect.vue";
import ImageField from "@/components/ImageField.vue";
import ListEditor from "@/components/ListEditor.vue";
import PageHeader from "@/components/PageHeader.vue";
import { useZodForm } from "@/composables/useZodForm";
import { toSlug } from "@/utils/slug";
type Form = z.output<typeof categoryInputSchema>;
type Group = Form["groups"][number];
const route = useRoute();
const router = useRouter();
const id = computed(() => (route.params.id ? Number(route.params.id) : null));
const empty: Form = {
slug: "",
code: "",
name: "",
nameEn: "",
shortDesc: "",
fullDesc: "",
icon: "",
coverImageId: null,
isPublished: true,
seoTitle: "",
seoDescription: "",
groups: [],
};
const { model, validate, handleError, reset } = useZodForm(categoryInputSchema, empty);
const cover = ref<MediaDto | null>(null);
/** product count per existing group id, to warn before deleting a group */
const groupProducts = ref<Record<number, number>>({});
const loading = ref(false);
const saving = ref(false);
async function load() {
if (!id.value) return;
loading.value = true;
try {
const c = await api<AdminCategoryDetail>(`/admin/categories/${id.value}`);
reset({
slug: c.slug,
code: c.code,
name: c.name,
nameEn: c.nameEn,
shortDesc: c.shortDesc,
fullDesc: c.fullDesc,
icon: c.icon,
coverImageId: c.coverImageId,
isPublished: c.isPublished,
seoTitle: c.seoTitle,
seoDescription: c.seoDescription,
groups: c.groups.map((g) => ({ id: g.id, slug: g.slug, name: g.name, desc: g.desc })),
});
cover.value = c.coverImage;
groupProducts.value = Object.fromEntries(c.groups.map((g) => [g.id, g.productCount]));
} catch (e) {
void message.error(errorMessage(e));
} finally {
loading.value = false;
}
}
function pickCover(m: MediaDto) {
cover.value = m;
model.value.coverImageId = m.id;
}
async function save() {
const data = validate();
if (!data) return;
saving.value = true;
try {
const saved = await api<AdminCategoryDetail>(
id.value ? `/admin/categories/${id.value}` : "/admin/categories",
{ method: id.value ? "PUT" : "POST", body: data },
);
void message.success("دسته ذخیره شد");
if (!id.value) await router.replace({ name: "category-edit", params: { id: saved.id } });
await load();
} catch (e) {
handleError(e);
} finally {
saving.value = false;
}
}
const newGroup = (): Group => ({ slug: "", name: "", desc: "" });
const groupTitle = (g: Group) => {
const count = g.id ? groupProducts.value[g.id] : 0;
return count ? `${g.name} (${count} محصول)` : g.name;
};
onMounted(load);
</script>
<template>
<PageHeader :title="id ? `ویرایش دسته: ${model.name}` : 'دسته جدید'" back="/categories">
<a-button type="primary" :loading="saving" @click="save">
<template #icon><SaveOutlined /></template>
ذخیره
</a-button>
</PageHeader>
<a-spin :spinning="loading">
<a-form layout="vertical" @submit.prevent="save">
<div class="grid gap-6 xl:grid-cols-3">
<div class="space-y-6 xl:col-span-2">
<a-card title="اطلاعات اصلی">
<div class="grid gap-x-4 md:grid-cols-2">
<FormField path="name" label="نام دسته" required>
<a-input v-model:value="model.name" />
</FormField>
<FormField path="nameEn" label="نام انگلیسی" hint="زیر نام دسته نمایش داده می‌شود">
<a-input v-model:value="model.nameEn" class="ltr-input" />
</FormField>
<FormField path="slug" label="اسلاگ (آدرس صفحه)" :hint="`آدرس: /categories/${model.slug || '...'}`" required>
<a-input v-model:value="model.slug" class="ltr-input">
<template #suffix>
<a class="text-xs" @click="model.slug = toSlug(model.nameEn)">ساخت از نام انگلیسی</a>
</template>
</a-input>
</FormField>
<FormField path="code" label="کد دسته" required>
<a-input v-model:value="model.code" class="ltr-input" placeholder="IP-C09" />
</FormField>
<FormField path="shortDesc" label="توضیح کوتاه" class="md:col-span-2">
<a-textarea v-model:value="model.shortDesc" :auto-size="{ minRows: 2, maxRows: 4 }" />
</FormField>
<FormField path="fullDesc" label="توضیح کامل (بالای صفحه دسته)" class="md:col-span-2">
<a-textarea v-model:value="model.fullDesc" :auto-size="{ minRows: 3, maxRows: 8 }" />
</FormField>
</div>
</a-card>
<a-card title="زیرگروه‌ها" :body-style="{ background: '#fafafa' }">
<p class="mb-4 text-sm text-gray-500">
زیرگروه‌ها در صفحه دسته به‌صورت فیلتر نمایش داده می‌شوند. با حذف یک زیرگروه، محصولات آن بدون زیرگروه می‌مانند.
</p>
<ListEditor
v-model="model.groups"
:create="newGroup"
add-label="افزودن زیرگروه"
:item-title="groupTitle"
>
<template #default="{ item, index }">
<div class="grid gap-x-4 md:grid-cols-2">
<FormField :path="`groups.${index}.name`" label="نام" required>
<a-input v-model:value="item.name" />
</FormField>
<FormField :path="`groups.${index}.slug`" label="اسلاگ" required>
<a-input v-model:value="item.slug" class="ltr-input" />
</FormField>
<FormField :path="`groups.${index}.desc`" label="توضیح" class="md:col-span-2">
<a-textarea v-model:value="item.desc" :auto-size="{ minRows: 1, maxRows: 4 }" />
</FormField>
</div>
</template>
</ListEditor>
</a-card>
</div>
<div class="space-y-6">
<a-card title="انتشار">
<FormField path="isPublished">
<a-switch v-model:checked="model.isPublished" />
<span class="ms-2">{{ model.isPublished ? "در سایت نمایش داده می‌شود" : "مخفی" }}</span>
</FormField>
</a-card>
<a-card title="تصویر کاور">
<FormField path="coverImageId">
<ImageField :url="cover?.url" clearable @pick="pickCover" @clear="cover = null; model.coverImageId = null" />
</FormField>
</a-card>
<a-card title="آیکون">
<FormField path="icon">
<IconSelect v-model="model.icon" allow-clear />
</FormField>
</a-card>
<a-card title="سئو">
<FormField path="seoTitle" label="عنوان صفحه" hint="خالی = نام دسته">
<a-input v-model:value="model.seoTitle" :maxlength="120" show-count />
</FormField>
<FormField path="seoDescription" label="توضیحات متا" hint="خالی = توضیح کامل">
<a-textarea v-model:value="model.seoDescription" :maxlength="300" show-count :auto-size="{ minRows: 3 }" />
</FormField>
</a-card>
</div>
</div>
</a-form>
</a-spin>
</template>
+87
View File
@@ -0,0 +1,87 @@
<script setup lang="ts">
import { PlusOutlined } from "@ant-design/icons-vue";
import { type DashboardDto, MESSAGE_STATUS_LABELS } from "@imen/shared";
import { message } from "ant-design-vue";
import { onMounted, ref } from "vue";
import { api, errorMessage } from "@/api/http";
import PageHeader from "@/components/PageHeader.vue";
import { activityLabel, faNumber, jalali } from "@/utils/format";
const data = ref<DashboardDto | null>(null);
onMounted(async () => {
try {
data.value = await api<DashboardDto>("/admin/dashboard");
} catch (e) {
void message.error(errorMessage(e));
}
});
</script>
<template>
<PageHeader title="داشبورد" subtitle="خلاصه وضعیت محتوای سایت">
<RouterLink :to="{ name: 'product-new' }">
<a-button type="primary">
<template #icon><PlusOutlined /></template>
محصول جدید
</a-button>
</RouterLink>
</PageHeader>
<a-spin :spinning="!data">
<div class="grid grid-cols-2 gap-4 lg:grid-cols-5">
<RouterLink :to="{ name: 'products' }">
<a-card hoverable><a-statistic title="محصولات" :value="faNumber(data?.products ?? 0)" /></a-card>
</RouterLink>
<RouterLink :to="{ name: 'products', query: { status: 'draft' } }">
<a-card hoverable><a-statistic title="پیش‌نویس" :value="faNumber(data?.draftProducts ?? 0)" /></a-card>
</RouterLink>
<RouterLink :to="{ name: 'categories' }">
<a-card hoverable><a-statistic title="دسته‌بندی‌ها" :value="faNumber(data?.categories ?? 0)" /></a-card>
</RouterLink>
<RouterLink :to="{ name: 'messages', query: { status: 'NEW' } }">
<a-card hoverable>
<a-statistic
title="پیام‌های جدید"
:value="faNumber(data?.newMessages ?? 0)"
:value-style="data?.newMessages ? { color: '#ff5a00' } : undefined"
/>
</a-card>
</RouterLink>
<RouterLink :to="{ name: 'media' }">
<a-card hoverable><a-statistic title="تصاویر" :value="faNumber(data?.media ?? 0)" /></a-card>
</RouterLink>
</div>
<div class="mt-6 grid gap-6 lg:grid-cols-2">
<a-card title="آخرین پیام‌های تماس">
<template #extra><RouterLink :to="{ name: 'messages' }">همه پیام‌ها</RouterLink></template>
<a-empty v-if="!data?.recentMessages.length" description="پیامی ثبت نشده است" />
<a-list v-else :data-source="data.recentMessages" item-layout="horizontal">
<template #renderItem="{ item }">
<a-list-item>
<a-list-item-meta :title="`${item.name} — ${item.org}`" :description="item.message || item.phone" />
<div class="text-left text-xs text-gray-400">
<a-tag :color="item.status === 'NEW' ? 'orange' : 'default'">{{ MESSAGE_STATUS_LABELS[item.status as keyof typeof MESSAGE_STATUS_LABELS] }}</a-tag>
<div class="mt-1">{{ jalali(item.createdAt) }}</div>
</div>
</a-list-item>
</template>
</a-list>
</a-card>
<a-card title="آخرین فعالیت‌ها">
<a-empty v-if="!data?.recentActivity.length" description="فعالیتی ثبت نشده است" />
<a-timeline v-else class="!mt-2">
<a-timeline-item v-for="a in data.recentActivity" :key="a.id">
<div class="text-sm">
<b>{{ activityLabel(a.action, a.entity) }}</b>
<span v-if="a.summary" class="text-gray-600"> — {{ a.summary }}</span>
</div>
<div class="text-xs text-gray-400">{{ a.user ?? "سیستم" }} · {{ jalali(a.createdAt) }}</div>
</a-timeline-item>
</a-timeline>
</a-card>
</div>
</a-spin>
</template>
+55
View File
@@ -0,0 +1,55 @@
<script setup lang="ts">
import { LockOutlined, MailOutlined } from "@ant-design/icons-vue";
import { loginSchema } from "@imen/shared";
import { ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import FormField from "@/components/FormField.vue";
import { useZodForm } from "@/composables/useZodForm";
import { useAuthStore } from "@/stores/auth";
const auth = useAuthStore();
const router = useRouter();
const route = useRoute();
const { model, validate, handleError } = useZodForm(loginSchema, { email: "", password: "" });
const loading = ref(false);
async function submit() {
const data = validate();
if (!data) return;
loading.value = true;
try {
await auth.login(data);
const redirect = typeof route.query.redirect === "string" ? route.query.redirect : "/";
await router.replace(redirect.startsWith("/") ? redirect : "/");
} catch (e) {
handleError(e);
} finally {
loading.value = false;
}
}
</script>
<template>
<div class="flex min-h-screen items-center justify-center bg-[#0b1224] p-4">
<div class="w-full max-w-sm rounded-2xl bg-white p-8 shadow-2xl">
<div class="mb-8 text-center">
<img src="/favicon.svg" alt="" class="mx-auto size-12" />
<h1 class="mt-4 text-xl font-bold text-gray-800">پنل مدیریت ایمن پیشگامان</h1>
<p class="mt-1 text-sm text-gray-500">برای ادامه وارد شوید</p>
</div>
<a-form layout="vertical" @submit.prevent="submit">
<FormField path="email" label="ایمیل">
<a-input v-model:value="model.email" size="large" class="ltr-input" autocomplete="username" autofocus>
<template #prefix><MailOutlined class="text-gray-400" /></template>
</a-input>
</FormField>
<FormField path="password" label="رمز عبور">
<a-input-password v-model:value="model.password" size="large" class="ltr-input" autocomplete="current-password">
<template #prefix><LockOutlined class="text-gray-400" /></template>
</a-input-password>
</FormField>
<a-button type="primary" html-type="submit" size="large" block :loading="loading">ورود</a-button>
</a-form>
</div>
</div>
</template>
+151
View File
@@ -0,0 +1,151 @@
<script setup lang="ts">
import { CopyOutlined, DeleteOutlined, UploadOutlined } from "@ant-design/icons-vue";
import type { MediaDto, Paginated } from "@imen/shared";
import { message } from "ant-design-vue";
import { onMounted, ref } from "vue";
import { api, errorMessage } from "@/api/http";
import PageHeader from "@/components/PageHeader.vue";
import { faNumber, fileSize, jalali } from "@/utils/format";
const items = ref<MediaDto[]>([]);
const total = ref(0);
const page = ref(1);
const q = ref("");
const loading = ref(false);
const uploading = ref(0);
const selected = ref<MediaDto | null>(null);
const altDraft = ref("");
const PAGE_SIZE = 36;
async function load() {
loading.value = true;
try {
const res = await api<Paginated<MediaDto>>("/admin/media", {
query: { page: page.value, pageSize: PAGE_SIZE, q: q.value || undefined },
});
items.value = res.items;
total.value = res.total;
} catch (e) {
void message.error(errorMessage(e));
} finally {
loading.value = false;
}
}
async function upload(file: File) {
uploading.value++;
try {
const body = new FormData();
body.append("file", file);
await api<MediaDto>("/admin/media", { method: "POST", body });
void message.success(`«${file.name}» آپلود شد`);
page.value = 1;
await load();
} catch (e) {
void message.error(`${file.name}: ${errorMessage(e)}`);
} finally {
uploading.value--;
}
return false;
}
function open(m: MediaDto) {
selected.value = m;
altDraft.value = m.alt;
}
async function saveAlt() {
if (!selected.value) return;
try {
const m = await api<MediaDto>(`/admin/media/${selected.value.id}`, { method: "PATCH", body: { alt: altDraft.value } });
Object.assign(selected.value, m);
void message.success("ذخیره شد");
} catch (e) {
void message.error(errorMessage(e));
}
}
async function remove() {
if (!selected.value) return;
try {
await api(`/admin/media/${selected.value.id}`, { method: "DELETE" });
void message.success("تصویر حذف شد");
selected.value = null;
await load();
} catch (e) {
void message.error(errorMessage(e));
}
}
async function copyUrl(url: string) {
await navigator.clipboard.writeText(new URL(url, location.origin).toString());
void message.success("آدرس کپی شد");
}
onMounted(load);
</script>
<template>
<PageHeader title="کتابخانه رسانه" :subtitle="`${faNumber(total)} تصویر`">
<a-upload accept="image/jpeg,image/png,image/webp,image/avif,image/gif" multiple :show-upload-list="false" :before-upload="upload">
<a-button type="primary" :loading="uploading > 0">
<template #icon><UploadOutlined /></template>
آپلود تصویر
</a-button>
</a-upload>
</PageHeader>
<a-card>
<a-input-search
v-model:value="q"
allow-clear
placeholder="جستجو در نام فایل یا متن جایگزین"
class="mb-4 max-w-md"
@search="() => { page = 1; load(); }"
/>
<a-spin :spinning="loading">
<a-empty v-if="!items.length && !loading" description="تصویری پیدا نشد" />
<div class="grid grid-cols-3 gap-3 sm:grid-cols-4 md:grid-cols-6 xl:grid-cols-9">
<button
v-for="m in items"
:key="m.id"
type="button"
class="overflow-hidden rounded-lg border border-gray-200 bg-gray-50 transition hover:border-[#ff5a00]"
:title="m.originalName"
@click="open(m)"
>
<img :src="m.url" :alt="m.alt" class="aspect-square w-full object-contain" loading="lazy" />
</button>
</div>
</a-spin>
<div class="mt-4 flex justify-center">
<a-pagination v-model:current="page" :total="total" :page-size="PAGE_SIZE" :show-size-changer="false" @change="load" />
</div>
</a-card>
<a-drawer :open="!!selected" title="جزئیات تصویر" :width="380" placement="left" @close="selected = null">
<template v-if="selected">
<img :src="selected.url" :alt="selected.alt" class="w-full rounded-lg border border-gray-200 bg-gray-50 object-contain" />
<a-descriptions :column="1" size="small" class="mt-4">
<a-descriptions-item label="نام فایل"><span dir="ltr">{{ selected.originalName }}</span></a-descriptions-item>
<a-descriptions-item label="ابعاد">
<span dir="ltr">{{ selected.width }}×{{ selected.height }}</span>
</a-descriptions-item>
<a-descriptions-item label="حجم">{{ fileSize(selected.size) }}</a-descriptions-item>
<a-descriptions-item label="تاریخ">{{ jalali(selected.createdAt) }}</a-descriptions-item>
</a-descriptions>
<a-form layout="vertical" class="mt-4">
<a-form-item label="متن جایگزین (alt)">
<a-input v-model:value="altDraft" />
</a-form-item>
<a-space wrap>
<a-button type="primary" @click="saveAlt">ذخیره</a-button>
<a-button @click="copyUrl(selected.url)"><template #icon><CopyOutlined /></template>کپی آدرس</a-button>
<a-popconfirm title="این تصویر حذف شود؟" ok-text="حذف" cancel-text="انصراف" @confirm="remove">
<a-button danger><template #icon><DeleteOutlined /></template>حذف</a-button>
</a-popconfirm>
</a-space>
</a-form>
</template>
</a-drawer>
</template>
+126
View File
@@ -0,0 +1,126 @@
<script setup lang="ts">
import { DeleteOutlined } from "@ant-design/icons-vue";
import {
type ContactMessageDto,
MESSAGE_STATUS_LABELS,
MESSAGE_STATUSES,
type MessageStatus,
type Paginated,
} from "@imen/shared";
import { message } from "ant-design-vue";
import { onMounted, ref, watch } from "vue";
import { useRoute } from "vue-router";
import { api, errorMessage } from "@/api/http";
import PageHeader from "@/components/PageHeader.vue";
import { faNumber, jalali } from "@/utils/format";
const route = useRoute();
/** "ALL" or one status */
const status = ref<MessageStatus | "ALL">((route.query.status as MessageStatus) || "ALL");
const STATUS_OPTIONS = MESSAGE_STATUSES.map((s) => ({ value: s, label: MESSAGE_STATUS_LABELS[s] }));
const FILTER_OPTIONS = [{ value: "ALL", label: "همه" }, ...STATUS_OPTIONS];
const page = ref(1);
const rows = ref<ContactMessageDto[]>([]);
const total = ref(0);
const loading = ref(false);
const PAGE_SIZE = 20;
async function load() {
loading.value = true;
try {
const res = await api<Paginated<ContactMessageDto>>("/admin/messages", {
query: { status: status.value === "ALL" ? undefined : status.value, page: page.value, pageSize: PAGE_SIZE },
});
rows.value = res.items;
total.value = res.total;
} catch (e) {
void message.error(errorMessage(e));
} finally {
loading.value = false;
}
}
async function setStatus(row: ContactMessageDto, s: MessageStatus) {
try {
await api(`/admin/messages/${row.id}`, { method: "PATCH", body: { status: s } });
row.status = s;
} catch (e) {
void message.error(errorMessage(e));
}
}
/** opening a new message marks it as read */
function onExpand(expanded: boolean, row: ContactMessageDto) {
if (expanded && row.status === "NEW") void setStatus(row, "READ");
}
async function remove(row: ContactMessageDto) {
try {
await api(`/admin/messages/${row.id}`, { method: "DELETE" });
void message.success("پیام حذف شد");
await load();
} catch (e) {
void message.error(errorMessage(e));
}
}
const STATUS_COLORS: Record<MessageStatus, string> = { NEW: "orange", READ: "blue", ARCHIVED: "default" };
const columns = [
{ title: "نام", dataIndex: "name" },
{ title: "سازمان", dataIndex: "org" },
{ title: "تلفن", key: "phone", width: 150 },
{ title: "تاریخ", key: "date", width: 170 },
{ title: "وضعیت", key: "status", width: 140 },
{ title: "", key: "actions", width: 60 },
];
watch(status, () => {
page.value = 1;
void load();
});
onMounted(load);
</script>
<template>
<PageHeader title="پیام‌های تماس" :subtitle="`${faNumber(total)} پیام — درخواست‌های ثبت‌شده از فرم مشاوره سایت`">
<a-segmented v-model:value="status" :options="FILTER_OPTIONS" />
</PageHeader>
<a-card :body-style="{ padding: 0 }">
<a-table
:columns="columns"
:data-source="rows"
:loading="loading"
row-key="id"
:scroll="{ x: 760 }"
:pagination="{ current: page, pageSize: PAGE_SIZE, total, showSizeChanger: false, onChange: (p: number) => { page = p; load(); } }"
@expand="onExpand"
>
<template #expandedRowRender="{ record }">
<p class="whitespace-pre-line leading-7">{{ record.message || "— بدون توضیح —" }}</p>
</template>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'phone'">
<a :href="`tel:${record.phone}`" dir="ltr">{{ record.phone }}</a>
</template>
<template v-else-if="column.key === 'date'">{{ jalali(record.createdAt) }}</template>
<template v-else-if="column.key === 'status'">
<a-select
:value="record.status"
size="small"
class="w-28"
:options="STATUS_OPTIONS"
@change="(v: unknown) => setStatus(record as ContactMessageDto, v as MessageStatus)"
>
<template #suffixIcon><a-badge :color="STATUS_COLORS[record.status as MessageStatus]" /></template>
</a-select>
</template>
<template v-else-if="column.key === 'actions'">
<a-popconfirm title="این پیام حذف شود؟" ok-text="حذف" cancel-text="انصراف" @confirm="remove(record as ContactMessageDto)">
<a-button size="small" danger><template #icon><DeleteOutlined /></template></a-button>
</a-popconfirm>
</template>
</template>
</a-table>
</a-card>
</template>
+245
View File
@@ -0,0 +1,245 @@
<script setup lang="ts">
import { CloseOutlined, PlusOutlined, SaveOutlined } from "@ant-design/icons-vue";
import { type MediaDto, productInputSchema } from "@imen/shared";
import { message } from "ant-design-vue";
import { computed, onMounted, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import type { z } from "zod";
import { api, errorMessage } from "@/api/http";
import type { AdminCategory, AdminCategoryDetail, AdminProductDetail } from "@/api/types";
import FormField from "@/components/FormField.vue";
import ImageField from "@/components/ImageField.vue";
import MediaPicker from "@/components/MediaPicker.vue";
import PageHeader from "@/components/PageHeader.vue";
import { useZodForm } from "@/composables/useZodForm";
import { SITE_URL } from "@/utils/format";
import { toSlug } from "@/utils/slug";
type Form = z.output<typeof productInputSchema>;
const route = useRoute();
const router = useRouter();
const id = computed(() => (route.params.id ? Number(route.params.id) : null));
const empty = (): Form => ({
categoryId: Number(route.query.categoryId) || (undefined as unknown as number),
groupId: null,
code: "",
slug: "",
name: "",
nameEn: "",
desc: "",
specs: [],
variants: [],
imageId: null,
galleryIds: [],
isPublished: true,
});
const { model, validate, handleError, reset } = useZodForm(productInputSchema, empty());
const image = ref<MediaDto | null>(null);
const gallery = ref<MediaDto[]>([]);
const galleryPicker = ref(false);
const categories = ref<AdminCategory[]>([]);
const groups = ref<AdminCategoryDetail["groups"]>([]);
const loading = ref(false);
const saving = ref(false);
const category = computed(() => categories.value.find((c) => c.id === model.value.categoryId));
/** a-select clears to undefined, the API expects null */
const groupId = computed({
get: () => model.value.groupId ?? undefined,
set: (v: number | undefined) => (model.value.groupId = v ?? null),
});
async function loadGroups(clear: boolean) {
if (clear) model.value.groupId = null;
groups.value = model.value.categoryId
? (await api<AdminCategoryDetail>(`/admin/categories/${model.value.categoryId}`)).groups
: [];
}
async function load() {
loading.value = true;
try {
categories.value = await api<AdminCategory[]>("/admin/categories");
if (id.value) {
const p = await api<AdminProductDetail>(`/admin/products/${id.value}`);
reset({
categoryId: p.categoryId,
groupId: p.groupId,
code: p.code,
slug: p.slug,
name: p.name,
nameEn: p.nameEn,
desc: p.desc,
specs: p.specs,
variants: p.variants,
imageId: p.imageId,
galleryIds: p.gallery.map((g) => g.id),
isPublished: p.isPublished,
});
image.value = p.image;
gallery.value = p.gallery;
} else {
reset(empty());
image.value = null;
gallery.value = [];
}
await loadGroups(false);
} catch (e) {
void message.error(errorMessage(e));
} finally {
loading.value = false;
}
}
function pickImage(m: MediaDto) {
image.value = m;
model.value.imageId = m.id;
}
function addToGallery(m: MediaDto) {
if (gallery.value.some((g) => g.id === m.id)) return;
gallery.value = [...gallery.value, m];
}
function removeFromGallery(mediaId: number) {
gallery.value = gallery.value.filter((g) => g.id !== mediaId);
}
watch(gallery, (g) => (model.value.galleryIds = g.map((m) => m.id)));
async function save() {
const data = validate();
if (!data) return;
saving.value = true;
try {
const saved = await api<AdminProductDetail>(id.value ? `/admin/products/${id.value}` : "/admin/products", {
method: id.value ? "PUT" : "POST",
body: data,
});
void message.success("محصول ذخیره شد");
if (!id.value) await router.replace({ name: "product-edit", params: { id: saved.id } });
else await load();
} catch (e) {
handleError(e);
} finally {
saving.value = false;
}
}
// /products/new and /products/:id share this component
watch(id, load);
onMounted(load);
</script>
<template>
<PageHeader :title="id ? `ویرایش محصول: ${model.name}` : 'محصول جدید'" back="/products">
<a
v-if="id && category && model.isPublished"
:href="`${SITE_URL}/categories/${category.slug}`"
target="_blank"
rel="noopener"
>
<a-button>مشاهده در سایت</a-button>
</a>
<a-button type="primary" :loading="saving" @click="save">
<template #icon><SaveOutlined /></template>
ذخیره
</a-button>
</PageHeader>
<a-spin :spinning="loading">
<a-form layout="vertical" @submit.prevent="save">
<div class="grid gap-6 xl:grid-cols-3">
<div class="space-y-6 xl:col-span-2">
<a-card title="اطلاعات محصول">
<div class="grid gap-x-4 md:grid-cols-2">
<FormField path="name" label="نام محصول" required>
<a-input v-model:value="model.name" />
</FormField>
<FormField path="nameEn" label="نام انگلیسی">
<a-input v-model:value="model.nameEn" class="ltr-input" />
</FormField>
<FormField path="code" label="کد محصول" required hint="یکتا، مثلاً IP-G20">
<a-input v-model:value="model.code" class="ltr-input" />
</FormField>
<FormField path="slug" label="اسلاگ" required>
<a-input v-model:value="model.slug" class="ltr-input">
<template #suffix>
<a class="text-xs" @click="model.slug = toSlug(model.code || model.nameEn || '')">ساخت از کد</a>
</template>
</a-input>
</FormField>
<FormField path="desc" label="توضیحات" class="md:col-span-2">
<a-textarea v-model:value="model.desc" :auto-size="{ minRows: 3, maxRows: 8 }" />
</FormField>
<FormField path="specs" label="ویژگی‌ها" hint="هر ویژگی را بنویسید و Enter بزنید" class="md:col-span-2">
<a-select v-model:value="model.specs" mode="tags" :open="false" placeholder="مثلاً: ضد برش" />
</FormField>
<FormField path="variants" label="مدل‌ها / رنگ‌ها" hint="اختیاری — هر مورد را بنویسید و Enter بزنید" class="md:col-span-2">
<a-select v-model:value="model.variants" mode="tags" :open="false" placeholder="مثلاً: مشکی/زرد" />
</FormField>
</div>
</a-card>
<a-card title="گالری تصاویر (اختیاری)">
<div class="flex flex-wrap gap-3">
<div v-for="m in gallery" :key="m.id" class="relative size-24 overflow-hidden rounded-lg border border-gray-200 bg-gray-50">
<img :src="m.url" alt="" class="size-full object-contain" />
<button
type="button"
class="absolute end-1 top-1 flex size-6 items-center justify-center rounded-full bg-white/90 text-red-500 shadow"
title="حذف از گالری"
@click="removeFromGallery(m.id)"
>
<CloseOutlined class="text-xs" />
</button>
</div>
<button
type="button"
class="flex size-24 items-center justify-center rounded-lg border border-dashed border-gray-300 text-gray-400 hover:border-[#ff5a00] hover:text-[#ff5a00]"
@click="galleryPicker = true"
>
<PlusOutlined />
</button>
</div>
<MediaPicker v-model:open="galleryPicker" @select="addToGallery" />
</a-card>
</div>
<div class="space-y-6">
<a-card title="انتشار">
<FormField path="isPublished">
<a-switch v-model:checked="model.isPublished" />
<span class="ms-2">{{ model.isPublished ? "در سایت نمایش داده می‌شود" : "پیش‌نویس (مخفی)" }}</span>
</FormField>
</a-card>
<a-card title="دسته‌بندی">
<FormField path="categoryId" label="دسته" required>
<a-select
v-model:value="model.categoryId"
placeholder="انتخاب دسته"
:options="categories.map((c) => ({ value: c.id, label: c.name }))"
@change="loadGroups(true)"
/>
</FormField>
<FormField path="groupId" label="زیرگروه">
<a-select
v-model:value="groupId"
allow-clear
:disabled="!groups.length"
:placeholder="groups.length ? 'بدون زیرگروه' : 'این دسته زیرگروه ندارد'"
:options="groups.map((g) => ({ value: g.id, label: g.name }))"
/>
</FormField>
</a-card>
<a-card title="تصویر اصلی">
<FormField path="imageId" hint="بدون تصویر، کاور دسته نمایش داده می‌شود">
<ImageField :url="image?.url" clearable @pick="pickImage" @clear="image = null; model.imageId = null" />
</FormField>
</a-card>
</div>
</div>
</a-form>
</a-spin>
</template>
+266
View File
@@ -0,0 +1,266 @@
<script setup lang="ts">
import {
ArrowDownOutlined,
ArrowUpOutlined,
CopyOutlined,
DeleteOutlined,
EditOutlined,
PlusOutlined,
} from "@ant-design/icons-vue";
import type { Paginated } from "@imen/shared";
import { message } from "ant-design-vue";
import { computed, onMounted, reactive, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { api, errorMessage } from "@/api/http";
import type { AdminCategory, AdminCategoryDetail, AdminProduct } from "@/api/types";
import PageHeader from "@/components/PageHeader.vue";
import { faNumber } from "@/utils/format";
const route = useRoute();
const router = useRouter();
const num = (v: unknown) => (v ? Number(v) : undefined);
const filters = reactive({
categoryId: num(route.query.categoryId),
groupId: num(route.query.groupId),
status: (route.query.status as "published" | "draft" | undefined) || undefined,
q: typeof route.query.q === "string" ? route.query.q : "",
page: num(route.query.page) ?? 1,
});
const rows = ref<AdminProduct[]>([]);
const total = ref(0);
const loading = ref(false);
const categories = ref<AdminCategory[]>([]);
const groups = ref<AdminCategoryDetail["groups"]>([]);
/** products without their own photo show the category cover (same fallback as the website) */
const thumbOf = (row: AdminProduct) =>
row.image ? { url: row.image.url, fallback: false } : {
url: categories.value.find((c) => c.id === row.categoryId)?.coverImage?.url ?? null,
fallback: true,
};
/** with a single category selected (and no other filter) the whole list is shown and can be reordered */
const reorderable = computed(() => !!filters.categoryId && !filters.groupId && !filters.status && !filters.q);
const pageSize = computed(() => (reorderable.value ? 200 : 30));
async function load() {
loading.value = true;
void router.replace({
query: Object.fromEntries(Object.entries(filters).filter(([k, v]) => v && !(k === "page" && v === 1))),
});
try {
const res = await api<Paginated<AdminProduct>>("/admin/products", {
query: { ...filters, q: filters.q || undefined, pageSize: pageSize.value },
});
rows.value = res.items;
total.value = res.total;
} catch (e) {
void message.error(errorMessage(e));
} finally {
loading.value = false;
}
}
async function loadGroups() {
groups.value = filters.categoryId
? (await api<AdminCategoryDetail>(`/admin/categories/${filters.categoryId}`)).groups
: [];
}
watch(
() => filters.categoryId,
async () => {
filters.groupId = undefined;
await loadGroups();
},
);
watch(
() => [filters.categoryId, filters.groupId, filters.status],
() => {
filters.page = 1;
void load();
},
);
async function togglePublish(row: AdminProduct, isPublished: boolean) {
try {
await api(`/admin/products/${row.id}/publish`, { method: "PATCH", body: { isPublished } });
row.isPublished = isPublished;
void message.success(isPublished ? "محصول منتشر شد" : "محصول از سایت مخفی شد");
} catch (e) {
void message.error(errorMessage(e));
}
}
async function duplicate(row: AdminProduct) {
try {
const copy = await api<{ id: number }>(`/admin/products/${row.id}/duplicate`, { method: "POST" });
void message.success("کپی پیش‌نویس ساخته شد");
await router.push({ name: "product-edit", params: { id: copy.id } });
} catch (e) {
void message.error(errorMessage(e));
}
}
async function remove(row: AdminProduct) {
try {
await api(`/admin/products/${row.id}`, { method: "DELETE" });
void message.success("محصول حذف شد");
await load();
} catch (e) {
void message.error(errorMessage(e));
}
}
async function move(index: number, d: -1 | 1) {
const list = [...rows.value];
const [row] = list.splice(index, 1);
list.splice(index + d, 0, row!);
rows.value = list;
try {
await api("/admin/products/reorder", { method: "POST", body: { ids: list.map((r) => r.id) } });
} catch (e) {
void message.error(errorMessage(e));
await load();
}
}
const columns = computed(() => [
{ title: "تصویر", key: "image", width: 76 },
{ title: "محصول", key: "name" },
{ title: "دسته / زیرگروه", key: "category", width: 200 },
{ title: "انتشار", key: "status", width: 90 },
...(reorderable.value ? [{ title: "ترتیب", key: "order", width: 100 }] : []),
{ title: "", key: "actions", width: 130 },
]);
onMounted(async () => {
try {
categories.value = await api<AdminCategory[]>("/admin/categories");
await loadGroups();
} catch (e) {
void message.error(errorMessage(e));
}
await load();
});
</script>
<template>
<PageHeader title="محصولات" :subtitle="`${faNumber(total)} محصول`">
<RouterLink :to="{ name: 'product-new', query: filters.categoryId ? { categoryId: filters.categoryId } : {} }">
<a-button type="primary">
<template #icon><PlusOutlined /></template>
محصول جدید
</a-button>
</RouterLink>
</PageHeader>
<a-card class="mb-4" :body-style="{ padding: '16px' }">
<div class="grid gap-3 md:grid-cols-4">
<a-select
v-model:value="filters.categoryId"
allow-clear
placeholder="همه دسته‌ها"
:options="categories.map((c) => ({ value: c.id, label: c.name }))"
/>
<a-select
v-model:value="filters.groupId"
allow-clear
placeholder="همه زیرگروه‌ها"
:disabled="!groups.length"
:options="groups.map((g) => ({ value: g.id, label: g.name }))"
/>
<a-select
v-model:value="filters.status"
allow-clear
placeholder="همه وضعیت‌ها"
:options="[
{ value: 'published', label: 'منتشرشده' },
{ value: 'draft', label: 'پیش‌نویس / مخفی' },
]"
/>
<a-input-search
v-model:value="filters.q"
allow-clear
placeholder="جستجوی نام یا کد"
@search="() => { filters.page = 1; load(); }"
/>
</div>
<p v-if="filters.categoryId && !reorderable" class="mt-3 text-xs text-gray-400">
برای تغییر ترتیب محصولات، فقط فیلتر دسته را نگه دارید.
</p>
</a-card>
<a-card :body-style="{ padding: 0 }">
<a-table
:columns="columns"
:data-source="rows"
:loading="loading"
row-key="id"
:scroll="{ x: 760 }"
:pagination="reorderable ? false : {
current: filters.page,
pageSize,
total,
showSizeChanger: false,
onChange: (p: number) => { filters.page = p; load(); },
}"
>
<template #bodyCell="{ column, record, index }">
<template v-if="column.key === 'image'">
<template v-if="thumbOf(record as AdminProduct).url">
<img
:src="thumbOf(record as AdminProduct).url!"
alt=""
:title="thumbOf(record as AdminProduct).fallback ? 'این محصول عکس ندارد؛ کاور دسته نمایش داده شده' : undefined"
:class="['size-12 rounded bg-gray-50 object-contain', thumbOf(record as AdminProduct).fallback && 'opacity-40 grayscale']"
/>
</template>
<div v-else class="size-12 rounded bg-gray-100" />
</template>
<template v-else-if="column.key === 'name'">
<RouterLink :to="{ name: 'product-edit', params: { id: record.id } }" class="font-bold">
{{ record.name }}
</RouterLink>
<div class="text-xs text-gray-400" dir="ltr">{{ record.code }}</div>
</template>
<template v-else-if="column.key === 'category'">
<div>{{ record.category.name }}</div>
<div v-if="record.group" class="text-xs text-gray-400">{{ record.group.name }}</div>
</template>
<template v-else-if="column.key === 'status'">
<a-switch
:checked="record.isPublished"
size="small"
@change="(v: unknown) => togglePublish(record as AdminProduct, !!v)"
/>
</template>
<template v-else-if="column.key === 'order'">
<a-space :size="4">
<a-button size="small" :disabled="index === 0" @click="move(index, -1)">
<template #icon><ArrowUpOutlined /></template>
</a-button>
<a-button size="small" :disabled="index === rows.length - 1" @click="move(index, 1)">
<template #icon><ArrowDownOutlined /></template>
</a-button>
</a-space>
</template>
<template v-else-if="column.key === 'actions'">
<a-space :size="4">
<RouterLink :to="{ name: 'product-edit', params: { id: record.id } }">
<a-button size="small" title="ویرایش"><template #icon><EditOutlined /></template></a-button>
</RouterLink>
<a-button size="small" title="کپی" @click="duplicate(record as AdminProduct)">
<template #icon><CopyOutlined /></template>
</a-button>
<a-popconfirm title="این محصول حذف شود؟" ok-text="حذف" cancel-text="انصراف" @confirm="remove(record as AdminProduct)">
<a-button size="small" danger title="حذف"><template #icon><DeleteOutlined /></template></a-button>
</a-popconfirm>
</a-space>
</template>
</template>
</a-table>
</a-card>
</template>
+56
View File
@@ -0,0 +1,56 @@
<script setup lang="ts">
import { changePasswordSchema, ROLE_LABELS } from "@imen/shared";
import { message } from "ant-design-vue";
import { ref } from "vue";
import { api } from "@/api/http";
import FormField from "@/components/FormField.vue";
import PageHeader from "@/components/PageHeader.vue";
import { useZodForm } from "@/composables/useZodForm";
import { useAuthStore } from "@/stores/auth";
const auth = useAuthStore();
const { model, validate, handleError, reset } = useZodForm(changePasswordSchema, {
currentPassword: "",
newPassword: "",
});
const saving = ref(false);
async function save() {
const data = validate();
if (!data) return;
saving.value = true;
try {
await api("/admin/auth/change-password", { method: "POST", body: data });
void message.success("رمز عبور تغییر کرد");
reset({ currentPassword: "", newPassword: "" });
} catch (e) {
handleError(e);
} finally {
saving.value = false;
}
}
</script>
<template>
<PageHeader title="حساب کاربری" />
<div class="grid max-w-4xl gap-6 md:grid-cols-2">
<a-card title="مشخصات">
<a-descriptions :column="1">
<a-descriptions-item label="نام">{{ auth.user?.name }}</a-descriptions-item>
<a-descriptions-item label="ایمیل"><span dir="ltr">{{ auth.user?.email }}</span></a-descriptions-item>
<a-descriptions-item label="نقش">{{ auth.user && ROLE_LABELS[auth.user.role] }}</a-descriptions-item>
</a-descriptions>
</a-card>
<a-card title="تغییر رمز عبور">
<a-form layout="vertical" @submit.prevent="save">
<FormField path="currentPassword" label="رمز فعلی" required>
<a-input-password v-model:value="model.currentPassword" class="ltr-input" autocomplete="current-password" />
</FormField>
<FormField path="newPassword" label="رمز جدید" hint="حداقل ۸ کاراکتر" required>
<a-input-password v-model:value="model.newPassword" class="ltr-input" autocomplete="new-password" />
</FormField>
<a-button type="primary" html-type="submit" :loading="saving">تغییر رمز</a-button>
</a-form>
</a-card>
</div>
</template>
+105
View File
@@ -0,0 +1,105 @@
<script setup lang="ts">
import { SaveOutlined } from "@ant-design/icons-vue";
import { isSectionKey, SECTION_LABELS, type SectionKey, sectionSchemas } from "@imen/shared";
import { message } from "ant-design-vue";
import { type Component, computed, ref } from "vue";
import { useRoute } from "vue-router";
import { api, errorMessage } from "@/api/http";
import type { SectionResponse } from "@/api/types";
import PageHeader from "@/components/PageHeader.vue";
import { useZodForm } from "@/composables/useZodForm";
import { jalali, SITE_URL } from "@/utils/format";
import AboutForm from "@/sections/AboutForm.vue";
import ContactForm from "@/sections/ContactForm.vue";
import FooterForm from "@/sections/FooterForm.vue";
import HeroForm from "@/sections/HeroForm.vue";
import IndustriesForm from "@/sections/IndustriesForm.vue";
import ProductsIntroForm from "@/sections/ProductsIntroForm.vue";
import ServicesForm from "@/sections/ServicesForm.vue";
import SettingsForm from "@/sections/SettingsForm.vue";
import StandardsForm from "@/sections/StandardsForm.vue";
import StatsForm from "@/sections/StatsForm.vue";
import TapeForm from "@/sections/TapeForm.vue";
import TestimonialsForm from "@/sections/TestimonialsForm.vue";
const FORMS: Record<SectionKey, Component> = {
settings: SettingsForm,
hero: HeroForm,
tape: TapeForm,
stats: StatsForm,
productsIntro: ProductsIntroForm,
about: AboutForm,
services: ServicesForm,
standards: StandardsForm,
industries: IndustriesForm,
testimonials: TestimonialsForm,
contact: ContactForm,
footer: FooterForm,
};
const route = useRoute();
const key = String(route.params.key);
const valid = isSectionKey(key);
const sectionKey = (valid ? key : "hero") as SectionKey;
// the page is re-created per key (RouterView keys by path), so one form instance per section
const { model, validate, handleError, reset } = useZodForm(
sectionSchemas[sectionKey] as (typeof sectionSchemas)["hero"],
{} as never,
);
const loaded = ref(false);
const saving = ref(false);
const updatedAt = ref<string | null>(null);
const label = computed(() => (valid ? SECTION_LABELS[sectionKey] : null));
async function load() {
try {
const res = await api<SectionResponse>(`/admin/sections/${sectionKey}`);
reset(res.data as never);
updatedAt.value = res.updatedAt;
loaded.value = true;
} catch (e) {
void message.error(errorMessage(e));
}
}
async function save() {
const data = validate();
if (!data) return;
saving.value = true;
try {
const res = await api<SectionResponse>(`/admin/sections/${sectionKey}`, { method: "PUT", body: data });
reset(res.data as never);
updatedAt.value = res.updatedAt;
void message.success("ذخیره شد؛ سایت تا چند لحظه دیگر به‌روز می‌شود");
} catch (e) {
handleError(e);
} finally {
saving.value = false;
}
}
if (valid) void load();
</script>
<template>
<a-result v-if="!valid" status="404" title="بخش پیدا نشد" />
<template v-else>
<PageHeader
:title="label!.title"
:subtitle="updatedAt ? `آخرین ذخیره: ${jalali(updatedAt)}` : label!.desc"
back="/sections"
>
<a :href="SITE_URL" target="_blank" rel="noopener"><a-button>مشاهده سایت</a-button></a>
<a-button type="primary" :loading="saving" :disabled="!loaded" @click="save">
<template #icon><SaveOutlined /></template>
ذخیره
</a-button>
</PageHeader>
<a-spin :spinning="!loaded">
<a-form v-if="loaded" layout="vertical" @submit.prevent="save">
<component :is="FORMS[sectionKey]" v-model="model" />
</a-form>
</a-spin>
</template>
</template>
+24
View File
@@ -0,0 +1,24 @@
<script setup lang="ts">
import { SECTION_KEYS, SECTION_LABELS } from "@imen/shared";
import PageHeader from "@/components/PageHeader.vue";
import { useAuthStore } from "@/stores/auth";
const auth = useAuthStore();
// site-wide settings are editable by admins only
const keys = SECTION_KEYS.filter((k) => k !== "settings" || auth.isAdmin);
</script>
<template>
<PageHeader
title="بخش‌های سایت"
subtitle="متن‌ها، تصاویر و فهرست‌های صفحه اصلی؛ تغییرات پس از ذخیره حداکثر ظرف یک دقیقه روی سایت دیده می‌شوند"
/>
<div class="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
<RouterLink v-for="key in keys" :key="key" :to="{ name: 'section-edit', params: { key } }">
<a-card hoverable class="h-full">
<div class="font-bold text-gray-800">{{ SECTION_LABELS[key].title }}</div>
<p class="mt-2 text-sm leading-6 text-gray-500">{{ SECTION_LABELS[key].desc }}</p>
</a-card>
</RouterLink>
</div>
</template>
+174
View File
@@ -0,0 +1,174 @@
<script setup lang="ts">
import { DeleteOutlined, EditOutlined, PlusOutlined } from "@ant-design/icons-vue";
import {
type AdminUserDto,
ROLE_LABELS,
ROLES,
toIssues,
userCreateSchema,
userUpdateSchema,
} from "@imen/shared";
import { message } from "ant-design-vue";
import { computed, onMounted, type Ref, ref } from "vue";
import type { z } from "zod";
import { api, errorMessage } from "@/api/http";
import FormField from "@/components/FormField.vue";
import PageHeader from "@/components/PageHeader.vue";
import { useZodForm } from "@/composables/useZodForm";
import { useAuthStore } from "@/stores/auth";
import { jalali } from "@/utils/format";
const auth = useAuthStore();
const rows = ref<AdminUserDto[]>([]);
const loading = ref(false);
/** null = closed, 0 = new user, id = editing */
const editing = ref<number | null>(null);
const saving = ref(false);
// one form model for both create and update; the matching schema validates on save
type Form = z.input<typeof userCreateSchema> & { isActive: boolean };
const empty: Form = { email: "", name: "", role: "EDITOR", password: "", isActive: true };
const form = useZodForm(userCreateSchema, empty);
const model = form.model as unknown as Ref<Form>;
const isNew = computed(() => editing.value === 0);
const ROLE_OPTIONS = ROLES.map((r) => ({ value: r, label: ROLE_LABELS[r] }));
async function load() {
loading.value = true;
try {
rows.value = await api<AdminUserDto[]>("/admin/users");
} catch (e) {
void message.error(errorMessage(e));
} finally {
loading.value = false;
}
}
function openNew() {
form.reset(empty);
editing.value = 0;
}
function openEdit(u: AdminUserDto) {
form.reset({ email: u.email, name: u.name, role: u.role, isActive: u.isActive, password: "" } as Form);
editing.value = u.id;
}
async function save() {
saving.value = true;
try {
if (isNew.value) {
const data = form.validate();
if (!data) return;
await api("/admin/users", { method: "POST", body: data });
} else {
const { name, role, isActive, password } = model.value;
const parsed = userUpdateSchema.safeParse({ name, role, isActive, password: password || undefined });
if (!parsed.success) {
form.errors.value = Object.fromEntries(toIssues(parsed.error).map((i) => [i.path, i.message]));
return;
}
await api(`/admin/users/${editing.value}`, { method: "PUT", body: parsed.data });
}
void message.success("ذخیره شد");
editing.value = null;
await load();
} catch (e) {
form.handleError(e);
} finally {
saving.value = false;
}
}
async function remove(u: AdminUserDto) {
try {
await api(`/admin/users/${u.id}`, { method: "DELETE" });
void message.success("کاربر حذف شد");
await load();
} catch (e) {
void message.error(errorMessage(e));
}
}
const columns = [
{ title: "نام", dataIndex: "name" },
{ title: "ایمیل", key: "email" },
{ title: "نقش", key: "role", width: 110 },
{ title: "وضعیت", key: "active", width: 100 },
{ title: "آخرین ورود", key: "login", width: 170 },
{ title: "", key: "actions", width: 100 },
];
onMounted(load);
</script>
<template>
<PageHeader title="کاربران پنل" subtitle="مدیر کل به همه بخش‌ها دسترسی دارد؛ ویرایشگر به جز کاربران و تنظیمات سایت">
<a-button type="primary" @click="openNew">
<template #icon><PlusOutlined /></template>
کاربر جدید
</a-button>
</PageHeader>
<a-card :body-style="{ padding: 0 }">
<a-table :columns="columns" :data-source="rows" :loading="loading" row-key="id" :pagination="false" :scroll="{ x: 700 }">
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'email'"><span dir="ltr">{{ record.email }}</span></template>
<template v-else-if="column.key === 'role'">
<a-tag :color="record.role === 'ADMIN' ? 'orange' : 'blue'">{{ ROLE_LABELS[record.role as keyof typeof ROLE_LABELS] }}</a-tag>
</template>
<template v-else-if="column.key === 'active'">
<a-tag :color="record.isActive ? 'green' : 'default'">{{ record.isActive ? "فعال" : "غیرفعال" }}</a-tag>
</template>
<template v-else-if="column.key === 'login'">{{ jalali(record.lastLoginAt) }}</template>
<template v-else-if="column.key === 'actions'">
<a-space :size="4">
<a-button size="small" @click="openEdit(record as AdminUserDto)"><template #icon><EditOutlined /></template></a-button>
<a-popconfirm
v-if="record.id !== auth.user?.id"
title="این کاربر حذف شود؟"
ok-text="حذف"
cancel-text="انصراف"
@confirm="remove(record as AdminUserDto)"
>
<a-button size="small" danger><template #icon><DeleteOutlined /></template></a-button>
</a-popconfirm>
</a-space>
</template>
</template>
</a-table>
</a-card>
<a-modal
:open="editing !== null"
:title="isNew ? 'کاربر جدید' : 'ویرایش کاربر'"
ok-text="ذخیره"
cancel-text="انصراف"
:confirm-loading="saving"
destroy-on-close
@ok="save"
@cancel="editing = null"
>
<a-form layout="vertical" class="mt-4" @submit.prevent="save">
<FormField path="email" label="ایمیل" required>
<a-input v-model:value="model.email" class="ltr-input" :disabled="!isNew" />
</FormField>
<FormField path="name" label="نام" required>
<a-input v-model:value="model.name" />
</FormField>
<FormField path="role" label="نقش" required>
<a-select
v-model:value="model.role"
:disabled="editing === auth.user?.id"
:options="ROLE_OPTIONS"
/>
</FormField>
<FormField v-if="!isNew" path="isActive">
<a-checkbox v-model:checked="model.isActive" :disabled="editing === auth.user?.id">حساب فعال است</a-checkbox>
</FormField>
<FormField path="password" :label="isNew ? 'رمز عبور' : 'رمز عبور جدید (اختیاری)'" :required="isNew" hint="حداقل ۸ کاراکتر">
<a-input-password v-model:value="model.password" class="ltr-input" autocomplete="new-password" />
</FormField>
</a-form>
</a-modal>
</template>