Compare commits

...
20 Commits
Author SHA1 Message Date
Amirmahdi 4ac190f161 fix 2026-06-17 19:33:19 +03:30
Amirmahdi 012d928120 feat: add faq 2026-06-17 16:18:28 +03:30
Amirmahdi b1de8cfdc1 feat: add breath colors 2026-06-16 18:50:40 +03:30
Amirmahdi 90e00bc08c feat: add is_premium 2026-06-16 17:19:46 +03:30
Amirmahdi cfcddb55bb feat: add theme 2026-06-14 15:15:03 +03:30
Amirmahdi 034a345521 fix: deploy fixed 2026-06-13 21:06:31 +03:30
Amirmahdi 504b1e2c8e feat: musci category image 2026-06-13 19:21:23 +03:30
Amirmahdi 60a054710a feat: add pagination music 2026-06-12 15:34:19 +03:30
Amirmahdi 1b2d2dec7d feat: add tags 2026-06-12 14:55:49 +03:30
Amirmahdi e374829358 feat: add playlist 2026-06-11 12:00:39 +03:30
Amirmahdi 7c6d16693c feat: update deploy 2026-06-11 10:59:26 +03:30
Amirmahdi 3cc1d1385c feat: add category 2026-06-11 10:28:19 +03:30
Amirmahdi bd71076c72 feat: category type 2026-06-11 09:51:02 +03:30
Amirmahdi 944d3bc00a feat: media & music file name 2026-06-07 21:53:01 +03:30
Amirmahdi 2be0f3e2b8 deploy 2026-06-07 16:04:59 +03:30
Amirmahdi d3089ff2dd feat: add feedback 2026-06-07 15:41:33 +03:30
Amirmahdi 2f976bade1 feat: add media_detail 2026-06-06 20:59:05 +03:30
Amirmahdi ef054280bb feat: add image playlist 2026-06-06 17:22:21 +03:30
Amirmahdi 07cbeec816 feat: add chat topic 2026-06-03 17:08:59 +03:30
Amirmahdi 4d67af0bfc feat: add dark mode 2026-06-03 09:01:42 +03:30
37 changed files with 2235 additions and 134 deletions
+22
View File
@@ -0,0 +1,22 @@
#!/usr/bin/env bash
# Runs on `git push`. If a tag ref is among what's being pushed, build locally
# and deploy to the server. Normal branch pushes are untouched.
set -euo pipefail
deploy=0
tag=""
while read -r local_ref _local_sha _remote_ref _remote_sha; do
case "$local_ref" in
refs/tags/*)
deploy=1
tag="${local_ref#refs/tags/}"
;;
esac
done
if [ "$deploy" = "1" ]; then
echo "→ Tag '$tag' is being pushed — building locally and deploying to the server…"
exec "$(git rev-parse --show-toplevel)/scripts/deploy.sh"
fi
exit 0
+3
View File
@@ -39,3 +39,6 @@ yarn-error.log*
# typescript
*.tsbuildinfo
next-env.d.ts
# local deploy secrets
.env.deploy
+60
View File
@@ -0,0 +1,60 @@
# Deployment
The site is a **static export**. It is built **on your machine** and the result
(`out/`) is copied to the server — nothing is built on the server.
- Server: `185.226.116.88`, user `ubuntu`
- Target dir: `/var/www/aramland-admin` (its contents are fully replaced each deploy)
## Deploy by pushing a git tag (automatic)
A versioned git hook ([`.githooks/pre-push`](.githooks/pre-push)) runs the local
build + upload whenever you push a **tag**:
```bash
git tag v1.0.0
git push origin v1.0.0 # ← hook builds locally, then uploads to the server
```
Normal branch pushes are unaffected — only tag pushes deploy.
> The hook path is set via `git config core.hooksPath .githooks` (already configured
> in this clone). On a fresh clone, run that once.
## Deploy manually (no tag)
```bash
npm run deploy # = bash scripts/deploy.sh : build locally + upload
```
## The password
Both paths use [`scripts/deploy.sh`](scripts/deploy.sh), which streams `out/` over a
single SSH connection. By default **SSH asks for the server password once** per deploy.
To make it **unattended** (no prompt), provide the password without committing it:
1. Create `.env.deploy` in the project root (already gitignored):
```bash
DEPLOY_PASSWORD=your-server-password
```
2. Install `sshpass` (the only piece that can feed a password to SSH non-interactively):
- Linux/WSL: `sudo apt-get install -y sshpass`
- macOS: `brew install hudochenkov/sshpass/sshpass`
- Windows Git Bash has no sshpass — either deploy from WSL, or just answer the one
password prompt.
Override the host/user/path too if needed (env or `.env.deploy`):
`DEPLOY_HOST`, `DEPLOY_USER`, `DEPLOY_PATH`.
> **More robust option:** set up an SSH **key** (`ssh-copy-id ubuntu@185.226.116.88`).
> Then deploys are unattended on any OS with no password or sshpass at all.
## Notes / troubleshooting
- **Permission denied** writing the target: the `ubuntu` user must own it →
on the server run `sudo chown -R ubuntu:ubuntu /var/www/aramland-admin`.
- **Web server:** point nginx's site root at `/var/www/aramland-admin`. The export uses
`trailingSlash: true`, so clean URLs resolve to `…/index.html`.
- The deploy replaces the directory **contents** (including dotfiles) in place; it does
not touch nginx config or sibling folders.
+195
View File
@@ -0,0 +1,195 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import { apiFetch, ApiError } from "@/lib/api";
import { useToast } from "@/components/toast";
import { DataTable, type Column } from "@/components/DataTable";
import { Button, Card, ConfirmDialog, PageHeader } from "@/components/ui";
import { TrashIcon } from "@/components/icons";
import { toFa } from "@/lib/utils";
interface Feedback {
id: number;
stars?: number | null;
content?: string | null;
created_at?: string;
user?: {
name?: string | null;
identifier?: string | null;
mobile?: string | null;
} | null;
}
interface Summary {
total: number;
rated: number;
with_comment: number;
average_stars: number;
}
interface AdminResponse {
summary: Summary;
feedback: { data: Feedback[] };
}
function Stars({ value }: { value?: number | null }) {
if (!value) return <span className="text-muted"></span>;
return (
<span className="text-amber-500" dir="ltr" title={toFa(value)}>
{"★".repeat(value)}
<span className="text-border">{"★".repeat(5 - value)}</span>
</span>
);
}
function userName(u: Feedback["user"]): string {
return u?.name || u?.identifier || u?.mobile || "—";
}
function faDate(value?: string): string {
if (!value) return "—";
try {
return toFa(new Date(value).toLocaleDateString("fa-IR"));
} catch {
return "—";
}
}
export default function AppFeedbackPage() {
const toast = useToast();
const [rows, setRows] = useState<Feedback[]>([]);
const [summary, setSummary] = useState<Summary | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [deleting, setDeleting] = useState<Feedback | null>(null);
const [removing, setRemoving] = useState(false);
// Fetch without touching state synchronously (safe to call from an effect).
const fetchFeedback = useCallback(() => {
return apiFetch<AdminResponse>("/admin/app-feedback")
.then((res) => {
setRows(res.feedback?.data ?? []);
setSummary(res.summary ?? null);
setError(null);
})
.catch((e: unknown) =>
setError(e instanceof ApiError ? e.message : "خطا در دریافت اطلاعات"),
)
.finally(() => setLoading(false));
}, []);
// Reload triggered by user actions (retry / after delete): show the spinner.
const reload = useCallback(() => {
setLoading(true);
setError(null);
fetchFeedback();
}, [fetchFeedback]);
useEffect(() => {
fetchFeedback();
}, [fetchFeedback]);
async function confirmDelete() {
if (!deleting) return;
setRemoving(true);
try {
await apiFetch(`/admin/app-feedback/${deleting.id}`, { method: "DELETE" });
toast.success("بازخورد حذف شد.");
setDeleting(null);
reload();
} catch (err) {
toast.error(err instanceof ApiError ? err.message : "خطا در حذف");
} finally {
setRemoving(false);
}
}
const columns: Column<Feedback>[] = [
{ key: "id", header: "شناسه", render: (r) => toFa(r.id), className: "w-20" },
{ key: "user", header: "کاربر", render: (r) => userName(r.user) },
{
key: "stars",
header: "امتیاز",
className: "w-28",
render: (r) => <Stars value={r.stars} />,
},
{
key: "content",
header: "ایده / نظر",
render: (r) => r.content || <span className="text-muted"></span>,
},
{
key: "created_at",
header: "تاریخ",
className: "w-32",
render: (r) => faDate(r.created_at),
},
];
return (
<div>
<PageHeader
title="نظرات و ایده‌ها"
subtitle="بازخورد کاربران درباره برنامه"
/>
{summary && (
<div className="mb-6 grid grid-cols-2 gap-3 sm:grid-cols-4">
<Card>
<p className="text-sm text-muted">میانگین امتیاز</p>
<p className="mt-1 text-2xl font-bold text-foreground">
{toFa(summary.average_stars)} <span className="text-amber-500"></span>
</p>
</Card>
<Card>
<p className="text-sm text-muted">کل بازخوردها</p>
<p className="mt-1 text-2xl font-bold text-foreground">
{toFa(summary.total)}
</p>
</Card>
<Card>
<p className="text-sm text-muted">دارای امتیاز</p>
<p className="mt-1 text-2xl font-bold text-foreground">
{toFa(summary.rated)}
</p>
</Card>
<Card>
<p className="text-sm text-muted">دارای نظر</p>
<p className="mt-1 text-2xl font-bold text-foreground">
{toFa(summary.with_comment)}
</p>
</Card>
</div>
)}
<DataTable
columns={columns}
rows={rows}
loading={loading}
error={error}
onRetry={reload}
emptyMessage="هنوز بازخوردی ثبت نشده است."
actions={(row) => (
<Button
variant="ghost"
onClick={() => setDeleting(row)}
aria-label="حذف"
className="text-danger"
>
<TrashIcon className="h-4 w-4" />
</Button>
)}
/>
<ConfirmDialog
open={!!deleting}
message={`آیا از حذف بازخورد «${userName(deleting?.user)}» مطمئن هستید؟`}
loading={removing}
onConfirm={confirmDelete}
onClose={() => setDeleting(null)}
/>
</div>
);
}
+293
View File
@@ -0,0 +1,293 @@
"use client";
import { useState } from "react";
import { apiFetch, ApiError } from "@/lib/api";
import { useList } from "@/lib/useResource";
import { useToast } from "@/components/toast";
import { DataTable, type Column } from "@/components/DataTable";
import {
Badge,
Button,
ConfirmDialog,
Field,
Input,
Modal,
PageHeader,
Switch,
} from "@/components/ui";
import { EditIcon, PlusIcon, TrashIcon } from "@/components/icons";
import { toFa } from "@/lib/utils";
interface BreathingColor {
id: number;
name?: string | null;
colors: string[];
order?: number;
is_active?: boolean;
}
function cssColor(c?: string): string {
if (!c) return "transparent";
const hex = c.replace("#", "");
if (hex.length === 8) return `#${hex.slice(2)}${hex.slice(0, 2)}`;
return `#${hex}`;
}
function gradientStyle(colors: string[]): React.CSSProperties {
const cs = (colors.length ? colors : ["#00000000"]).map(cssColor);
if (cs.length === 1) return { background: cs[0] };
return { background: `linear-gradient(135deg, ${cs.join(", ")})` };
}
export default function BreathingColorsPage() {
const { data, loading, error, reload } =
useList<BreathingColor>("/breathing-colors?include_inactive=1");
const toast = useToast();
const [editing, setEditing] = useState<BreathingColor | null>(null);
const [open, setOpen] = useState(false);
const [name, setName] = useState("");
const [order, setOrder] = useState("");
const [isActive, setIsActive] = useState(true);
const [colors, setColors] = useState<string[]>(["#5360FC"]);
const [saving, setSaving] = useState(false);
const [deleting, setDeleting] = useState<BreathingColor | null>(null);
const [removing, setRemoving] = useState(false);
function openCreate() {
setEditing(null);
setName("");
setOrder("");
setIsActive(true);
setColors(["#5360FC"]);
setOpen(true);
}
function openEdit(row: BreathingColor) {
setEditing(row);
setName(row.name ?? "");
setOrder(row.order != null ? String(row.order) : "");
setIsActive(row.is_active ?? true);
setColors(Array.isArray(row.colors) && row.colors.length ? row.colors : ["#5360FC"]);
setOpen(true);
}
async function save(e: React.FormEvent) {
e.preventDefault();
const clean = colors.map((c) => c.trim()).filter(Boolean);
if (!clean.length) {
toast.error("حداقل یک رنگ وارد کنید.");
return;
}
setSaving(true);
try {
const payload = {
name: name || null,
colors: clean,
order: order === "" ? undefined : Number(order),
is_active: isActive,
};
if (editing) {
await apiFetch(`/breathing-colors/${editing.id}`, { method: "PUT", body: payload });
toast.success("رنگ ویرایش شد.");
} else {
await apiFetch("/breathing-colors", { method: "POST", body: payload });
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(`/breathing-colors/${deleting.id}`, { method: "DELETE" });
toast.success("رنگ حذف شد.");
setDeleting(null);
reload();
} catch (err) {
toast.error(err instanceof ApiError ? err.message : "خطا در حذف");
} finally {
setRemoving(false);
}
}
const columns: Column<BreathingColor>[] = [
{ key: "id", header: "شناسه", render: (r) => toFa(r.id), className: "w-20" },
{
key: "preview",
header: "رنگ",
className: "w-24",
render: (r) => (
<span
className="inline-block h-7 w-12 rounded-md border border-border"
style={gradientStyle(r.colors ?? [])}
/>
),
},
{ key: "name", header: "نام", render: (r) => r.name || "—" },
{
key: "codes",
header: "کدها",
render: (r) => (
<span dir="ltr" className="text-xs text-muted">
{(r.colors ?? []).join("، ")}
</span>
),
},
{ key: "order", header: "ترتیب", render: (r) => toFa(r.order ?? 0), className: "w-20" },
{
key: "is_active",
header: "وضعیت",
className: "w-24",
render: (r) =>
r.is_active ? <Badge tone="success">فعال</Badge> : <Badge tone="neutral">غیرفعال</Badge>,
},
];
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={() => openEdit(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={editing ? "ویرایش رنگ" : "رنگ جدید"}
footer={
<>
<Button variant="secondary" onClick={() => setOpen(false)}>
انصراف
</Button>
<Button form="bc-form" type="submit" loading={saving}>
ذخیره
</Button>
</>
}
>
<form id="bc-form" onSubmit={save} className="flex flex-col gap-4">
<Field label="نام">
<Input
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="مثلاً بنفش"
autoFocus
/>
</Field>
<Field label="رنگ‌ها" hint="یک رنگ = تک‌رنگ، چند رنگ = گرادینت.">
<div className="mb-2 flex items-center gap-2">
<span className="text-xs text-muted">پیشنمایش:</span>
<span
className="h-9 w-20 rounded-lg border border-border"
style={gradientStyle(colors)}
/>
</div>
<div className="flex flex-col gap-2">
{colors.map((c, i) => (
<div key={i} className="flex items-center gap-2">
<input
type="color"
value={cssColor(c)}
onChange={(e) =>
setColors((prev) => prev.map((x, j) => (j === i ? e.target.value : x)))
}
className="h-9 w-10 cursor-pointer rounded border border-border bg-transparent"
/>
<Input
value={c}
onChange={(e) =>
setColors((prev) => prev.map((x, j) => (j === i ? e.target.value : x)))
}
placeholder="#RRGGBB"
dir="ltr"
/>
{colors.length > 1 && (
<Button
type="button"
variant="ghost"
className="text-danger"
onClick={() => setColors((prev) => prev.filter((_, j) => j !== i))}
>
</Button>
)}
</div>
))}
<div>
<Button
type="button"
variant="secondary"
onClick={() => setColors((prev) => [...prev, "#5360FC"])}
>
+ افزودن رنگ
</Button>
</div>
</div>
</Field>
<Field label="ترتیب">
<Input
type="number"
value={order}
onChange={(e) => setOrder(e.target.value)}
dir="ltr"
/>
</Field>
<Switch checked={isActive} onChange={setIsActive} label="فعال" />
</form>
</Modal>
<ConfirmDialog
open={!!deleting}
message={`آیا از حذف این رنگ مطمئن هستید؟`}
loading={removing}
onConfirm={confirmDelete}
onClose={() => setDeleting(null)}
/>
</div>
);
}
+82
View File
@@ -26,6 +26,29 @@ interface BreathingTemplate {
duration?: number;
description?: string;
image_id?: number;
breathing_color_id?: number | null;
breathing_color?: BreathingColor | null;
}
interface BreathingColor {
id: number;
name?: string | null;
colors: string[];
}
// "#AARRGGBB" (ARGB) or "#RRGGBB" → a CSS color string.
function cssColor(c?: string): string {
if (!c) return "transparent";
const hex = c.replace("#", "");
if (hex.length === 8) return `#${hex.slice(2)}${hex.slice(0, 2)}`; // ARGB→RGB(drop alpha)
return `#${hex}`;
}
// Linear gradient (or solid) preview for a list of colors.
function gradientStyle(colors: string[]): React.CSSProperties {
const cs = (colors.length ? colors : ["#00000000"]).map(cssColor);
if (cs.length === 1) return { background: cs[0] };
return { background: `linear-gradient(135deg, ${cs.join(", ")})` };
}
interface BreathingForm {
@@ -57,11 +80,13 @@ function numOrUndefined(v: string): number | undefined {
export default function BreathingPage() {
const { data, loading, error, reload } =
useList<BreathingTemplate>("/breathing-templates");
const { data: palette } = useList<BreathingColor>("/breathing-colors");
const toast = useToast();
const [editing, setEditing] = useState<BreathingTemplate | null>(null);
const [open, setOpen] = useState(false);
const [form, setForm] = useState<BreathingForm>(emptyForm);
const [breathingColorId, setBreathingColorId] = useState<number | null>(null);
const [saving, setSaving] = useState(false);
const [deleting, setDeleting] = useState<BreathingTemplate | null>(null);
@@ -74,6 +99,7 @@ export default function BreathingPage() {
function openCreate() {
setEditing(null);
setForm(emptyForm);
setBreathingColorId(null);
setOpen(true);
}
function openEdit(row: BreathingTemplate) {
@@ -87,6 +113,7 @@ export default function BreathingPage() {
description: row.description ?? "",
image_id: row.image_id != null ? String(row.image_id) : "",
});
setBreathingColorId(row.breathing_color_id ?? null);
setOpen(true);
}
@@ -102,6 +129,8 @@ export default function BreathingPage() {
duration: numOrUndefined(form.duration),
description: form.description,
image_id: numOrUndefined(form.image_id),
// Send null (not undefined) so choosing "بدون رنگ" actually clears it.
breathing_color_id: breathingColorId,
};
if (editing) {
// Update is JSON on /breathing-templates/:id
@@ -167,6 +196,21 @@ export default function BreathingPage() {
header: "مدت زمان",
render: (r) => (r.duration != null ? formatDuration(r.duration) : "—"),
},
{
key: "color",
header: "رنگ",
className: "w-20",
render: (r) =>
r.breathing_color?.colors?.length ? (
<span
className="inline-block h-6 w-10 rounded-md border border-border"
style={gradientStyle(r.breathing_color.colors)}
title={r.breathing_color.name ?? ""}
/>
) : (
"—"
),
},
];
return (
@@ -288,6 +332,44 @@ export default function BreathingPage() {
placeholder="توضیح کوتاه درباره قالب"
/>
</Field>
<Field
label="رنگ تمرین"
hint={
palette.length
? "یک رنگ از پالت انتخاب کنید (در «رنگ‌های تنفس» مدیریت می‌شود)."
: "هنوز رنگی در «رنگ‌های تنفس» تعریف نشده است."
}
>
<div className="flex flex-wrap items-center gap-2">
{/* "no color" option */}
<button
type="button"
title="بدون رنگ"
onClick={() => setBreathingColorId(null)}
className={`flex h-9 w-9 items-center justify-center rounded-full border-2 text-muted ${
breathingColorId === null ? "border-primary ring-2 ring-primary/40" : "border-border"
}`}
>
</button>
{palette.map((p) => {
const selected = breathingColorId === p.id;
return (
<button
key={p.id}
type="button"
title={p.name ?? ""}
onClick={() => setBreathingColorId(p.id)}
style={gradientStyle(p.colors)}
className={`h-9 w-9 rounded-full border-2 transition ${
selected ? "border-primary ring-2 ring-primary/40" : "border-border"
}`}
/>
);
})}
</div>
</Field>
</form>
</Modal>
+286
View File
@@ -0,0 +1,286 @@
"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,
Select,
Textarea,
Modal,
PageHeader,
} 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";
type CategoryType = "media" | "playlist" | "breathing_template";
interface Category {
id: number;
name: string;
type: CategoryType;
description?: string | null;
icon?: string | null;
subcategories_count?: number;
}
// General category types, shared across media, playlists and breathing templates.
const TYPE_OPTIONS: { value: CategoryType; label: string }[] = [
{ value: "media", label: "رسانه" },
{ value: "playlist", label: "پلی‌لیست" },
{ value: "breathing_template", label: "قالب تنفس" },
];
const TYPE_LABELS: Record<CategoryType, string> = Object.fromEntries(
TYPE_OPTIONS.map((o) => [o.value, o.label]),
) as Record<CategoryType, string>;
// The icon is a direct image-file field on the category (not an image_id ref).
const ICON_KEYS = ["icon", "icon_url"];
export default function CategoriesPage() {
const [typeFilter, setTypeFilter] = useState<CategoryType>("media");
const { data, loading, error, reload } = useList<Category>("/categories", {
type: typeFilter,
});
const toast = useToast();
const [editing, setEditing] = useState<Category | null>(null);
const [open, setOpen] = useState(false);
const [name, setName] = useState("");
const [type, setType] = useState<CategoryType>("media");
const [description, setDescription] = useState("");
const [icon, setIcon] = useState<File | null>(null);
const [saving, setSaving] = useState(false);
const [deleting, setDeleting] = useState<Category | null>(null);
const [removing, setRemoving] = useState(false);
function openCreate() {
setEditing(null);
setName("");
setType(typeFilter);
setDescription("");
setIcon(null);
setOpen(true);
}
function openEdit(row: Category) {
setEditing(row);
setName(row.name ?? "");
setType(row.type ?? "media");
setDescription(row.description ?? "");
setIcon(null);
setOpen(true);
}
async function save(e: React.FormEvent) {
e.preventDefault();
setSaving(true);
try {
if (editing) {
// Icon is a file, so update goes through POST + Laravel method spoofing.
const body = toFormData({
_method: "PUT",
name,
type,
description,
icon,
});
await apiFetch(`/categories/${editing.id}`, { method: "POST", body });
toast.success("دسته‌بندی ویرایش شد.");
} else {
await apiFetch("/categories", {
method: "POST",
body: toFormData({ name, type, description, icon }),
});
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) => TYPE_LABELS[r.type] ?? r.type,
className: "w-28",
},
{
key: "description",
header: "توضیحات",
render: (r) => r.description || "—",
},
{
key: "subcategories_count",
header: "زیر‌دسته‌ها",
render: (r) => toFa(r.subcategories_count ?? 0),
className: "w-28",
},
];
return (
<div>
<PageHeader
title="دسته‌بندی‌ها"
subtitle="مدیریت دسته‌بندی‌های عمومی رسانه، پلی‌لیست و قالب تنفس"
action={
<div className="flex items-center gap-3">
<Select
value={typeFilter}
onChange={(e) => setTypeFilter(e.target.value as CategoryType)}
aria-label="نوع دسته‌بندی"
className="w-40"
>
{TYPE_OPTIONS.map((o) => (
<option key={o.value} value={o.value}>
{o.label}
</option>
))}
</Select>
<Button icon={<PlusIcon className="h-4 w-4" />} onClick={openCreate}>
دستهبندی جدید
</Button>
</div>
}
/>
<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={() => openEdit(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={editing ? "ویرایش دسته‌بندی" : "دسته‌بندی جدید"}
footer={
<>
<Button variant="secondary" onClick={() => setOpen(false)}>
انصراف
</Button>
<Button form="category-form" type="submit" loading={saving}>
ذخیره
</Button>
</>
}
>
<form id="category-form" onSubmit={save} className="flex flex-col gap-4">
<Field label="نوع" required>
<Select
value={type}
onChange={(e) => setType(e.target.value as CategoryType)}
>
{TYPE_OPTIONS.map((o) => (
<option key={o.value} value={o.value}>
{o.label}
</option>
))}
</Select>
</Field>
<Field label="نام دسته‌بندی" required>
<Input
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="مثلاً کودکان"
required
autoFocus
/>
</Field>
<Field label="توضیحات">
<Textarea
value={description}
onChange={(e) => setDescription(e.target.value)}
placeholder="توضیح کوتاه درباره این دسته‌بندی"
/>
</Field>
<Field
label="آیکن"
hint={
editing
? "در صورت عدم انتخاب، آیکن فعلی حفظ می‌شود."
: "یک تصویر برای نمایش دسته‌بندی انتخاب کنید."
}
>
<Input
type="file"
accept="image/*"
onChange={(e) => setIcon(e.target.files?.[0] ?? null)}
/>
</Field>
</form>
</Modal>
<ConfirmDialog
open={!!deleting}
message={`آیا از حذف «${deleting?.name}» مطمئن هستید؟`}
loading={removing}
onConfirm={confirmDelete}
onClose={() => setDeleting(null)}
/>
</div>
);
}
+238
View File
@@ -0,0 +1,238 @@
"use client";
import { useState } from "react";
import { apiFetch, ApiError } from "@/lib/api";
import { useList } from "@/lib/useResource";
import { useToast } from "@/components/toast";
import { DataTable, type Column } from "@/components/DataTable";
import {
Badge,
Button,
ConfirmDialog,
Field,
Input,
Textarea,
Switch,
Modal,
PageHeader,
} from "@/components/ui";
import { EditIcon, PlusIcon, TrashIcon } from "@/components/icons";
import { toFa } from "@/lib/utils";
interface ChatTopic {
id: number;
title?: string;
description?: string | null;
order?: number | null;
is_active?: boolean;
}
export default function ChatTopicsPage() {
const { data, loading, error, reload } = useList<ChatTopic>("/chat-topics");
const toast = useToast();
const [editing, setEditing] = useState<ChatTopic | null>(null);
const [open, setOpen] = useState(false);
const [saving, setSaving] = useState(false);
const [title, setTitle] = useState("");
const [description, setDescription] = useState("");
const [order, setOrder] = useState("");
const [isActive, setIsActive] = useState(true);
const [deleting, setDeleting] = useState<ChatTopic | null>(null);
const [removing, setRemoving] = useState(false);
function openCreate() {
setEditing(null);
setTitle("");
setDescription("");
setOrder("");
setIsActive(true);
setOpen(true);
}
function openEdit(row: ChatTopic) {
setEditing(row);
setTitle(row.title ?? "");
setDescription(row.description ?? "");
setOrder(row.order != null ? String(row.order) : "");
setIsActive(row.is_active ?? true);
setOpen(true);
}
async function save(e: React.FormEvent) {
e.preventDefault();
setSaving(true);
try {
// chat-topics is a JSON apiResource (no files).
const payload = {
title,
description: description || null,
order: order === "" ? null : Number(order),
is_active: isActive,
};
if (editing) {
await apiFetch(`/chat-topics/${editing.id}`, {
method: "PUT",
body: payload,
});
toast.success("موضوع ویرایش شد.");
} else {
await apiFetch("/chat-topics", { method: "POST", body: payload });
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(`/chat-topics/${deleting.id}`, { method: "DELETE" });
toast.success("موضوع حذف شد.");
setDeleting(null);
reload();
} catch (err) {
toast.error(err instanceof ApiError ? err.message : "خطا در حذف");
} finally {
setRemoving(false);
}
}
const columns: Column<ChatTopic>[] = [
{ key: "id", header: "شناسه", render: (r) => toFa(r.id), className: "w-20" },
{ key: "title", header: "عنوان", render: (r) => r.title ?? "—" },
{
key: "description",
header: "توضیحات",
render: (r) => r.description || "—",
},
{
key: "order",
header: "ترتیب",
render: (r) => toFa(r.order ?? "—"),
className: "w-20",
},
{
key: "is_active",
header: "وضعیت",
render: (r) =>
r.is_active ? (
<Badge tone="success">فعال</Badge>
) : (
<Badge tone="neutral">غیرفعال</Badge>
),
},
];
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={() => openEdit(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={editing ? "ویرایش موضوع" : "موضوع جدید"}
footer={
<>
<Button variant="secondary" onClick={() => setOpen(false)}>
انصراف
</Button>
<Button form="chat-topic-form" type="submit" loading={saving}>
ذخیره
</Button>
</>
}
>
<form id="chat-topic-form" onSubmit={save} className="flex flex-col gap-4">
<Field label="عنوان" required>
<Input
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder="مثلاً هیچ راه واحدی برای مدیتیشن وجود ندارد"
required
autoFocus
/>
</Field>
<Field label="توضیحات">
<Textarea
value={description}
onChange={(e) => setDescription(e.target.value)}
placeholder="توضیح اختیاری درباره موضوع"
/>
</Field>
<Field label="ترتیب">
<Input
type="number"
dir="ltr"
value={order}
onChange={(e) => setOrder(e.target.value)}
placeholder="مثلاً ۱"
/>
</Field>
<Field label="وضعیت">
<Switch
checked={isActive}
onChange={setIsActive}
label={isActive ? "فعال" : "غیرفعال"}
/>
</Field>
</form>
</Modal>
<ConfirmDialog
open={!!deleting}
message={`آیا از حذف «${deleting?.title ?? ""}» مطمئن هستید؟`}
loading={removing}
onConfirm={confirmDelete}
onClose={() => setDeleting(null)}
/>
</div>
);
}
@@ -1,46 +1,59 @@
"use client";
import { useState } from "react";
import { apiFetch, ApiError, toFormData } from "@/lib/api";
import { apiFetch, ApiError } from "@/lib/api";
import { useList } from "@/lib/useResource";
import { useToast } from "@/components/toast";
import { DataTable, type Column } from "@/components/DataTable";
import {
Badge,
Button,
ConfirmDialog,
Field,
Input,
Modal,
PageHeader,
Switch,
} from "@/components/ui";
import { EditIcon, PlusIcon, TrashIcon } from "@/components/icons";
import { toFa } from "@/lib/utils";
interface Category {
interface FaqCategory {
id: number;
name: string;
name?: string;
order?: number;
is_active?: boolean;
faqs_count?: number;
}
export default function MediaCategoriesPage() {
const { data, loading, error, reload } = useList<Category>("/categories");
export default function FaqCategoriesPage() {
const { data, loading, error, reload } = useList<FaqCategory>(
"/faq-categories?include_inactive=1",
);
const toast = useToast();
const [editing, setEditing] = useState<Category | null>(null);
const [editing, setEditing] = useState<FaqCategory | null>(null);
const [open, setOpen] = useState(false);
const [name, setName] = useState("");
const [order, setOrder] = useState("");
const [isActive, setIsActive] = useState(true);
const [saving, setSaving] = useState(false);
const [deleting, setDeleting] = useState<Category | null>(null);
const [deleting, setDeleting] = useState<FaqCategory | null>(null);
const [removing, setRemoving] = useState(false);
function openCreate() {
setEditing(null);
setName("");
setOrder("");
setIsActive(true);
setOpen(true);
}
function openEdit(row: Category) {
function openEdit(row: FaqCategory) {
setEditing(row);
setName(row.name);
setName(row.name ?? "");
setOrder(row.order != null ? String(row.order) : "");
setIsActive(row.is_active ?? true);
setOpen(true);
}
@@ -48,19 +61,16 @@ export default function MediaCategoriesPage() {
e.preventDefault();
setSaving(true);
try {
const body = {
name,
order: order === "" ? undefined : Number(order),
is_active: isActive,
};
if (editing) {
// Update is JSON on /categories/:id
await apiFetch(`/categories/${editing.id}`, {
method: "PUT",
body: { name },
});
await apiFetch(`/faq-categories/${editing.id}`, { method: "PUT", body });
toast.success("دسته‌بندی ویرایش شد.");
} else {
// Create is multipart on /categories
await apiFetch("/categories", {
method: "POST",
body: toFormData({ name }),
});
await apiFetch("/faq-categories", { method: "POST", body });
toast.success("دسته‌بندی افزوده شد.");
}
setOpen(false);
@@ -76,7 +86,7 @@ export default function MediaCategoriesPage() {
if (!deleting) return;
setRemoving(true);
try {
await apiFetch(`/categories/${deleting.id}`, { method: "DELETE" });
await apiFetch(`/faq-categories/${deleting.id}`, { method: "DELETE" });
toast.success("دسته‌بندی حذف شد.");
setDeleting(null);
reload();
@@ -87,16 +97,30 @@ export default function MediaCategoriesPage() {
}
}
const columns: Column<Category>[] = [
{ key: "id", header: "شناسه", render: (r) => toFa(r.id), className: "w-24" },
{ key: "name", header: "نام دسته‌بندی" },
const columns: Column<FaqCategory>[] = [
{ key: "id", header: "شناسه", render: (r) => toFa(r.id), className: "w-20" },
{ key: "name", header: "نام" },
{
key: "faqs_count",
header: "تعداد پرسش",
render: (r) => toFa(r.faqs_count ?? 0),
className: "w-28",
},
{ key: "order", header: "ترتیب", render: (r) => toFa(r.order ?? 0), className: "w-20" },
{
key: "is_active",
header: "وضعیت",
className: "w-24",
render: (r) =>
r.is_active ? <Badge tone="success">فعال</Badge> : <Badge tone="neutral">غیرفعال</Badge>,
},
];
return (
<div>
<PageHeader
title="دسته‌بندی رسانه‌ها"
subtitle="مدیریت دسته‌بندی‌های اصلی محتوای صوتی و تصویری"
title="دسته‌بندی سوالات متداول"
subtitle="مدیریت دسته‌بندی‌های پرسش‌های پرتکرار"
action={
<Button icon={<PlusIcon className="h-4 w-4" />} onClick={openCreate}>
دستهبندی جدید
@@ -110,7 +134,7 @@ export default function MediaCategoriesPage() {
loading={loading}
error={error}
onRetry={reload}
emptyMessage="هنوز دسته‌بندی‌ای ثبت نشده است. اولین دسته‌بندی را بسازید."
emptyMessage="هنوز دسته‌بندی ثبت نشده است."
emptyAction={
<Button icon={<PlusIcon className="h-4 w-4" />} onClick={openCreate}>
دستهبندی جدید
@@ -142,28 +166,37 @@ export default function MediaCategoriesPage() {
<Button variant="secondary" onClick={() => setOpen(false)}>
انصراف
</Button>
<Button form="category-form" type="submit" loading={saving}>
<Button form="faq-cat-form" type="submit" loading={saving}>
ذخیره
</Button>
</>
}
>
<form id="category-form" onSubmit={save}>
<Field label="نام دسته‌بندی" required>
<form id="faq-cat-form" onSubmit={save} className="flex flex-col gap-4">
<Field label="نام" required>
<Input
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="مثلاً کودکان"
placeholder="مثلاً حساب کاربری"
required
autoFocus
/>
</Field>
<Field label="ترتیب">
<Input
type="number"
value={order}
onChange={(e) => setOrder(e.target.value)}
dir="ltr"
/>
</Field>
<Switch checked={isActive} onChange={setIsActive} label="فعال" />
</form>
</Modal>
<ConfirmDialog
open={!!deleting}
message={`آیا از حذف «${deleting?.name}» مطمئن هستید؟`}
message={`آیا از حذف «${deleting?.name ?? ""}» مطمئن هستید؟`}
loading={removing}
onConfirm={confirmDelete}
onClose={() => setDeleting(null)}
+261
View File
@@ -0,0 +1,261 @@
"use client";
import { useMemo, useState } from "react";
import { apiFetch, ApiError } from "@/lib/api";
import { useList } from "@/lib/useResource";
import { useToast } from "@/components/toast";
import { DataTable, type Column } from "@/components/DataTable";
import {
Badge,
Button,
ConfirmDialog,
Field,
Input,
Textarea,
Select,
Modal,
PageHeader,
Switch,
} from "@/components/ui";
import { EditIcon, PlusIcon, TrashIcon } from "@/components/icons";
import { toFa } from "@/lib/utils";
interface Faq {
id: number;
faq_category_id?: number;
question?: string;
answer?: string;
order?: number;
is_active?: boolean;
category_name?: string;
}
interface FaqCategory {
id: number;
name?: string;
faqs?: Faq[];
}
export default function FaqsPage() {
// /faqs returns categories each with their faqs; flatten for the table.
const { data: grouped, loading, error, reload } = useList<FaqCategory>(
"/faqs?include_inactive=1",
);
const { data: categories } = useList<FaqCategory>("/faq-categories?include_inactive=1");
const toast = useToast();
const rows = useMemo<Faq[]>(
() =>
grouped.flatMap((c) =>
(c.faqs ?? []).map((f) => ({ ...f, category_name: c.name })),
),
[grouped],
);
const [editing, setEditing] = useState<Faq | null>(null);
const [open, setOpen] = useState(false);
const [categoryId, setCategoryId] = useState("");
const [question, setQuestion] = useState("");
const [answer, setAnswer] = useState("");
const [order, setOrder] = useState("");
const [isActive, setIsActive] = useState(true);
const [saving, setSaving] = useState(false);
const [deleting, setDeleting] = useState<Faq | null>(null);
const [removing, setRemoving] = useState(false);
function openCreate() {
setEditing(null);
setCategoryId(categories[0] ? String(categories[0].id) : "");
setQuestion("");
setAnswer("");
setOrder("");
setIsActive(true);
setOpen(true);
}
function openEdit(row: Faq) {
setEditing(row);
setCategoryId(row.faq_category_id != null ? String(row.faq_category_id) : "");
setQuestion(row.question ?? "");
setAnswer(row.answer ?? "");
setOrder(row.order != null ? String(row.order) : "");
setIsActive(row.is_active ?? true);
setOpen(true);
}
async function save(e: React.FormEvent) {
e.preventDefault();
if (!categoryId) {
toast.error("دسته‌بندی را انتخاب کنید.");
return;
}
setSaving(true);
try {
const body = {
faq_category_id: Number(categoryId),
question,
answer,
order: order === "" ? undefined : Number(order),
is_active: isActive,
};
if (editing) {
await apiFetch(`/faqs/${editing.id}`, { method: "PUT", body });
toast.success("پرسش ویرایش شد.");
} else {
await apiFetch("/faqs", { 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(`/faqs/${deleting.id}`, { method: "DELETE" });
toast.success("پرسش حذف شد.");
setDeleting(null);
reload();
} catch (err) {
toast.error(err instanceof ApiError ? err.message : "خطا در حذف");
} finally {
setRemoving(false);
}
}
const columns: Column<Faq>[] = [
{ key: "id", header: "شناسه", render: (r) => toFa(r.id), className: "w-20" },
{ key: "category", header: "دسته‌بندی", render: (r) => r.category_name ?? "—" },
{ key: "question", header: "پرسش", render: (r) => r.question ?? "—" },
{
key: "answer",
header: "پاسخ",
render: (r) =>
r.answer ? (
<span className="line-clamp-1 max-w-md text-muted">{r.answer}</span>
) : (
"—"
),
},
{ key: "order", header: "ترتیب", render: (r) => toFa(r.order ?? 0), className: "w-20" },
{
key: "is_active",
header: "وضعیت",
className: "w-24",
render: (r) =>
r.is_active ? <Badge tone="success">فعال</Badge> : <Badge tone="neutral">غیرفعال</Badge>,
},
];
return (
<div>
<PageHeader
title="سوالات متداول"
subtitle="مدیریت پرسش‌ها و پاسخ‌های پرتکرار"
action={
<Button icon={<PlusIcon className="h-4 w-4" />} onClick={openCreate}>
پرسش جدید
</Button>
}
/>
<DataTable
columns={columns}
rows={rows}
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={() => openEdit(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={editing ? "ویرایش پرسش" : "پرسش جدید"}
footer={
<>
<Button variant="secondary" onClick={() => setOpen(false)}>
انصراف
</Button>
<Button form="faq-form" type="submit" loading={saving}>
ذخیره
</Button>
</>
}
>
<form id="faq-form" onSubmit={save} className="flex flex-col gap-4">
<Field label="دسته‌بندی" required>
<Select value={categoryId} onChange={(e) => setCategoryId(e.target.value)}>
<option value=""> انتخاب دستهبندی </option>
{categories.map((c) => (
<option key={c.id} value={c.id}>
{c.name ?? `#${c.id}`}
</option>
))}
</Select>
</Field>
<Field label="پرسش" required>
<Input
value={question}
onChange={(e) => setQuestion(e.target.value)}
placeholder="مثلاً چطور رمز عبورم را تغییر دهم؟"
required
autoFocus
/>
</Field>
<Field label="پاسخ" required>
<Textarea
value={answer}
onChange={(e) => setAnswer(e.target.value)}
placeholder="پاسخ کامل پرسش"
required
/>
</Field>
<Field label="ترتیب">
<Input
type="number"
value={order}
onChange={(e) => setOrder(e.target.value)}
dir="ltr"
/>
</Field>
<Switch checked={isActive} onChange={setIsActive} label="فعال" />
</form>
</Modal>
<ConfirmDialog
open={!!deleting}
message={`آیا از حذف این پرسش مطمئن هستید؟`}
loading={removing}
onConfirm={confirmDelete}
onClose={() => setDeleting(null)}
/>
</div>
);
}
+2
View File
@@ -5,6 +5,7 @@ import { useRouter } from "next/navigation";
import { useAuth } from "@/lib/auth";
import { Sidebar } from "@/components/Sidebar";
import { Spinner, Button } from "@/components/ui";
import { ThemeToggle } from "@/components/ThemeToggle";
import { LogoutIcon, MenuIcon, CloseIcon } from "@/components/icons";
export default function DashboardLayout({
@@ -64,6 +65,7 @@ export default function DashboardLayout({
{mobileOpen ? <CloseIcon /> : <MenuIcon />}
</button>
<div className="flex-1" />
<ThemeToggle />
<Button variant="ghost" icon={<LogoutIcon className="h-4 w-4" />} onClick={onLogout}>
خروج
</Button>
+34 -5
View File
@@ -10,6 +10,7 @@ import {
ConfirmDialog,
Field,
Input,
Textarea,
Select,
Switch,
Modal,
@@ -17,7 +18,7 @@ import {
Badge,
} from "@/components/ui";
import { EditIcon, PlusIcon, TrashIcon } from "@/components/icons";
import { formatMinutes } from "@/lib/utils";
import { formatMinutes, fileNameToTitle } from "@/lib/utils";
import { MediaPreview } from "@/components/MediaPreview";
import { ImagePicker } from "@/components/ImagePicker";
import { pickUrl, SOUND_KEYS, VIDEO_KEYS, IMAGE_KEYS } from "@/lib/media";
@@ -41,6 +42,9 @@ interface Media {
is_premium?: boolean;
external_url?: string | null;
image_id?: number | null;
image?: unknown;
detail_image_id?: number | null;
detail_image?: unknown;
}
// Compact multi-select rendered as toggle chips.
@@ -81,7 +85,9 @@ function ChipMultiSelect({
export default function MediaPage() {
const [search, setSearch] = useState("");
const { data, loading, error, reload } = useList<Media>("/media", { search });
const { data: categories } = useList<Category>("/categories");
const { data: categories } = useList<Category>("/categories", {
type: "media",
});
const { data: subCategories } = useList<Category>("/sub-categories");
const toast = useToast();
@@ -101,6 +107,8 @@ export default function MediaPage() {
const [externalUrl, setExternalUrl] = useState("");
const [imageId, setImageId] = useState<number | null>(null);
const [imageFile, setImageFile] = useState<File | null>(null);
const [detailImageId, setDetailImageId] = useState<number | null>(null);
const [detailImageFile, setDetailImageFile] = useState<File | null>(null);
const [deleting, setDeleting] = useState<Media | null>(null);
const [removing, setRemoving] = useState(false);
@@ -118,6 +126,8 @@ export default function MediaPage() {
setExternalUrl("");
setImageId(null);
setImageFile(null);
setDetailImageId(null);
setDetailImageFile(null);
}
function openCreate() {
@@ -142,6 +152,8 @@ export default function MediaPage() {
setExternalUrl(row.external_url ?? "");
setImageId(row.image_id ?? null);
setImageFile(null);
setDetailImageId(row.detail_image_id ?? null);
setDetailImageFile(null);
setOpen(true);
}
@@ -166,6 +178,8 @@ export default function MediaPage() {
external_url: externalUrl,
image_id: imageId,
image: imageFile,
detail_image_id: detailImageId,
detail_image: detailImageFile,
});
if (editing) {
// File-bearing update: POST /media/:id (multipart, file optional)
@@ -328,14 +342,14 @@ export default function MediaPage() {
</Field>
<Field label="توضیحات">
<Input
<Textarea
value={caption}
onChange={(e) => setCaption(e.target.value)}
placeholder="توضیح کوتاه"
/>
</Field>
<Field label="تصویر شاخص" hint="انتخاب از کتابخانه یا بارگذاری تصویر جدید">
<Field label="تصویر لیست" hint="در فهرست نمایش داده می‌شود">
<ImagePicker
imageId={imageId}
onPickId={setImageId}
@@ -345,6 +359,16 @@ export default function MediaPage() {
/>
</Field>
<Field label="تصویر جزئیات" hint="در صفحه جزئیات نمایش داده می‌شود">
<ImagePicker
imageId={detailImageId}
onPickId={setDetailImageId}
file={detailImageFile}
onPickFile={setDetailImageFile}
existingUrl={editing ? pickUrl(editing, ["detail_image"]) : null}
/>
</Field>
<Field label="دسته‌بندی‌ها">
<ChipMultiSelect
options={categories}
@@ -375,7 +399,12 @@ export default function MediaPage() {
<Input
type="file"
accept="audio/*,video/*"
onChange={(e) => setFile(e.target.files?.[0] ?? null)}
onChange={(e) => {
const f = e.target.files?.[0] ?? null;
setFile(f);
// Fill the title from the file name if still empty.
if (f && !title.trim()) setTitle(fileNameToTitle(f.name));
}}
/>
</Field>
+34 -16
View File
@@ -17,6 +17,9 @@ import {
PageHeader,
} from "@/components/ui";
import { EditIcon, PlusIcon, TrashIcon } from "@/components/icons";
import { ImagePicker } from "@/components/ImagePicker";
import { MediaPreview } from "@/components/MediaPreview";
import { pickUrl, IMAGE_KEYS } from "@/lib/media";
import { toFa } from "@/lib/utils";
interface MusicCategory {
@@ -25,6 +28,8 @@ interface MusicCategory {
description?: string;
order?: number;
is_active?: boolean;
image_id?: number | null;
image?: unknown;
}
export default function MusicCategoriesPage() {
@@ -39,7 +44,8 @@ export default function MusicCategoriesPage() {
const [name, setName] = useState("");
const [description, setDescription] = useState("");
const [order, setOrder] = useState("");
const [imageId, setImageId] = useState("");
const [imageId, setImageId] = useState<number | null>(null);
const [imageFile, setImageFile] = useState<File | null>(null);
const [isActive, setIsActive] = useState(true);
const [deleting, setDeleting] = useState<MusicCategory | null>(null);
@@ -50,7 +56,8 @@ export default function MusicCategoriesPage() {
setName("");
setDescription("");
setOrder("");
setImageId("");
setImageId(null);
setImageFile(null);
setIsActive(true);
setOpen(true);
}
@@ -59,7 +66,8 @@ export default function MusicCategoriesPage() {
setName(row.name ?? "");
setDescription(row.description ?? "");
setOrder(row.order != null ? String(row.order) : "");
setImageId("");
setImageId(row.image_id ?? null);
setImageFile(null);
setIsActive(row.is_active ?? true);
setOpen(true);
}
@@ -69,15 +77,17 @@ export default function MusicCategoriesPage() {
setSaving(true);
try {
if (editing) {
// Update is JSON on /music-categories/:id
// Update is multipart (POST) so an image file can be uploaded.
await apiFetch(`/music-categories/${editing.id}`, {
method: "PUT",
body: {
method: "POST",
body: toFormData({
name,
description,
order: order === "" ? undefined : Number(order),
is_active: isActive,
},
image_id: imageId,
image: imageFile,
}),
});
toast.success("دسته‌بندی ویرایش شد.");
} else {
@@ -88,8 +98,9 @@ export default function MusicCategoriesPage() {
name,
description,
order,
image_id: imageId,
is_active: isActive,
image_id: imageId,
image: imageFile,
}),
});
toast.success("دسته‌بندی افزوده شد.");
@@ -120,6 +131,14 @@ export default function MusicCategoriesPage() {
const columns: Column<MusicCategory>[] = [
{ key: "id", header: "شناسه", render: (r) => toFa(r.id), className: "w-24" },
{
key: "image",
header: "تصویر",
className: "w-20",
render: (r) => (
<MediaPreview kind="image" src={pickUrl(r, IMAGE_KEYS)} label={r.name} />
),
},
{ key: "name", header: "نام" },
{
key: "description",
@@ -223,16 +242,15 @@ export default function MusicCategoriesPage() {
dir="ltr"
/>
</Field>
{!editing && (
<Field label="شناسه تصویر">
<Input
value={imageId}
onChange={(e) => setImageId(e.target.value)}
dir="ltr"
placeholder="image_id"
<Field label="تصویر">
<ImagePicker
imageId={imageId}
onPickId={setImageId}
file={imageFile}
onPickFile={setImageFile}
existingUrl={editing ? pickUrl(editing, IMAGE_KEYS) : null}
/>
</Field>
)}
<Switch checked={isActive} onChange={setIsActive} label="فعال" />
</form>
</Modal>
+61 -3
View File
@@ -15,12 +15,19 @@ import {
PageHeader,
} from "@/components/ui";
import { EditIcon, PlusIcon, TrashIcon } from "@/components/icons";
import { ImagePicker } from "@/components/ImagePicker";
import { MediaPreview } from "@/components/MediaPreview";
import { pickUrl, IMAGE_KEYS } from "@/lib/media";
import { toFa } from "@/lib/utils";
interface Playlist {
id: number;
name?: string;
description?: string;
image_id?: number | null;
image?: unknown;
detail_image_id?: number | null;
detail_image?: unknown;
}
interface MusicCategory {
@@ -42,6 +49,10 @@ export default function MusicPlaylistsPage() {
const [description, setDescription] = useState("");
const [categoryIds, setCategoryIds] = useState<number[]>([]);
const [subcategoryIds, setSubcategoryIds] = useState<number[]>([]);
const [imageId, setImageId] = useState<number | null>(null);
const [imageFile, setImageFile] = useState<File | null>(null);
const [detailImageId, setDetailImageId] = useState<number | null>(null);
const [detailImageFile, setDetailImageFile] = useState<File | null>(null);
const [deleting, setDeleting] = useState<Playlist | null>(null);
const [removing, setRemoving] = useState(false);
@@ -56,6 +67,10 @@ export default function MusicPlaylistsPage() {
setDescription("");
setCategoryIds([]);
setSubcategoryIds([]);
setImageId(null);
setImageFile(null);
setDetailImageId(null);
setDetailImageFile(null);
setOpen(true);
}
function openEdit(row: Playlist) {
@@ -64,6 +79,10 @@ export default function MusicPlaylistsPage() {
setDescription(row.description ?? "");
setCategoryIds([]);
setSubcategoryIds([]);
setImageId(row.image_id ?? null);
setImageFile(null);
setDetailImageId(row.detail_image_id ?? null);
setDetailImageFile(null);
setOpen(true);
}
@@ -72,10 +91,17 @@ export default function MusicPlaylistsPage() {
setSaving(true);
try {
if (editing) {
// Update is JSON on /music-playlists/:id
// Update is multipart (POST) so an image file can be uploaded.
await apiFetch(`/music-playlists/${editing.id}`, {
method: "PUT",
body: { name, description },
method: "POST",
body: toFormData({
name,
description,
image_id: imageId,
image: imageFile,
detail_image_id: detailImageId,
detail_image: detailImageFile,
}),
});
toast.success("پلی‌لیست ویرایش شد.");
} else {
@@ -87,6 +113,10 @@ export default function MusicPlaylistsPage() {
description,
category_ids: categoryIds,
subcategory_ids: subcategoryIds,
image_id: imageId,
image: imageFile,
detail_image_id: detailImageId,
detail_image: detailImageFile,
}),
});
toast.success("پلی‌لیست افزوده شد.");
@@ -117,6 +147,14 @@ export default function MusicPlaylistsPage() {
const columns: Column<Playlist>[] = [
{ key: "id", header: "شناسه", render: (r) => toFa(r.id), className: "w-24" },
{
key: "image",
header: "تصویر",
className: "w-20",
render: (r) => (
<MediaPreview kind="image" src={pickUrl(r, IMAGE_KEYS)} label={r.name} />
),
},
{ key: "name", header: "نام" },
{
key: "description",
@@ -199,6 +237,26 @@ export default function MusicPlaylistsPage() {
/>
</Field>
<Field label="تصویر لیست">
<ImagePicker
imageId={imageId}
onPickId={setImageId}
file={imageFile}
onPickFile={setImageFile}
existingUrl={editing ? pickUrl(editing, IMAGE_KEYS) : null}
/>
</Field>
<Field label="تصویر جزئیات">
<ImagePicker
imageId={detailImageId}
onPickId={setDetailImageId}
file={detailImageFile}
onPickFile={setDetailImageFile}
existingUrl={editing ? pickUrl(editing, ["detail_image"]) : null}
/>
</Field>
{!editing && (
<>
<Field label="دسته‌بندی‌ها">
+64 -9
View File
@@ -2,7 +2,7 @@
import { useState } from "react";
import { apiFetch, ApiError, toFormData } from "@/lib/api";
import { useList } from "@/lib/useResource";
import { useList, usePaginated } from "@/lib/useResource";
import { useToast } from "@/components/toast";
import { DataTable, type Column } from "@/components/DataTable";
import {
@@ -13,13 +13,22 @@ import {
Select,
Modal,
PageHeader,
Pagination,
} from "@/components/ui";
import { EditIcon, PlusIcon, TrashIcon } from "@/components/icons";
import { formatMinutes } from "@/lib/utils";
import { formatMinutes, fileNameToTitle } from "@/lib/utils";
import { MediaPreview } from "@/components/MediaPreview";
import { ImagePicker } from "@/components/ImagePicker";
import { pickUrl, SOUND_KEYS, IMAGE_KEYS } from "@/lib/media";
interface Playlist {
id: number;
name?: string;
// Some endpoints nest the playlist's sub-categories; key casing varies.
subcategories?: Playlist[];
subCategories?: Playlist[];
}
interface Track {
id: number;
title?: string;
@@ -28,15 +37,17 @@ interface Track {
type?: string;
playlist_id?: number;
image_id?: number | null;
}
interface Playlist {
id: number;
name?: string;
// A track belongs to many playlists; the /music row embeds them as an array.
playlists?: Playlist[];
// Sub-categories may also be embedded directly on the track (key casing varies).
subcategories?: Playlist[];
subCategories?: Playlist[];
sub_categories?: Playlist[];
}
export default function MusicTracksPage() {
const { data, loading, error, reload } = useList<Track>("/music");
const { data, meta, page, setPage, loading, error, reload } =
usePaginated<Track>("/music", { perPage: 20 });
const { data: playlists } = useList<Playlist>("/music-playlists");
const toast = useToast();
@@ -56,6 +67,26 @@ export default function MusicTracksPage() {
const [deleting, setDeleting] = useState<Track | null>(null);
const [removing, setRemoving] = useState(false);
// A track belongs to many playlists — list their names.
function playlistName(r: Track): string {
const names = (r.playlists ?? []).map((p) => p.name).filter(Boolean);
return names.length ? (names as string[]).join("، ") : "—";
}
// Sub-categories may sit on the track directly or come through its playlists;
// key casing varies between endpoints, so gather from every shape.
function subCategoryNames(r: Track): string {
const subs: Playlist[] = [
...(r.subcategories ?? r.subCategories ?? r.sub_categories ?? []),
...(r.playlists ?? []).flatMap(
(p) => p.subcategories ?? p.subCategories ?? [],
),
];
const names = subs.map((s) => s.name).filter(Boolean) as string[];
const unique = Array.from(new Set(names));
return unique.length ? unique.join("، ") : "—";
}
function resetForm() {
setTitle("");
setArtist("");
@@ -163,6 +194,16 @@ export default function MusicTracksPage() {
},
{ key: "title", header: "عنوان" },
{ key: "artist", header: "هنرمند", render: (r) => r.artist ?? "—" },
{
key: "playlist",
header: "پلی‌لیست",
render: (r) => playlistName(r),
},
{
key: "subcategory",
header: "زیر‌دسته",
render: (r) => subCategoryNames(r),
},
{
key: "duration",
header: "مدت زمان",
@@ -217,6 +258,15 @@ export default function MusicTracksPage() {
)}
/>
{meta && (
<Pagination
page={page}
lastPage={meta.last_page}
total={meta.total}
onChange={setPage}
/>
)}
<Modal
open={open}
onClose={() => setOpen(false)}
@@ -301,7 +351,12 @@ export default function MusicTracksPage() {
<Input
type="file"
accept="audio/*"
onChange={(e) => setFile(e.target.files?.[0] ?? null)}
onChange={(e) => {
const f = e.target.files?.[0] ?? null;
setFile(f);
// Fill the title from the file name if still empty.
if (f && !title.trim()) setTitle(fileNameToTitle(f.name));
}}
required={!editing}
/>
</Field>
+10 -3
View File
@@ -20,10 +20,17 @@ import { toFa } from "@/lib/utils";
interface Question {
id: number;
title?: string;
category?: string;
// Submitted as a string (name); returned by the API as a related object.
category?: { id?: number; name?: string } | string | null;
tags?: string[] | string;
}
function categoryName(c: Question["category"]): string {
if (!c) return "";
if (typeof c === "string") return c;
return c.name ?? "";
}
function asTags(value: Question["tags"]): string[] {
if (Array.isArray(value)) return value.map((t) => String(t));
if (typeof value === "string" && value.trim() !== "") {
@@ -73,7 +80,7 @@ export default function QuestionsPage() {
function openEdit(row: Question) {
setEditing(row);
setTitle(row.title ?? "");
setCategory(row.category ?? "");
setCategory(categoryName(row.category));
setTagsInput(asTags(row.tags).join("، "));
setOpen(true);
}
@@ -125,7 +132,7 @@ export default function QuestionsPage() {
const columns: Column<Question>[] = [
{ key: "id", header: "شناسه", render: (r) => toFa(r.id), className: "w-20" },
{ key: "title", header: "عنوان", render: (r) => r.title ?? "—" },
{ key: "category", header: "دسته", render: (r) => r.category ?? "—" },
{ key: "category", header: "دسته", render: (r) => categoryName(r.category) || "—" },
{
key: "tags",
header: "برچسب‌ها",
+83
View File
@@ -13,6 +13,7 @@ import {
Input,
Modal,
PageHeader,
Select,
Switch,
} from "@/components/ui";
import { EditIcon, PlusIcon, TrashIcon } from "@/components/icons";
@@ -20,22 +21,62 @@ import { toFa } from "@/lib/utils";
import { MediaPreview } from "@/components/MediaPreview";
import { pickUrl, SOUND_KEYS, VIDEO_KEYS, IMAGE_KEYS } from "@/lib/media";
interface Theme {
id: number;
key: string;
name: string;
colors: Record<string, string>;
}
interface Scene {
id: number;
name: string;
order?: number;
is_active?: boolean;
is_premium?: boolean;
theme_id?: number | null;
theme?: Theme | null;
}
// "#FF156395" (ARGB) or "#156395" → a CSS color the browser understands.
function cssColor(c?: string): string {
if (!c) return "transparent";
const hex = c.replace("#", "");
if (hex.length === 8) return `#${hex.slice(2)}${hex.slice(0, 2)}`; // ARGB → RGBA
return `#${hex}`;
}
function ThemeSwatch({ theme }: { theme?: Theme | null }) {
if (!theme) return <span className="text-muted"></span>;
const keys = ["themeUp", "themeDown", "lightColorGradient", "darkColorGradient"];
return (
<span className="inline-flex items-center gap-2">
<span className="inline-flex overflow-hidden rounded-full border border-border">
{keys.map((k) => (
<span
key={k}
className="h-4 w-4"
style={{ backgroundColor: cssColor(theme.colors?.[k]) }}
/>
))}
</span>
{theme.name}
</span>
);
}
export default function ScenesPage() {
const { data, loading, error, reload } = useList<Scene>("/scenes");
const { data: themes } = useList<Theme>("/themes");
const toast = useToast();
const [editing, setEditing] = useState<Scene | null>(null);
const [open, setOpen] = useState(false);
const [name, setName] = useState("");
const [order, setOrder] = useState("");
const [themeId, setThemeId] = useState("");
const [isActive, setIsActive] = useState(true);
const [isPremium, setIsPremium] = useState(false);
const [image, setImage] = useState<File | null>(null);
const [video, setVideo] = useState<File | null>(null);
const [sound, setSound] = useState<File | null>(null);
@@ -48,7 +89,9 @@ export default function ScenesPage() {
setEditing(null);
setName("");
setOrder("");
setThemeId("");
setIsActive(true);
setIsPremium(false);
setImage(null);
setVideo(null);
setSound(null);
@@ -58,7 +101,9 @@ export default function ScenesPage() {
setEditing(row);
setName(row.name ?? "");
setOrder(row.order != null ? String(row.order) : "");
setThemeId(row.theme_id != null ? String(row.theme_id) : "");
setIsActive(!!row.is_active);
setIsPremium(!!row.is_premium);
setImage(null);
setVideo(null);
setSound(null);
@@ -73,7 +118,9 @@ export default function ScenesPage() {
const body = toFormData({
name,
order,
theme_id: themeId,
is_active: isActive,
is_premium: isPremium,
image,
video,
sound,
@@ -112,6 +159,11 @@ export default function ScenesPage() {
const columns: Column<Scene>[] = [
{ key: "id", header: "شناسه", render: (r) => toFa(r.id), className: "w-24" },
{ key: "name", header: "نام صحنه" },
{
key: "theme",
header: "قالب رنگی",
render: (r) => <ThemeSwatch theme={r.theme} />,
},
{
key: "image",
header: "تصویر",
@@ -153,6 +205,17 @@ export default function ScenesPage() {
),
className: "w-28",
},
{
key: "is_premium",
header: "نوع",
render: (r) =>
r.is_premium ? (
<Badge tone="primary">ویژه</Badge>
) : (
<Badge tone="neutral">رایگان</Badge>
),
className: "w-24",
},
];
return (
@@ -236,8 +299,28 @@ export default function ScenesPage() {
/>
</Field>
<Field label="قالب رنگی">
<Select value={themeId} onChange={(e) => setThemeId(e.target.value)}>
<option value=""> بدون قالب </option>
{themes.map((t) => (
<option key={t.id} value={t.id}>
{t.name}
</option>
))}
</Select>
{themeId && (
<div className="mt-2">
<ThemeSwatch
theme={themes.find((t) => String(t.id) === themeId) ?? null}
/>
</div>
)}
</Field>
<Switch checked={isActive} onChange={setIsActive} label="فعال" />
<Switch checked={isPremium} onChange={setIsPremium} label="ویژه (پولی)" />
<Field
label="تصویر"
hint={editing ? "در صورت عدم انتخاب، تصویر قبلی حفظ می‌شود." : undefined}
@@ -10,6 +10,7 @@ import {
ConfirmDialog,
Field,
Input,
Textarea,
Select,
Modal,
PageHeader,
@@ -25,6 +26,7 @@ interface Category {
interface SubCategory {
id: number;
name?: string;
description?: string | null;
category_id?: number;
category?: { id?: number; name?: string };
}
@@ -39,6 +41,7 @@ export default function SubCategoriesPage() {
const [saving, setSaving] = useState(false);
const [name, setName] = useState("");
const [description, setDescription] = useState("");
const [categoryId, setCategoryId] = useState("");
const [deleting, setDeleting] = useState<SubCategory | null>(null);
@@ -47,6 +50,7 @@ export default function SubCategoriesPage() {
function openCreate() {
setEditing(null);
setName("");
setDescription("");
setCategoryId("");
setOpen(true);
}
@@ -54,6 +58,7 @@ export default function SubCategoriesPage() {
function openEdit(row: SubCategory) {
setEditing(row);
setName(row.name ?? "");
setDescription(row.description ?? "");
setCategoryId(
row.category_id != null
? String(row.category_id)
@@ -72,14 +77,14 @@ export default function SubCategoriesPage() {
// Update is JSON on /sub-categories/:id
await apiFetch(`/sub-categories/${editing.id}`, {
method: "PUT",
body: { name, category_id: categoryId },
body: { name, category_id: categoryId, description },
});
toast.success("زیر‌دسته ویرایش شد.");
} else {
// Create is multipart on /sub-categories
await apiFetch("/sub-categories", {
method: "POST",
body: toFormData({ category_id: categoryId, name }),
body: toFormData({ category_id: categoryId, name, description }),
});
toast.success("زیر‌دسته افزوده شد.");
}
@@ -115,6 +120,11 @@ export default function SubCategoriesPage() {
header: "دسته‌بندی والد",
render: (r) => r.category?.name ?? "—",
},
{
key: "description",
header: "توضیحات",
render: (r) => r.description || "—",
},
];
return (
@@ -202,6 +212,14 @@ export default function SubCategoriesPage() {
autoFocus
/>
</Field>
<Field label="توضیحات">
<Textarea
value={description}
onChange={(e) => setDescription(e.target.value)}
placeholder="توضیح کوتاه درباره این زیر‌دسته"
/>
</Field>
</form>
</Modal>
+48 -13
View File
@@ -20,9 +20,21 @@ import {
import { EditIcon, PlusIcon, TrashIcon } from "@/components/icons";
import { toFa } from "@/lib/utils";
interface SurveyTag {
id: number;
name: string;
}
interface SurveyOption {
id?: number;
label?: string;
tags?: SurveyTag[];
}
// Form-side option: tags edited as a comma-separated string.
interface OptionDraft {
label: string;
tags: string;
}
interface SurveyQuestion {
@@ -54,7 +66,9 @@ export default function SurveysPage() {
const [type, setType] = useState("single");
const [order, setOrder] = useState("0");
const [isActive, setIsActive] = useState(true);
const [options, setOptions] = useState<string[]>([""]);
const [options, setOptions] = useState<OptionDraft[]>([
{ label: "", tags: "" },
]);
const [deleting, setDeleting] = useState<SurveyQuestion | null>(null);
const [removing, setRemoving] = useState(false);
@@ -66,7 +80,7 @@ export default function SurveysPage() {
setType("single");
setOrder("0");
setIsActive(true);
setOptions([""]);
setOptions([{ label: "", tags: "" }]);
setOpen(true);
}
@@ -79,17 +93,22 @@ export default function SurveysPage() {
setIsActive(row.is_active ?? true);
setOptions(
row.options && row.options.length
? row.options.map((o) => o.label ?? "")
: [""],
? row.options.map((o) => ({
label: o.label ?? "",
tags: (o.tags ?? []).map((t) => t.name).join("، "),
}))
: [{ label: "", tags: "" }],
);
setOpen(true);
}
function setOptionAt(index: number, value: string) {
setOptions((prev) => prev.map((o, i) => (i === index ? value : o)));
function setOptionAt(index: number, patch: Partial<OptionDraft>) {
setOptions((prev) =>
prev.map((o, i) => (i === index ? { ...o, ...patch } : o)),
);
}
function addOption() {
setOptions((prev) => [...prev, ""]);
setOptions((prev) => [...prev, { label: "", tags: "" }]);
}
function removeOption(index: number) {
setOptions((prev) =>
@@ -108,9 +127,15 @@ export default function SurveysPage() {
order: Number(order),
is_active: isActive,
options: options
.map((label) => label.trim())
.filter((label) => label !== "")
.map((label) => ({ label })),
.map((o) => ({ label: o.label.trim(), tagsRaw: o.tags }))
.filter((o) => o.label !== "")
.map((o) => ({
label: o.label,
tags: o.tagsRaw
.split(/[,،]/)
.map((t) => t.trim())
.filter((t) => t !== ""),
})),
};
if (editing) {
await apiFetch(`/survey-questions/${editing.id}`, {
@@ -283,12 +308,22 @@ export default function SurveysPage() {
</Button>
</div>
{options.map((opt, i) => (
<div key={i} className="flex items-center gap-2">
<div
key={i}
className="flex items-start gap-2 rounded-lg border border-border p-2"
>
<div className="flex flex-1 flex-col gap-2">
<Input
value={opt}
onChange={(e) => setOptionAt(i, e.target.value)}
value={opt.label}
onChange={(e) => setOptionAt(i, { label: e.target.value })}
placeholder={`گزینه ${toFa(i + 1)}`}
/>
<Input
value={opt.tags}
onChange={(e) => setOptionAt(i, { tags: e.target.value })}
placeholder="برچسب‌ها (با کاما جدا کنید) — برای پیشنهاد محتوا"
/>
</div>
<Button
type="button"
variant="ghost"
+29 -1
View File
@@ -1,10 +1,15 @@
@import "tailwindcss";
/* Enable class-based dark mode (toggle a `.dark` class on <html>). */
@custom-variant dark (&:where(.dark, .dark *));
/* Persian admin theme — calm meditation palette, RTL-first. */
:root {
color-scheme: light;
--background: #f4f6fb;
--surface: #ffffff;
--surface-muted: #eef1f8;
--surface-hover: #e2e6f2;
--foreground: #1f2433;
--muted: #6b7390;
--border: #e1e5f0;
@@ -14,12 +19,34 @@
--danger: #e25b6e;
--success: #2fb583;
--ring: rgba(91, 110, 225, 0.35);
--switch-off: #cdd3e6;
--scroll-thumb: #cdd3e6;
}
.dark {
color-scheme: dark;
--background: #0f1320;
--surface: #181d2e;
--surface-muted: #222840;
--surface-hover: #2c3450;
--foreground: #e7eaf3;
--muted: #97a0bd;
--border: #2c3450;
--primary: #6f7ff0;
--primary-hover: #5f6fe6;
--primary-soft: #232a47;
--danger: #f06b7d;
--success: #3ec79a;
--ring: rgba(111, 127, 240, 0.4);
--switch-off: #3a4566;
--scroll-thumb: #39425f;
}
@theme inline {
--color-background: var(--background);
--color-surface: var(--surface);
--color-surface-muted: var(--surface-muted);
--color-surface-hover: var(--surface-hover);
--color-foreground: var(--foreground);
--color-muted: var(--muted);
--color-border: var(--border);
@@ -45,6 +72,7 @@ body {
color: var(--foreground);
font-family: var(--font-vazir), system-ui, sans-serif;
-webkit-font-smoothing: antialiased;
transition: background-color 0.2s ease, color 0.2s ease;
}
/* Persian digits feel native when the font handles them; keep tabular for tables. */
@@ -58,7 +86,7 @@ table {
height: 10px;
}
::-webkit-scrollbar-thumb {
background: #cdd3e6;
background: var(--scroll-thumb);
border-radius: 999px;
}
::-webkit-scrollbar-track {
+13 -1
View File
@@ -14,13 +14,25 @@ export const metadata: Metadata = {
description: "پنل مدیریت محتوای اپلیکیشن آرام جان",
};
// Runs before paint to set the `.dark` class from saved preference / system,
// avoiding a light flash on load. Kept inline + minimal on purpose.
const noFlashTheme = `(function(){try{var t=localStorage.getItem('aram_theme');if(!t){t=window.matchMedia('(prefers-color-scheme: dark)').matches?'dark':'light';}if(t==='dark'){document.documentElement.classList.add('dark');}}catch(e){}})();`;
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="fa" dir="rtl" className={`${vazir.variable} h-full`}>
<html
lang="fa"
dir="rtl"
className={`${vazir.variable} h-full`}
suppressHydrationWarning
>
<head>
<script dangerouslySetInnerHTML={{ __html: noFlashTheme }} />
</head>
<body className="min-h-full">
<Providers>{children}</Providers>
</body>
+5 -1
View File
@@ -7,6 +7,7 @@ import { useToast } from "@/components/toast";
import { ApiError } from "@/lib/api";
import { Button, Field, Input } from "@/components/ui";
import { Logo } from "@/components/Logo";
import { ThemeToggle } from "@/components/ThemeToggle";
export default function LoginPage() {
const { login, token, ready } = useAuth();
@@ -39,7 +40,10 @@ export default function LoginPage() {
}
return (
<div className="flex min-h-screen items-center justify-center bg-gradient-to-bl from-[#eef1fb] to-[#f6f3fb] p-4">
<div className="relative flex min-h-screen items-center justify-center bg-gradient-to-bl from-[#eef1fb] to-[#f6f3fb] p-4 dark:from-[#11151f] dark:to-[#0d1018]">
<div className="absolute top-4 left-4">
<ThemeToggle />
</div>
<div className="w-full max-w-md rounded-3xl border border-border bg-surface p-8 shadow-lg">
<div className="mb-8 text-center">
<div className="mx-auto mb-4 flex h-20 w-20 items-center justify-center rounded-2xl bg-primary-soft">
+1 -1
View File
@@ -81,7 +81,7 @@ export function ImagePicker({
انتخاب از کتابخانه
</Button>
<label className="inline-flex cursor-pointer items-center justify-center gap-2 rounded-xl border border-border bg-surface-muted px-4 py-2 text-sm font-medium text-foreground transition hover:bg-[#e2e6f2]">
<label className="inline-flex cursor-pointer items-center justify-center gap-2 rounded-xl border border-border bg-surface-muted px-4 py-2 text-sm font-medium text-foreground transition hover:bg-surface-hover">
بارگذاری تصویر
<input
type="file"
+3
View File
@@ -1,12 +1,15 @@
"use client";
import { AuthProvider } from "@/lib/auth";
import { ThemeProvider } from "@/lib/theme";
import { ToastProvider } from "./toast";
export function Providers({ children }: { children: React.ReactNode }) {
return (
<ThemeProvider>
<ToastProvider>
<AuthProvider>{children}</AuthProvider>
</ToastProvider>
</ThemeProvider>
);
}
+21
View File
@@ -0,0 +1,21 @@
"use client";
import { useTheme } from "@/lib/theme";
import { SunIcon, MoonIcon } from "./icons";
export function ThemeToggle({ className }: { className?: string }) {
const { theme, toggle } = useTheme();
const dark = theme === "dark";
return (
<button
type="button"
onClick={toggle}
aria-label={dark ? "حالت روشن" : "حالت تاریک"}
title={dark ? "حالت روشن" : "حالت تاریک"}
className={`rounded-lg p-2 text-muted transition hover:bg-surface-muted hover:text-foreground ${className ?? ""}`}
>
{dark ? <SunIcon className="h-5 w-5" /> : <MoonIcon className="h-5 w-5" />}
</button>
);
}
+20
View File
@@ -70,6 +70,19 @@ export const SearchIcon = (p: IconProps) => (
</svg>
);
export const SunIcon = (p: IconProps) => (
<svg {...base(p)}>
<circle cx="12" cy="12" r="4" />
<path d="M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4" />
</svg>
);
export const MoonIcon = (p: IconProps) => (
<svg {...base(p)}>
<path d="M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8Z" />
</svg>
);
export const LogoutIcon = (p: IconProps) => (
<svg {...base(p)}>
<path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4" />
@@ -170,6 +183,13 @@ export const TrophyIcon = (p: IconProps) => (
<path d="M17 5h3v2a3 3 0 0 1-3 3M7 5H4v2a3 3 0 0 0 3 3" />
</svg>
);
export const ChatIcon = (p: IconProps) => (
<svg {...base(p)}>
<path d="M21 11.5a8.38 8.38 0 0 1-9 8.34 9.5 9.5 0 0 1-3.4-.5L3 21l1.66-4.5A8.38 8.38 0 0 1 4 12a8.5 8.5 0 0 1 9-8.45 8.38 8.38 0 0 1 8 7.95Z" />
<path d="M8.5 12h.01M12 12h.01M15.5 12h.01" />
</svg>
);
export const TagIcon = (p: IconProps) => (
<svg {...base(p)}>
<path d="M3 12V5a2 2 0 0 1 2-2h7l9 9-9 9-9-9Z" />
+1 -1
View File
@@ -53,7 +53,7 @@ export function ToastProvider({ children }: { children: React.ReactNode }) {
"min-w-64 rounded-xl px-4 py-3 text-sm text-white shadow-lg",
t.kind === "success" && "bg-success",
t.kind === "error" && "bg-danger",
t.kind === "info" && "bg-foreground",
t.kind === "info" && "bg-primary",
)}
>
{t.message}
+43 -5
View File
@@ -8,7 +8,7 @@ import {
type TextareaHTMLAttributes,
useEffect,
} from "react";
import { cn } from "@/lib/utils";
import { cn, toFa } from "@/lib/utils";
import { CloseIcon, SpinnerIcon } from "./icons";
/* ------------------------------- Button -------------------------------- */
@@ -22,7 +22,7 @@ interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
const buttonVariants: Record<ButtonVariant, string> = {
primary: "bg-primary text-white hover:bg-primary-hover",
secondary:
"bg-surface-muted text-foreground hover:bg-[#e2e6f2] border border-border",
"bg-surface-muted text-foreground hover:bg-surface-hover border border-border",
danger: "bg-danger text-white hover:opacity-90",
ghost: "text-muted hover:bg-surface-muted",
};
@@ -115,7 +115,7 @@ export function Switch({
<span
className={cn(
"relative h-6 w-11 rounded-full transition",
checked ? "bg-primary" : "bg-[#cdd3e6]",
checked ? "bg-primary" : "bg-[var(--switch-off)]",
)}
>
<span
@@ -182,8 +182,8 @@ export function Badge({
className={cn(
"inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium",
tone === "neutral" && "bg-surface-muted text-muted",
tone === "success" && "bg-[#e3f6ee] text-success",
tone === "danger" && "bg-[#fbe7ea] text-danger",
tone === "success" && "bg-success/15 text-success",
tone === "danger" && "bg-danger/15 text-danger",
tone === "primary" && "bg-primary-soft text-primary",
)}
>
@@ -192,6 +192,44 @@ export function Badge({
);
}
export function Pagination({
page,
lastPage,
total,
onChange,
}: {
page: number;
lastPage: number;
total?: number;
onChange: (p: number) => void;
}) {
if (lastPage <= 1) return null;
return (
<div className="mt-4 flex items-center justify-between gap-3 text-sm">
<span className="text-muted">
{total != null && `${toFa(total)} مورد · `}
صفحه {toFa(page)} از {toFa(lastPage)}
</span>
<div className="flex items-center gap-2">
<Button
variant="secondary"
onClick={() => onChange(page - 1)}
disabled={page <= 1}
>
قبلی
</Button>
<Button
variant="secondary"
onClick={() => onChange(page + 1)}
disabled={page >= lastPage}
>
بعدی
</Button>
</div>
</div>
);
}
export function EmptyState({
title,
message,
+5 -2
View File
@@ -24,8 +24,8 @@ All meditation calls send `Authorization: Bearer <meditationToken>` and `Accept:
- POST `/media/:id` — update (same multipart fields). Playable URL is in **`external_url`**; thumbnail in nested **`image.url`**.
- GET `/media/popular`, `/media/recently-played`, `/media/saved`
- POST `/media/:id/play`, `/media/:id/save`, `/media/:id/note`, `/media/:id/feedback` (stars, content)
- Categories: GET/POST/PUT/DELETE `/categories` (multipart name)
- Sub-categories: GET/POST `/sub-categories`, PUT/DELETE `/sub-categories/:id` (category_id, name)
- Categories: GET `/categories`, POST `/categories` (multipart: name, description, `icon`(image file)), PUT `/categories/:id` (file → POST + `_method=PUT`), DELETE `/categories/:id`. Icon path in `icon`.
- Sub-categories: GET/POST `/sub-categories` (category_id, name, description), PUT/DELETE `/sub-categories/:id` (json: category_id, name, description)
### Track (music)
- Categories: GET `/music-categories/:id`, POST `/music-categories`, PUT/DELETE `/music-categories/:id` (name, description, order, image_id, is_active)
@@ -75,6 +75,9 @@ All meditation calls send `Authorization: Bearer <meditationToken>` and `Accept:
- Saves: POST `/saves/toggle`, `/saves/save`, `/saves/unsave`, `/saves/check` (type, id), GET `/saves/my-saved?type=`
- Ratings: GET/POST/DELETE `/ratings/:type/:id` (stars), GET `/ratings/:type/:id/user`
### Chat topics (موضوعات پیشنهادی گفتگو با مشاور)
- GET `/chat-topics`, GET `/chat-topics/:id`, POST `/chat-topics`, PUT/DELETE `/chat-topics/:id` (json: title, description, order, is_active)
### Misc
- GET `/leader-board`
- GET `/profile`
BIN
View File
Binary file not shown.
+31 -7
View File
@@ -1,6 +1,7 @@
import type { ComponentType, SVGProps } from "react";
import {
BreathIcon,
ChatIcon,
HomeIcon,
ImageIcon,
MediaIcon,
@@ -32,14 +33,18 @@ export const NAV: NavSection[] = [
icon: HomeIcon,
items: [{ href: "/dashboard", label: "خانه" }],
},
{
label: "عمومی",
icon: TagIcon,
items: [
{ href: "/dashboard/categories", label: "دسته‌بندی‌ها" },
{ href: "/dashboard/sub-categories", label: "زیر‌دسته‌ها" },
],
},
{
label: "رسانه‌ها",
icon: MediaIcon,
items: [
{ href: "/dashboard/media", label: "فهرست رسانه‌ها" },
{ href: "/dashboard/media/categories", label: "دسته‌بندی‌ها" },
{ href: "/dashboard/media/sub-categories", label: "زیر‌دسته‌ها" },
],
items: [{ href: "/dashboard/media", label: "فهرست رسانه‌ها" }],
},
{
label: "موسیقی",
@@ -82,7 +87,10 @@ export const NAV: NavSection[] = [
{
label: "تمرین تنفس",
icon: BreathIcon,
items: [{ href: "/dashboard/breathing", label: "قالب‌های تنفس" }],
items: [
{ href: "/dashboard/breathing", label: "قالب‌های تنفس" },
{ href: "/dashboard/breathing/colors", label: "رنگ‌های تنفس" },
],
},
{
label: "پرسش‌ها",
@@ -94,6 +102,11 @@ export const NAV: NavSection[] = [
icon: SurveyIcon,
items: [{ href: "/dashboard/surveys", label: "پرسش‌های نظرسنجی" }],
},
{
label: "گفتگو با مشاور",
icon: ChatIcon,
items: [{ href: "/dashboard/chat-topics", label: "موضوعات پیشنهادی" }],
},
{
label: "حال‌وهوا",
icon: MoodIcon,
@@ -112,6 +125,17 @@ export const NAV: NavSection[] = [
{
label: "محتوای کاربران",
icon: TagIcon,
items: [{ href: "/dashboard/comments", label: "نظرات" }],
items: [
{ href: "/dashboard/comments", label: "نظرات" },
{ href: "/dashboard/app-feedback", label: "نظرات و ایده‌ها برنامه" },
],
},
{
label: "سوالات متداول",
icon: QuestionIcon,
items: [
{ href: "/dashboard/faq", label: "پرسش‌ها" },
{ href: "/dashboard/faq/categories", label: "دسته‌بندی‌ها" },
],
},
];
+66
View File
@@ -0,0 +1,66 @@
"use client";
// Light/dark theme state. The actual `.dark` class is set on <html> by an inline
// script in the root layout (before paint, to avoid a flash) and kept in sync
// here. Preference persists in localStorage.
import {
createContext,
useCallback,
useContext,
useEffect,
useState,
} from "react";
export const THEME_STORAGE_KEY = "aram_theme";
type Theme = "light" | "dark";
interface ThemeApi {
theme: Theme;
toggle: () => void;
setTheme: (t: Theme) => void;
}
const ThemeContext = createContext<ThemeApi | null>(null);
function applyClass(theme: Theme) {
document.documentElement.classList.toggle("dark", theme === "dark");
}
export function ThemeProvider({ children }: { children: React.ReactNode }) {
const [theme, setThemeState] = useState<Theme>("light");
// Read whatever the no-flash script already decided.
useEffect(() => {
const isDark = document.documentElement.classList.contains("dark");
setThemeState(isDark ? "dark" : "light");
}, []);
const setTheme = useCallback((t: Theme) => {
setThemeState(t);
applyClass(t);
try {
window.localStorage.setItem(THEME_STORAGE_KEY, t);
} catch {
/* ignore (private mode) */
}
}, []);
const toggle = useCallback(() => {
setTheme(
document.documentElement.classList.contains("dark") ? "light" : "dark",
);
}, [setTheme]);
return (
<ThemeContext.Provider value={{ theme, toggle, setTheme }}>
{children}
</ThemeContext.Provider>
);
}
export function useTheme(): ThemeApi {
const ctx = useContext(ThemeContext);
if (!ctx) throw new Error("useTheme must be used within <ThemeProvider>");
return ctx;
}
+67
View File
@@ -51,6 +51,73 @@ export function useList<T = unknown>(
return { data, loading, error, reload };
}
export interface PageMeta {
current_page: number;
last_page: number;
per_page: number;
total: number;
}
// Paginated GET-list hook for Laravel paginator responses
// ({ data, current_page, last_page, per_page, total }).
export function usePaginated<T = unknown>(
path: string | null,
options?: { perPage?: number; query?: Query },
): {
data: T[];
meta: PageMeta | null;
page: number;
setPage: (p: number) => void;
loading: boolean;
error: string | null;
reload: () => void;
} {
const perPage = options?.perPage ?? 20;
const query = options?.query;
const [page, setPage] = useState(1);
const [data, setData] = useState<T[]>([]);
const [meta, setMeta] = useState<PageMeta | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const queryKey = JSON.stringify(query ?? {});
const reload = useCallback(() => {
if (!path) {
setData([]);
setMeta(null);
setLoading(false);
setError(null);
return;
}
setLoading(true);
setError(null);
apiFetch(path, { query: { ...query, page, per_page: perPage } })
.then((res) => {
const r = (res ?? {}) as Record<string, unknown>;
const rows = Array.isArray(r.data) ? (r.data as T[]) : [];
setData(rows);
setMeta({
current_page: Number(r.current_page ?? page),
last_page: Number(r.last_page ?? 1),
per_page: Number(r.per_page ?? perPage),
total: Number(r.total ?? rows.length),
});
})
.catch((e: unknown) => {
setError(e instanceof ApiError ? e.message : "خطا در دریافت اطلاعات");
setData([]);
})
.finally(() => setLoading(false));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [path, page, perPage, queryKey]);
useEffect(() => {
reload();
}, [reload]);
return { data, meta, page, setPage, loading, error, reload };
}
// Single-record GET hook.
export function useItem<T = unknown>(path: string | null): {
data: T | null;
+10
View File
@@ -19,6 +19,16 @@ export function formatDuration(seconds?: number | null): string {
return toFa(`${m}:${String(s).padStart(2, "0")}`);
}
// Derive a clean title from an uploaded file name: drop the extension and turn
// underscores/dashes into spaces (e.g. "morning_calm-01.mp3" -> "morning calm 01").
export function fileNameToTitle(name: string): string {
return name
.replace(/\.[^./\\]+$/, "")
.replace(/[_-]+/g, " ")
.replace(/\s+/g, " ")
.trim();
}
// Minutes -> Persian label. Media and music store `duration` in minutes.
export function formatMinutes(minutes?: number | null): string {
if (minutes === null || minutes === undefined) return "—";
+1 -24
View File
@@ -277,30 +277,6 @@
"node": ">=6.9.0"
}
},
"node_modules/@emnapi/core": {
"version": "1.10.0",
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.10.0.tgz",
"integrity": "sha512-yq6OkJ4p82CAfPl0u9mQebQHKPJkY7WrIuk205cTYnYe+k2Z8YBh11FrbRG/H6ihirqcacOgl2BIO8oyMQLeXw==",
"dev": true,
"license": "MIT",
"optional": true,
"peer": true,
"dependencies": {
"@emnapi/wasi-threads": "1.2.1",
"tslib": "^2.4.0"
}
},
"node_modules/@emnapi/runtime": {
"version": "1.10.0",
"resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.10.0.tgz",
"integrity": "sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA==",
"license": "MIT",
"optional": true,
"peer": true,
"dependencies": {
"tslib": "^2.4.0"
}
},
"node_modules/@emnapi/wasi-threads": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.1.tgz",
@@ -3312,6 +3288,7 @@
"integrity": "sha512-whOE1HFo/qJDyX4SnXzP4N6zOWn79WhnCUY/iDR0mPfQZO8wcYE4JClzI2oZrhBnnMUCBCHZhO6VQyoBU95mZA==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@rtsao/scc": "^1.1.0",
"array-includes": "^3.1.9",
+2 -1
View File
@@ -6,7 +6,8 @@
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "eslint"
"lint": "eslint",
"deploy": "bash scripts/deploy.sh"
},
"dependencies": {
"next": "16.2.7",
+49
View File
@@ -0,0 +1,49 @@
#!/usr/bin/env bash
# Build the static site locally, then replace the server directory with it.
#
# - Builds on THIS machine (npm run build -> ./out).
# - Streams out/ over a single SSH connection (tar pipe) and swaps the
# contents of the target dir on the server. No rsync/sshpass required.
#
# Password handling:
# - If `sshpass` is installed AND DEPLOY_PASSWORD is set (env or .env.deploy),
# the deploy is fully unattended.
# - Otherwise SSH prompts for the password once (interactive).
#
# Config (override via env or .env.deploy):
set -euo pipefail
cd "$(git rev-parse --show-toplevel 2>/dev/null || dirname "$(dirname "$0")")"
# Optional local secrets file (gitignored).
[ -f .env.deploy ] && . ./.env.deploy
DEPLOY_HOST="${DEPLOY_HOST:-185.226.116.88}"
DEPLOY_USER="${DEPLOY_USER:-ubuntu}"
DEPLOY_PATH="${DEPLOY_PATH:-/var/www/aramland-admin}"
DEPLOY_PASSWORD="${DEPLOY_PASSWORD:-}"
echo "▸ Building locally (clean)…"
# Remove caches so the production build never type-checks a stale `.next/dev`
# validator (tsconfig includes .next/dev/types) and never ships stale out/ files.
rm -rf .next out
npm run build
if [ ! -d out ]; then
echo "✗ Build did not produce ./out" >&2
exit 1
fi
# Pick the SSH command: unattended with sshpass, else interactive prompt.
ssh_cmd=(ssh -o StrictHostKeyChecking=no "$DEPLOY_USER@$DEPLOY_HOST")
if command -v sshpass >/dev/null 2>&1 && [ -n "$DEPLOY_PASSWORD" ]; then
ssh_cmd=(sshpass -p "$DEPLOY_PASSWORD" "${ssh_cmd[@]}")
else
echo " sshpass/password not available — SSH will prompt for the password."
fi
echo "▸ Uploading to $DEPLOY_USER@$DEPLOY_HOST:$DEPLOY_PATH"
# Replace the directory contents (incl. dotfiles) then extract the new build.
tar -C out -czf - . | "${ssh_cmd[@]}" \
"set -e; mkdir -p '$DEPLOY_PATH'; find '$DEPLOY_PATH' -mindepth 1 -delete; tar -C '$DEPLOY_PATH' -xzf -"
echo "✓ Deployed to $DEPLOY_HOST:$DEPLOY_PATH"