feat: add deep link

This commit is contained in:
2026-09-02 10:30:29 +03:30
parent 1898dbb322
commit fdbf02bc07
3 changed files with 785 additions and 0 deletions
@@ -0,0 +1,366 @@
"use client";
import { useState } from "react";
import { apiFetch, ApiError, toFormData } from "@/lib/api";
import { useList } from "@/lib/useResource";
import { useToast } from "@/components/toast";
import { DataTable, type Column } from "@/components/DataTable";
import {
Button,
ConfirmDialog,
Field,
Input,
Modal,
PageHeader,
Select,
Textarea,
} from "@/components/ui";
import { EditIcon, PlusIcon, TrashIcon } from "@/components/icons";
import { MediaPreview } from "@/components/MediaPreview";
import { pickUrl } from "@/lib/media";
import { toFa } from "@/lib/utils";
interface Category {
id: number;
name: string;
type: string;
order?: number;
description?: string | null;
icon?: string | null;
icon_url?: string | null;
deep_link?: string | null;
is_deeplink_only?: boolean;
subcategories_count?: number;
}
const ICON_KEYS = ["icon", "icon_url"];
export default function CategoryDeepLinksPage() {
const { data, loading, error, reload } = useList<Category>("/categories", {
deeplink_only: 1,
});
const { data: allCategories, loading: allLoading } =
useList<Category>("/categories");
const toast = useToast();
const [editing, setEditing] = useState<Category | null>(null);
const [open, setOpen] = useState(false);
const [saving, setSaving] = useState(false);
// Source: 'new' (create a hidden category) or 'existing' (pick existing to hide).
const [source, setSource] = useState<"new" | "existing">("new");
const [existingId, setExistingId] = useState<string>("");
// Fields for creating a new hidden category.
const [name, setName] = useState("");
const [type, setType] = useState("media");
const [order, setOrder] = useState("0");
const [description, setDescription] = useState("");
const [icon, setIcon] = useState<File | null>(null);
const [deleting, setDeleting] = useState<Category | null>(null);
const [removing, setRemoving] = useState(false);
function resetForm() {
setSource("new");
setExistingId("");
setName("");
setType("media");
setOrder("0");
setDescription("");
setIcon(null);
}
function openCreate() {
setEditing(null);
resetForm();
setOpen(true);
}
async function toggleHidden(row: Category) {
try {
await apiFetch(`/categories/${row.id}`, {
method: "POST",
body: toFormData({
is_deeplink_only: !row.is_deeplink_only ? 1 : 0,
}),
});
toast.success(
row.is_deeplink_only
? "از لینک مستقیم خارج شد."
: "به لینک مستقیم تبدیل شد.",
);
reload();
} catch (err) {
toast.error(err instanceof ApiError ? err.message : "خطا در ذخیره‌سازی");
}
}
async function save(e: React.FormEvent) {
e.preventDefault();
setSaving(true);
try {
if (editing) {
setOpen(false);
reload();
toast.success("لینک مستقیم بهروزرسانی شد.");
return;
}
if (source === "existing") {
if (!existingId) {
toast.error("دسته‌بندی را انتخاب کنید.");
return;
}
await apiFetch(`/categories/${existingId}`, {
method: "POST",
body: toFormData({ is_deeplink_only: 1 }),
});
toast.success("دسته‌بندی به لینک مستقیم تبدیل شد.");
} else {
const body = toFormData({
name,
type,
order,
description,
icon,
is_deeplink_only: true,
});
await apiFetch("/categories", { method: "POST", body });
toast.success("لینک مستقیم جدید افزوده شد.");
}
setOpen(false);
reload();
} catch (err) {
toast.error(err instanceof ApiError ? err.message : "خطا در ذخیره‌سازی");
} finally {
setSaving(false);
}
}
async function confirmDelete() {
if (!deleting) return;
setRemoving(true);
try {
await apiFetch(`/categories/${deleting.id}`, { method: "DELETE" });
toast.success("دسته‌بندی حذف شد.");
setDeleting(null);
reload();
} catch (err) {
toast.error(err instanceof ApiError ? err.message : "خطا در حذف");
} finally {
setRemoving(false);
}
}
const columns: Column<Category>[] = [
{
key: "icon",
header: "آیکن",
className: "w-20",
render: (r) => (
<MediaPreview kind="image" src={pickUrl(r, ICON_KEYS)} label={r.name} />
),
},
{ key: "name", header: "نام دسته‌بندی" },
{
key: "type",
header: "نوع",
render: (r) =>
r.type === "media"
? "رسانه"
: r.type === "playlist"
? "پلی‌لیست"
: r.type === "breathing_template"
? "قالب تنفس"
: r.type,
className: "w-28",
},
{
key: "deep_link",
header: "لینک مستقیم",
render: (r) =>
r.deep_link ? (
<a
href={r.deep_link}
target="_blank"
rel="noreferrer"
dir="ltr"
className="inline-block max-w-[220px] truncate text-xs text-primary underline"
>
{r.deep_link}
</a>
) : (
<span className="text-xs text-muted">—</span>
),
},
{
key: "subcategories_count",
header: "زیر‌دسته‌ها",
render: (r) => toFa(r.subcategories_count ?? 0),
className: "w-28",
},
];
return (
<div>
<PageHeader
title="لینکهای مستقیم دسته‌بندی"
subtitle="دسته‌بندیهایی که در فهرست نمایش داده نمیشوند اما از طریق لینک مستقیم قابل دسترسیاند"
action={
<Button icon={<PlusIcon className="h-4 w-4" />} onClick={openCreate}>
لینک مستقیم جدید
</Button>
}
/>
<DataTable
columns={columns}
rows={data}
loading={loading}
error={error}
onRetry={reload}
emptyMessage="هنوز لینک مستقیمی تعریف نشده است."
emptyAction={
<Button icon={<PlusIcon className="h-4 w-4" />} onClick={openCreate}>
لینک مستقیم جدید
</Button>
}
actions={(row) => (
<>
<Button
variant="ghost"
onClick={() => toggleHidden(row)}
aria-label="نمایش در فهرست"
>
<EditIcon className="h-4 w-4" />
</Button>
<Button
variant="ghost"
onClick={() => setDeleting(row)}
aria-label="حذف"
className="text-danger"
>
<TrashIcon className="h-4 w-4" />
</Button>
</>
)}
/>
<Modal
open={open}
onClose={() => setOpen(false)}
title="لینک مستقیم دسته‌بندی جدید"
footer={
<>
<Button variant="secondary" onClick={() => setOpen(false)}>
انصراف
</Button>
<Button form="cat-deeplink-form" type="submit" loading={saving}>
ذخیره
</Button>
</>
}
>
<form
id="cat-deeplink-form"
onSubmit={save}
className="flex flex-col gap-4"
>
<Field label="منبع دسته‌بندی" required>
<Select
value={source}
onChange={(e) => setSource(e.target.value as "new" | "existing")}
>
<option value="new">ساخت دسته‌بندی جدید</option>
<option value="existing">استفاده از دسته‌بندی موجود</option>
</Select>
</Field>
{source === "existing" ? (
<Field label="انتخاب دسته‌بندی" required>
{allCategories.length ? (
<Select
value={existingId}
onChange={(e) => setExistingId(e.target.value)}
>
<option value="">انتخاب کنید...</option>
{allCategories.map((c) => (
<option key={c.id} value={String(c.id)}>
{c.name} ({c.type})
</option>
))}
</Select>
) : (
<p className="text-xs text-muted">
{allLoading ? "در حال بارگذاری..." : "دسته‌بندی‌ای موجود نیست."}
</p>
)}
</Field>
) : (
<>
<Field label="نام دسته‌بندی" required>
<Input
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="مثلاً مدیتیشن شبانه"
required
autoFocus
/>
</Field>
<Field label="نوع">
<Select
value={type}
onChange={(e) => setType(e.target.value)}
>
<option value="media">رسانه</option>
<option value="playlist">پلی‌لیست</option>
<option value="breathing_template">قالب تنفس</option>
</Select>
</Field>
<Field label="ترتیب">
<Input
type="number"
dir="ltr"
value={order}
onChange={(e) => setOrder(e.target.value)}
/>
</Field>
<Field label="توضیحات">
<Textarea
value={description}
onChange={(e) => setDescription(e.target.value)}
placeholder="توضیح کوتاه"
/>
</Field>
<Field label="آیکن">
<Input
type="file"
accept="image/*"
onChange={(e) => setIcon(e.target.files?.[0] ?? null)}
/>
</Field>
</>
)}
<p className="rounded-xl border border-border bg-surface-muted p-3 text-xs text-muted">
پس از ذخیره، این دسته‌بندی در فهرست نمایش داده نمیشود و فقط با لینک
مستقیم قابل دسترسی است.
</p>
</form>
</Modal>
<ConfirmDialog
open={!!deleting}
message={`آیا از حذف «${deleting?.name ?? ""}» مطمئن هستید؟`}
loading={removing}
onConfirm={confirmDelete}
onClose={() => setDeleting(null)}
/>
</div>
);
}
+410
View File
@@ -0,0 +1,410 @@
"use client";
import { useState } from "react";
import { apiFetch, ApiError, toFormData } from "@/lib/api";
import { useList } from "@/lib/useResource";
import { useToast } from "@/components/toast";
import { DataTable, type Column } from "@/components/DataTable";
import {
Button,
ConfirmDialog,
Field,
Input,
Modal,
PageHeader,
Select,
Textarea,
Badge,
Switch,
} from "@/components/ui";
import { EditIcon, PlusIcon, TrashIcon } from "@/components/icons";
import { MediaPreview } from "@/components/MediaPreview";
import { ImagePicker } from "@/components/ImagePicker";
import { pickUrl, SOUND_KEYS, VIDEO_KEYS, IMAGE_KEYS } from "@/lib/media";
import { formatMinutes, fileNameToTitle } from "@/lib/utils";
interface Cat {
id: number;
name?: string;
}
interface Media {
id: number;
title?: string;
caption?: string;
type?: string;
duration?: number;
visibility?: string;
is_deeplink_only?: boolean;
is_premium?: boolean;
external_url?: string | null;
deep_link?: string | null;
image_id?: number | null;
image?: unknown;
detail_image_id?: number | null;
detail_image?: unknown;
categories?: Cat[];
sub_categories?: Cat[];
subcategories?: Cat[];
subCategories?: Cat[];
}
function DeepLink({ deep_link }: { deep_link?: string | null }) {
return (
<div>
{deep_link ? (
<a
href={deep_link}
target="_blank"
rel="noreferrer"
dir="ltr"
className="inline-block max-w-[220px] truncate text-xs text-primary underline"
>
{deep_link}
</a>
) : (
<span className="text-xs text-muted">—</span>
)}
</div>
);
}
export default function MediaDeepLinksPage() {
const { data, loading, error, reload } = useList<Media>("/media", {
deeplink_only: 1,
});
const { data: allMedia, loading: allLoading } = useList<Media>("/media", {
count: 500,
});
const toast = useToast();
const [editing, setEditing] = useState<Media | null>(null);
const [open, setOpen] = useState(false);
const [saving, setSaving] = useState(false);
// Source: 'new' (upload / external url) or 'existing' (pick a media record).
const [source, setSource] = useState<"new" | "existing">("new");
const [existingId, setExistingId] = useState<string>("");
// Fields for creating a new hidden media.
const [title, setTitle] = useState("");
const [caption, setCaption] = useState("");
const [type, setType] = useState("audio");
const [duration, setDuration] = useState("");
const [file, setFile] = useState<File | null>(null);
const [externalUrl, setExternalUrl] = useState("");
const [imageId, setImageId] = useState<number | null>(null);
const [imageFile, setImageFile] = useState<File | null>(null);
const [deleting, setDeleting] = useState<Media | null>(null);
const [removing, setRemoving] = useState(false);
function resetForm() {
setSource("new");
setExistingId("");
setTitle("");
setCaption("");
setType("audio");
setDuration("");
setFile(null);
setExternalUrl("");
setImageId(null);
setImageFile(null);
}
function openCreate() {
setEditing(null);
resetForm();
setOpen(true);
}
async function toggleHidden(row: Media) {
try {
await apiFetch(`/media/${row.id}`, {
method: "POST",
body: toFormData({
is_deeplink_only: !row.is_deeplink_only ? 1 : 0,
}),
});
toast.success(
row.is_deeplink_only ? "از لینک مستقیم خارج شد." : "به لینک مستقیم تبدیل شد.",
);
reload();
} catch (err) {
toast.error(err instanceof ApiError ? err.message : "خطا در ذخیره‌سازی");
}
}
async function save(e: React.FormEvent) {
e.preventDefault();
setSaving(true);
try {
if (editing) {
setOpen(false);
reload();
toast.success("لینک مستقیم بهروزرسانی شد.");
return;
}
if (source === "existing") {
// Toggle the chosen existing media to deeplink-only.
if (!existingId) {
toast.error("رسانهای را انتخاب کنید.");
return;
}
await apiFetch(`/media/${existingId}`, {
method: "POST",
body: toFormData({ is_deeplink_only: 1 }),
});
toast.success("رسانه به لینک مستقیم تبدیل شد.");
} else {
// Create a brand new hidden media (upload / external url).
const body = toFormData({
title,
caption,
type,
duration,
file,
external_url: externalUrl,
image_id: imageId,
image: imageFile,
is_deeplink_only: true,
});
await apiFetch("/media", { method: "POST", body });
toast.success("لینک مستقیم جدید افزوده شد.");
}
setOpen(false);
reload();
} catch (err) {
toast.error(err instanceof ApiError ? err.message : "خطا در ذخیره‌سازی");
} finally {
setSaving(false);
}
}
async function confirmDelete() {
if (!deleting) return;
setRemoving(true);
try {
await apiFetch(`/media/${deleting.id}`, { method: "DELETE" });
toast.success("رسانه حذف شد.");
setDeleting(null);
reload();
} catch (err) {
toast.error(err instanceof ApiError ? err.message : "خطا در حذف");
} finally {
setRemoving(false);
}
}
const columns: Column<Media>[] = [
{
key: "play",
header: "پخش",
className: "w-20",
render: (r) =>
r.type === "video" ? (
<MediaPreview kind="video" src={pickUrl(r, VIDEO_KEYS)} label={r.title} />
) : (
<MediaPreview kind="audio" src={pickUrl(r, SOUND_KEYS)} label={r.title} />
),
},
{
key: "thumbnail",
header: "تصویر",
className: "w-20",
render: (r) => (
<MediaPreview kind="image" src={pickUrl(r, IMAGE_KEYS)} label={r.title} />
),
},
{ key: "title", header: "عنوان", render: (r) => r.title ?? "—" },
{
key: "deep_link",
header: "لینک مستقیم",
render: (r) => <DeepLink deep_link={r.deep_link} />,
},
{
key: "duration",
header: "مدت",
render: (r) => formatMinutes(r.duration),
},
];
return (
<div>
<PageHeader
title="لینکهای مستقیم رسانه"
subtitle="رسانههایی که در فهرست نمایش داده نمیشوند اما از طریق لینک مستقیم (دیپلینک) قابل دسترسیاند"
action={
<Button icon={<PlusIcon className="h-4 w-4" />} onClick={openCreate}>
لینک مستقیم جدید
</Button>
}
/>
<DataTable
columns={columns}
rows={data}
loading={loading}
error={error}
onRetry={reload}
emptyMessage="هنوز لینک مستقیمی تعریف نشده است."
emptyAction={
<Button icon={<PlusIcon className="h-4 w-4" />} onClick={openCreate}>
لینک مستقیم جدید
</Button>
}
actions={(row) => (
<>
<Button
variant="ghost"
onClick={() => toggleHidden(row)}
aria-label="نمایش در فهرست"
>
<EditIcon className="h-4 w-4" />
</Button>
<Button
variant="ghost"
onClick={() => setDeleting(row)}
aria-label="حذف"
className="text-danger"
>
<TrashIcon className="h-4 w-4" />
</Button>
</>
)}
/>
<Modal
open={open}
onClose={() => setOpen(false)}
title="لینک مستقیم رسانه جدید"
footer={
<>
<Button variant="secondary" onClick={() => setOpen(false)}>
انصراف
</Button>
<Button form="deeplink-form" type="submit" loading={saving}>
ذخیره
</Button>
</>
}
>
<form
id="deeplink-form"
onSubmit={save}
className="flex flex-col gap-4"
>
<Field label="منبع رسانه" required>
<Select
value={source}
onChange={(e) => setSource(e.target.value as "new" | "existing")}
>
<option value="new">بارگذاری رسانه جدید</option>
<option value="existing">استفاده از رسانه موجود</option>
</Select>
</Field>
{source === "existing" ? (
<Field label="انتخاب رسانه" required>
{allMedia.length ? (
<Select value={existingId} onChange={(e) => setExistingId(e.target.value)}>
<option value="">انتخاب کنید...</option>
{allMedia.map((m) => (
<option key={m.id} value={String(m.id)}>
{m.title ?? `#${m.id}`}
</option>
))}
</Select>
) : (
<p className="text-xs text-muted">
{allLoading ? "در حال بارگذاری..." : "رسانهای موجود نیست."}
</p>
)}
</Field>
) : (
<>
<Field label="عنوان" required>
<Input
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder="مثلاً مدیتیشن شبانه"
required
autoFocus
/>
</Field>
<Field label="توضیحات">
<Textarea
value={caption}
onChange={(e) => setCaption(e.target.value)}
placeholder="توضیح کوتاه"
/>
</Field>
<Field label="تصویر">
<ImagePicker
imageId={imageId}
onPickId={setImageId}
file={imageFile}
onPickFile={setImageFile}
/>
</Field>
<Field label="نوع" required>
<Select value={type} onChange={(e) => setType(e.target.value)} required>
<option value="audio">صوت</option>
<option value="video">ویدیو</option>
</Select>
</Field>
<Field label="فایل" hint="بارگذاری فایل یا وارد کردن لینک خارجی">
<Input
type="file"
accept="audio/*,video/*"
onChange={(e) => {
const f = e.target.files?.[0] ?? null;
setFile(f);
if (f && !title.trim()) setTitle(fileNameToTitle(f.name));
}}
/>
</Field>
<Field label="لینک خارجی" hint="اگر فایل آپلود نمیکنید، آدرس مستقیم فایل.">
<Input
dir="ltr"
value={externalUrl}
onChange={(e) => setExternalUrl(e.target.value)}
placeholder="https://..."
/>
</Field>
<Field label="مدت (دقیقه)">
<Input
type="number"
dir="ltr"
value={duration}
onChange={(e) => setDuration(e.target.value)}
placeholder="مثلاً ۱۰"
/>
</Field>
</>
)}
<p className="rounded-xl border border-border bg-surface-muted p-3 text-xs text-muted">
پس از ذخیره، این رسانه در فهرست «رسانهها» نمایش داده نمیشود و فقط با لینک
مستقیم قابل دسترسی است.
</p>
</form>
</Modal>
<ConfirmDialog
open={!!deleting}
message={`آیا از حذف «${deleting?.title ?? ""}» مطمئن هستید؟`}
loading={removing}
onConfirm={confirmDelete}
onClose={() => setDeleting(null)}
/>
</div>
);
}
+9
View File
@@ -2,6 +2,7 @@ import type { ComponentType, SVGProps } from "react";
import { import {
BreathIcon, BreathIcon,
ChatIcon, ChatIcon,
EyeIcon,
HomeIcon, HomeIcon,
ImageIcon, ImageIcon,
MediaIcon, MediaIcon,
@@ -81,6 +82,14 @@ export const NAV: NavSection[] = [
icon: SliderIcon, icon: SliderIcon,
items: [{ href: "/dashboard/sliders", label: "اسلایدرها" }], items: [{ href: "/dashboard/sliders", label: "اسلایدرها" }],
}, },
{
label: "لینکهای مستقیم",
icon: EyeIcon,
items: [
{ href: "/dashboard/deep-links/media", label: "رسانهها" },
{ href: "/dashboard/deep-links/categories", label: "دستهبندیها" },
],
},
{ {
label: "اعلان‌ها", label: "اعلان‌ها",
icon: SliderIcon, icon: SliderIcon,