Merge branch 'production' of https://gitea.yaltopia.com/Yimaru/Yimaru-Admin into el-ui

This commit is contained in:
elnatansamuel25 2026-07-10 12:11:00 +03:00
commit 4f3a49da35
12 changed files with 293 additions and 30 deletions

2
.env
View File

@ -1,3 +1,3 @@
VITE_API_BASE_URL=https://api.yimaruacademy.com/api/v1
# VITE_API_BASE_URL=http://localhost:8432/api/v1
VITE_GOOGLE_CLIENT_ID=
VITE_GOOGLE_CLIENT_ID=

View File

@ -2,9 +2,9 @@
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>yimaru-admin</title>
<title>Yimaru Admin</title>
<script>
(function () {
var key = "yimaru-admin-theme";

8
public/favicon.svg Normal file
View File

@ -0,0 +1,8 @@
<svg width="170" height="196" viewBox="0 0 170 196" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M117.067 182.177C115.877 197.212 110.275 195.264 85.2333 195.212C84.4448 195.21 75.1908 196.597 70.8903 191.049C65.6205 184.25 72.0278 153.148 66.6476 148.541C35.4189 121.795 4.51062 115.662 0.0823302 67.1799C-1.67884 47.8957 25.4175 31.9131 23.7554 61.6575C23.719 62.3058 22.9739 65.1635 25.0985 62.8067C29.2141 58.2412 41.0922 63.3382 31.2926 74.5349C28.6322 77.5748 24.8148 77.7486 29.7086 86.6516C31.7965 90.4499 32.1575 90.3838 32.4261 90.1526C41.4869 82.3661 45.6132 74.0124 53.4047 80.4715C54.0587 81.0137 84.7318 107.292 87.455 109.625C94.8854 115.991 95.9815 110.8 108.517 100.555C133.126 80.4434 138.456 71.3292 144.851 76.8954C171.122 99.7616 171.024 101.369 169.414 104.755C166.698 110.466 118.649 145.024 117.265 151.52C117.004 152.747 117.06 155.903 117.067 182.176V182.177Z" fill="#9E2891"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M95.9691 7.04231C107.402 12.0196 133.385 46.145 132.81 49.3317C132.545 50.7992 131.661 50.4639 115.134 43.4362C88.5694 32.1406 77.2952 56.2361 54.3034 49.0066C52.8236 48.5409 50.3187 46.5017 62.8984 31.6198C77.3155 14.5642 81.6895 4.59241 95.9691 7.04231Z" fill="#9E2891"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M104.13 80.7417C101.825 93.3925 78.112 87.9719 81.2646 79.2604C83.4853 73.1244 89.8626 86.8841 97.1122 80.5444C97.7996 79.9435 102.375 73.8938 104.13 80.7417Z" fill="#9E2891"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M67.3682 66.1875C67.5867 65.3843 69.8818 56.9538 76.5731 61.3381C85.3369 67.0807 70.2095 79.6629 67.3682 66.1875Z" fill="#9E2891"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M106.098 66.1791C106.299 65.3769 108.584 56.2798 115.233 61.3404C123.931 67.9593 108.563 79.161 106.098 66.1791Z" fill="#9E2891"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M89.5097 3.27682C89.8473 3.71664 89.8388 3.7058 90.174 4.14097C91.8303 6.28896 92.274 4.5622 94.3639 1.95891C96.0729 -0.16895 96.6436 -0.723371 98.6653 1.09553C100.365 2.62483 99.0602 3.86144 97.4946 5.84759C96.4128 7.21893 96.3423 7.28397 96.4213 7.96074C96.4988 8.62279 96.7775 8.4323 98.8574 9.274C105.076 11.7913 99.5535 16.8431 88.6765 15.9038C82.979 15.4121 79.9885 12.8584 81.4551 10.8831C83.1269 8.63131 86.2172 9.03241 86.4046 7.96926C86.5788 6.97811 85.8719 6.46241 85.0635 5.44804C82.9534 2.79983 82.852 2.17959 84.6577 0.764118C86.7856 -0.903788 87.5932 0.850068 89.5097 3.27682Z" fill="#9E2891"/>
</svg>

After

Width:  |  Height:  |  Size: 2.5 KiB

View File

@ -49,14 +49,23 @@ export function parseSubscriptionPlanMutation(body: unknown): SubscriptionPlan |
return normalizeSubscriptionPlan(body)
}
export const getSubscriptionPlans = () =>
http.get<SubscriptionPlansListResponse | SubscriptionPlan[]>("/subscription-plans").then((res) => {
const plans = parseSubscriptionPlansList(res.data)
return {
...res,
data: plans,
}
})
export interface GetSubscriptionPlansOptions {
/** When false, returns active and inactive plans. Defaults to false for admin views. */
active_only?: boolean
}
export const getSubscriptionPlans = (options?: GetSubscriptionPlansOptions) =>
http
.get<SubscriptionPlansListResponse | SubscriptionPlan[]>("/subscription-plans", {
params: { active_only: options?.active_only ?? false },
})
.then((res) => {
const plans = parseSubscriptionPlansList(res.data)
return {
...res,
data: plans,
}
})
function mutationResult(res: { data: unknown }) {
const plan = parseSubscriptionPlanMutation(res.data)

View File

@ -131,6 +131,11 @@ export function getSeriesPeriodLabel(dateFilter?: DashboardDateFilter): string {
}
}
export function formatPercentRate(rate: number, fractionDigits = 1): string {
if (!Number.isFinite(rate)) return "0%"
return `${(rate * 100).toFixed(fractionDigits)}%`
}
/** Display label for dashboard breakdown rows (regions, enums, free text). */
export function formatAnalyticsLabel(label: string): string {
const text = label?.trim() ?? ""

View File

@ -2,6 +2,7 @@ import type {
SubscriptionPlan,
SubscriptionPlanCategory,
SubscriptionPlanDurationUnit,
UpdateSubscriptionPlanPayload,
} from "../types/subscription.types"
export const SUBSCRIPTION_PLAN_CATEGORIES: {
@ -59,3 +60,19 @@ export function formatPlanCreatedAt(iso: string): string {
day: "numeric",
})
}
export function planToUpdatePayload(
plan: SubscriptionPlan,
overrides?: Partial<UpdateSubscriptionPlanPayload>,
): UpdateSubscriptionPlanPayload {
return {
name: plan.name,
description: plan.description,
duration_value: plan.duration_value,
duration_unit: plan.duration_unit,
price: plan.price,
currency: plan.currency,
is_active: plan.is_active,
...overrides,
}
}

View File

@ -119,7 +119,7 @@ export function DashboardPage() {
const fetchPlans = async () => {
setSubscriptionPlansLoading(true)
try {
const res = await getSubscriptionPlans()
const res = await getSubscriptionPlans({ active_only: false })
setSubscriptionPlans(res.data)
} catch (err) {
console.error(err)

View File

@ -33,6 +33,9 @@ import {
FolderOpen,
RefreshCw,
ChevronDown,
PlayCircle,
RotateCcw,
CheckCircle2,
} from "lucide-react"
import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card"
import { Badge } from "../../components/ui/badge"
@ -46,6 +49,7 @@ import {
formatAnalyticsLabel,
getSubscriptionMetrics,
getVideoLessonsSummary,
formatPercentRate,
} from "../../lib/analytics"
import type { DashboardData, DashboardFilters, LabelCount } from "../../types/analytics.types"
@ -363,7 +367,7 @@ export function AnalyticsPage() {
)
}
const { users, subscriptions, payments, courses, content, notifications, issues, team } = dashboard
const { users, subscriptions, payments, courses, content, notifications, issues, team, videos } = dashboard
const subscriptionMetrics = getSubscriptionMetrics(subscriptions)
const seriesPeriodLabel = getSeriesPeriodLabel(dashboard.date_filter)
const lms = courses.lms
@ -402,6 +406,21 @@ export function AnalyticsPage() {
color: PIE_COLORS[i % PIE_COLORS.length],
}))
const dropOffData =
videos?.drop_off_by_checkpoint.map((d) => ({
checkpoint: `${d.checkpoint_percent}%`,
checkpointPercent: d.checkpoint_percent,
dropOffRate: Number((d.drop_off_rate * 100).toFixed(1)),
viewersReached: d.viewers_reached,
totalSessions: d.total_sessions,
})) ?? []
const retentionData =
videos?.drop_off_by_checkpoint.map((d) => ({
checkpoint: `${d.checkpoint_percent}%`,
viewers: d.viewers_reached,
})) ?? []
const generatedAt = new Date(dashboard.generated_at).toLocaleString("en-US", {
month: "short",
day: "numeric",
@ -880,6 +899,160 @@ export function AnalyticsPage() {
</div>
</Section>
{/* ─── Video Analytics ─── */}
{videos && (
<Section title="Video Analytics" icon={PlayCircle} count={videos.total_watch_sessions} defaultOpen>
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
<KpiCard
icon={PlayCircle}
label="Watch Sessions"
value={formatNumber(videos.total_watch_sessions)}
sub={`${videos.unique_video_starts.toLocaleString()} unique starts`}
trend={videos.total_watch_sessions > 0 ? "up" : "neutral"}
/>
<KpiCard
icon={CheckCircle2}
label="Completion Rate"
value={formatPercentRate(videos.completion_rate)}
sub={`${videos.completed_sessions.toLocaleString()} completed sessions`}
trend={videos.completion_rate >= 0.25 ? "up" : "neutral"}
/>
<KpiCard
icon={RotateCcw}
label="Replay Rate"
value={formatPercentRate(videos.replay_rate)}
sub={`${videos.replay_sessions.toLocaleString()} replays · ${videos.users_who_replayed.toLocaleString()} users`}
trend={videos.replay_rate > 0 ? "up" : "neutral"}
/>
<KpiCard
icon={Video}
label="Unique Starts"
value={formatNumber(videos.unique_video_starts)}
sub={`${videos.completed_sessions.toLocaleString()} completed · ${videos.replay_sessions.toLocaleString()} replays`}
trend="neutral"
/>
</div>
<div className="mt-4 grid gap-4 lg:grid-cols-2">
<Card className="shadow-none">
<CardHeader className="pb-2">
<div className="flex items-center justify-between">
<div>
<CardTitle>Viewer Retention by Checkpoint</CardTitle>
<div className="mt-1 text-xs text-grayScale-400">
Viewers still watching at each progress milestone
</div>
</div>
<Badge variant="secondary">{seriesPeriodLabel}</Badge>
</div>
</CardHeader>
<CardContent className="h-[280px] p-6 pt-2">
{retentionData.length > 0 ? (
<ResponsiveContainer width="100%" height="100%">
<AreaChart data={retentionData} margin={{ left: 8, right: 8, top: 8, bottom: 0 }}>
<defs>
<linearGradient id="gradRetention" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stopColor="#6366F1" stopOpacity={0.25} />
<stop offset="100%" stopColor="#6366F1" stopOpacity={0.02} />
</linearGradient>
</defs>
<CartesianGrid vertical={false} stroke="#E0E0E0" strokeDasharray="4 4" />
<XAxis dataKey="checkpoint" tickLine={false} axisLine={false} fontSize={11} />
<YAxis tickLine={false} axisLine={false} fontSize={11} width={36} allowDecimals={false} />
<Tooltip
formatter={(v) => [Number(v).toLocaleString(), "Viewers"]}
contentStyle={{
borderRadius: 12,
border: "1px solid #E0E0E0",
boxShadow: "0 10px 30px rgba(0,0,0,0.08)",
fontSize: 12,
}}
/>
<Area
type="monotone"
dataKey="viewers"
stroke="#6366F1"
strokeWidth={2}
fill="url(#gradRetention)"
/>
</AreaChart>
</ResponsiveContainer>
) : (
<div className="flex h-full items-center justify-center text-xs text-grayScale-400">
No checkpoint data available
</div>
)}
</CardContent>
</Card>
<Card className="shadow-none">
<CardHeader className="pb-2">
<div className="flex items-center justify-between">
<div>
<CardTitle>Drop-off Rate by Checkpoint</CardTitle>
<div className="mt-1 text-xs text-grayScale-400">
Share of sessions that stopped before each milestone
</div>
</div>
<Badge variant="secondary">{seriesPeriodLabel}</Badge>
</div>
</CardHeader>
<CardContent className="h-[280px] p-6 pt-2">
{dropOffData.length > 0 ? (
<ResponsiveContainer width="100%" height="100%">
<BarChart data={dropOffData} margin={{ left: 8, right: 8, top: 8 }}>
<CartesianGrid vertical={false} stroke="#E0E0E0" strokeDasharray="4 4" />
<XAxis dataKey="checkpoint" tickLine={false} axisLine={false} fontSize={11} />
<YAxis
tickLine={false}
axisLine={false}
fontSize={11}
width={42}
tickFormatter={(v) => `${v}%`}
domain={[0, 100]}
/>
<Tooltip
formatter={(v, _name, props) => {
const row = props?.payload as (typeof dropOffData)[number] | undefined
return [
`${Number(v).toFixed(1)}% drop-off`,
`${row?.viewersReached?.toLocaleString() ?? 0} viewers reached`,
]
}}
contentStyle={{
borderRadius: 12,
border: "1px solid #E0E0E0",
boxShadow: "0 10px 30px rgba(0,0,0,0.08)",
fontSize: 12,
}}
/>
<Bar dataKey="dropOffRate" radius={[6, 6, 0, 0]} fill="#F97316" />
</BarChart>
</ResponsiveContainer>
) : (
<div className="flex h-full items-center justify-center text-xs text-grayScale-400">
No drop-off data available
</div>
)}
</CardContent>
</Card>
</div>
{dropOffData.length > 0 && (
<div className="mt-4">
<BreakdownList
title="Checkpoint Funnel"
data={dropOffData.map((d) => ({
label: `${d.checkpointPercent}% — ${d.viewersReached} viewers (${d.dropOffRate}% drop-off)`,
count: d.viewersReached,
}))}
total={videos.total_watch_sessions}
/>
</div>
)}
</Section>
)}
{/* ─── Team ─── */}
<Section title="Team" icon={UsersRound} count={team.total_members} defaultOpen={false}>
<div className="grid items-start gap-4 sm:grid-cols-2">

View File

@ -12,13 +12,14 @@ import {
Trash2,
} from "lucide-react"
import { toast } from "sonner"
import { getSubscriptionPlans } from "../../api/subscription-plans.api"
import { getSubscriptionPlans, updateSubscriptionPlan } from "../../api/subscription-plans.api"
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel"
import { Badge } from "../../components/ui/badge"
import { Button } from "../../components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card"
import { Input } from "../../components/ui/input"
import { SpinnerIcon } from "../../components/ui/spinner-icon"
import { ToggleSwitch } from "../../components/ui/toggle-switch"
import { countActiveFilters } from "../../lib/adminFilterUtils"
import { cn } from "../../lib/utils"
import {
@ -26,6 +27,7 @@ import {
formatPlanCreatedAt,
formatPlanDuration,
formatPlanPrice,
planToUpdatePayload,
} from "../../lib/subscriptionPlans"
import type { SubscriptionPlan } from "../../types/subscription.types"
import { CreateSubscriptionPlanDialog } from "./components/CreateSubscriptionPlanDialog"
@ -41,12 +43,13 @@ export function SubscriptionPlansTab() {
const [createOpen, setCreateOpen] = useState(false)
const [planToEdit, setPlanToEdit] = useState<SubscriptionPlan | null>(null)
const [planToDelete, setPlanToDelete] = useState<SubscriptionPlan | null>(null)
const [togglingId, setTogglingId] = useState<number | null>(null)
const load = useCallback(async () => {
setLoading(true)
setError(false)
try {
const res = await getSubscriptionPlans()
const res = await getSubscriptionPlans({ active_only: false })
setPlans(res.data)
} catch (e) {
console.error(e)
@ -94,6 +97,28 @@ export function SubscriptionPlansTab() {
setPlans((prev) => prev.filter((p) => p.id !== id))
}
const handleToggleActive = async (plan: SubscriptionPlan) => {
const nextActive = !plan.is_active
setTogglingId(plan.id)
try {
const res = await updateSubscriptionPlan(
plan.id,
planToUpdatePayload(plan, { is_active: nextActive }),
)
const updated = res.data ?? { ...plan, is_active: nextActive }
handleUpdated({
...updated,
category: updated.category || plan.category,
created_at: updated.created_at || plan.created_at,
})
toast.success(`Package ${nextActive ? "activated" : "deactivated"} successfully`)
} catch (err) {
notifyApiError(err, `Failed to ${nextActive ? "activate" : "deactivate"} package`)
} finally {
setTogglingId(null)
}
}
const activeFilterCount = countActiveFilters([
{ value: statusFilter, defaultValue: "all" },
])
@ -261,8 +286,8 @@ export function SubscriptionPlansTab() {
<th className="px-4 py-3">Category</th>
<th className="px-4 py-3">Duration</th>
<th className="px-4 py-3">Price</th>
<th className="px-4 py-3">Status</th>
<th className="px-4 py-3">Created</th>
<th className="px-4 py-3">Status</th>
<th className="px-4 py-3 text-right">Actions</th>
</tr>
</thead>
@ -286,17 +311,20 @@ export function SubscriptionPlansTab() {
<td className="px-4 py-4 font-semibold text-grayScale-900">
{formatPlanPrice(plan)}
</td>
<td className="px-4 py-4">
<Badge variant={plan.is_active ? "success" : "secondary"}>
{plan.is_active ? "Active" : "Inactive"}
</Badge>
</td>
<td className="px-4 py-4 text-grayScale-500">
<span className="inline-flex items-center gap-1.5">
<Calendar className="h-3.5 w-3.5 shrink-0" />
{formatPlanCreatedAt(plan.created_at)}
</span>
</td>
<td className="px-4 py-4">
<ToggleSwitch
checked={plan.is_active}
disabled={togglingId === plan.id}
aria-label={plan.is_active ? `Deactivate ${plan.name}` : `Activate ${plan.name}`}
onCheckedChange={() => void handleToggleActive(plan)}
/>
</td>
<td className="px-4 py-4">
<div className="flex justify-end gap-1">
<Button

View File

@ -114,7 +114,7 @@ export function CreateSubscriptionPlanDialog({
toast.success(res.message || "Subscription plan created successfully")
onCreated(res.data)
onOpenChange(false)
} catch {
} catch (err) {
notifyApiError(err, "Failed to create subscription plan.")
} finally {
setSaving(false)

View File

@ -74,6 +74,13 @@ function draftToPayload(draft: EditDraft): UpdateSubscriptionPlanPayload | null
}
}
function mergePlanWithPayload(
plan: SubscriptionPlan,
payload: UpdateSubscriptionPlanPayload,
): SubscriptionPlan {
return { ...plan, ...payload }
}
type EditSubscriptionPlanDialogProps = {
plan: SubscriptionPlan | null
open: boolean
@ -114,18 +121,15 @@ export function EditSubscriptionPlanDialog({
setSaving(true)
try {
const res = await updateSubscriptionPlan(plan.id, payload)
if (!res.data) {
toast.error("Plan was updated but the response could not be read.")
return
}
const updated = res.data ?? mergePlanWithPayload(plan, payload)
toast.success(res.message || "Subscription plan updated successfully")
onUpdated({
...res.data,
category: res.data.category || plan.category,
created_at: res.data.created_at || plan.created_at,
...updated,
category: updated.category || plan.category,
created_at: updated.created_at || plan.created_at,
})
onOpenChange(false)
} catch {
} catch (err) {
notifyApiError(err, "Failed to update subscription plan.")
} finally {
setSaving(false)

View File

@ -117,6 +117,24 @@ export interface DashboardTeam {
by_status: LabelCount[]
}
export interface VideoDropOffCheckpoint {
checkpoint_percent: number
total_sessions: number
viewers_reached: number
drop_off_rate: number
}
export interface DashboardVideos {
total_watch_sessions: number
completed_sessions: number
replay_sessions: number
unique_video_starts: number
users_who_replayed: number
completion_rate: number
replay_rate: number
drop_off_by_checkpoint: VideoDropOffCheckpoint[]
}
export type DashboardDateFilterMode = "all_time" | "year" | "year_month" | "custom"
export interface DashboardDateFilter {
@ -153,6 +171,7 @@ export interface DashboardData {
notifications: DashboardNotifications
issues: DashboardIssues
team: DashboardTeam
videos?: DashboardVideos
}
export interface DashboardResponse {