Integrate course pricing and affiliate management in admin panel

This commit is contained in:
Yared Yemane 2026-11-20 22:39:15 +03:00
parent 66028a434b
commit 3668967ac4
15 changed files with 254 additions and 23 deletions

View File

@ -477,3 +477,14 @@ For any new frontend module, follow this contract:
This keeps integration robust even with mixed legacy/unified backend surfaces. This keeps integration robust even with mixed legacy/unified backend surfaces.
## Course purchases and access defaults
The active `/new-content/courses` editor manages `price` and `currency` on courses only. Prices are nonnegative with up to two decimal places; currency defaults to ETB. A positive price enables one-time purchase of the course's premium content. Zero-price drafts may be saved, but their premium content cannot be purchased until a positive price is configured. Free courses may contain explicitly premium chapters/lessons covered by the course price.
New courses default to PREMIUM. New chapters/lessons default to INHERIT, following their parent's effective access. Editors can override either child with FREE or PREMIUM and restore INHERIT later. Course cards display pricing; child cards distinguish inherited access from explicit overrides. Pricing fields are never sent in chapter/lesson payloads.
Payment records retain `course_id` and identify course purchases separately from historical subscription payments. Legacy subscription records remain visible and cancellable; grant and extension controls are disabled because subscriptions no longer unlock courses. Existing active subscribers must purchase courses after the switch.
Requires backend migration `000008_course_purchases`. This panel configures prices; learner checkout uses the backend's course checkout endpoint in the learner clients.

View File

@ -214,3 +214,72 @@ test("retired Audio Conversation is excluded while historical reads remain avail
assert.equal(result.total_count,1) assert.equal(result.total_count,1)
assert.equal((await api.getQuestionTypeDefinitionById(10)).key,"audio_conversation_type") assert.equal((await api.getQuestionTypeDefinitionById(10)).key,"audio_conversation_type")
}) })
test("course prices and child overrides survive editing without unrelated fields", async () => {
const forms = await loadModule("src/lib/learningContentForm.ts")
const course = forms.learningContentForm("course", { id: 3, name: "Bridal", price: 1500.25, currency: "ETB", access_tier: "PREMIUM" })
assert.equal(course.price, "1500.25")
assert.deepEqual(forms.learningContentPayload("course", course), { name: "Bridal", description: "", thumbnail: "", access_tier: "PREMIUM", price: 1500.25, currency: "ETB" })
assert.equal(forms.learningContentForm("course").access_tier, "PREMIUM")
for (const kind of ["chapter", "lesson"]) {
const child = forms.learningContentForm(kind)
assert.equal(child.access_tier, "INHERIT")
child.name = "Preview"
child.access_tier = "FREE"
const payload = forms.learningContentPayload(kind, child)
assert.equal(payload.access_tier, "FREE")
assert.equal("price" in payload, false)
assert.equal("currency" in payload, false)
assert.equal("video_url" in payload, kind === "lesson")
assert.equal(forms.learningContentForm(kind, { id: 4, access_tier: "PREMIUM" }).access_tier, "PREMIUM")
}
assert.equal(forms.effectiveLearningAccess({ access_tier: "FREE" }, "PREMIUM"), "FREE")
assert.equal(forms.effectiveLearningAccess({ access_tier: "INHERIT" }, "FREE"), "FREE")
assert.equal(forms.effectiveLearningAccess({ access_tier: "INHERIT" }, "PREMIUM"), "PREMIUM")
})
test("course pricing rejects invalid amounts and normalizes currency", async () => {
const forms = await loadModule("src/lib/learningContentForm.ts")
const base = forms.learningContentForm("course")
for (const price of ["", "-1", "1.001", "NaN", "Infinity", "10000000000"]) {
assert.throws(() => forms.learningContentPayload("course", { ...base, price }))
}
assert.throws(() => forms.learningContentPayload("course", { ...base, currency: "12!" }))
assert.throws(() => forms.learningContentPayload("course", { ...base, access_tier: "INHERIT" }))
assert.equal(forms.learningContentPayload("course", { ...base, price: "0", currency: " etb " }).currency, "ETB")
})
test("payment records preserve course scope and legacy plan labels", async () => {
const api = await loadModule("src/api/payments.api.ts")
const format = await loadModule("src/lib/payments.ts")
const records = api.parsePaymentsList({ data: { payments: [
{ id: 1, course_id: 12, amount: 1500, currency: "ETB" },
{ id: 2, plan_id: 3, plan_name: "Historical pass", subscription_id: 8 },
] } }).payments
assert.equal(records[0].course_id, 12)
assert.equal(format.paymentContentLabel(records[0]), "Course #12")
assert.equal(records[1].course_id, undefined)
assert.equal(format.paymentContentLabel(records[1]), "Historical pass")
assert.equal(format.paymentContentLabel({ plan_id: 0, plan_name: "" }), "Unassigned")
})
test("affiliate admin requests use course ledger endpoints and preserve review notes", async () => {
const calls=[]
const api=await loadModule("src/api/affiliates.api.ts",{
get:async(path,options)=>{calls.push([path,options]);return {data:{data:{items:[],total_count:0}}}},
put:async(path,body)=>{calls.push([path,body]);return {data:{data:body}}},
post:async(path,body)=>{calls.push([path,body]);return {data:{data:body}}},
})
await api.listAffiliates(20,"PENDING")
await api.reviewAffiliate(42,"APPROVED","Verified artist")
await api.reviewAffiliatePayout(8,"PAID","Transferred externally","BANK-123")
await api.reverseAffiliateCommission(7,"Course payment refunded")
assert.deepEqual(calls,[
["/affiliates",{params:{limit:20,offset:20,status:"PENDING"}}],
["/affiliates/42/review",{status:"APPROVED",note:"Verified artist"}],
["/affiliates/payouts/8/review",{status:"PAID",note:"Transferred externally",payment_reference:"BANK-123"}],
["/affiliates/commissions/7/reverse",{reason:"Course payment refunded"}],
])
})

16
src/api/affiliates.api.ts Normal file
View File

@ -0,0 +1,16 @@
import http from "./http"
export type AffiliateProfile = { user_id:number; status:string; application:string; email:string; first_name:string; last_name:string; code:string; review_note:string }
export type AffiliateSettings = { commission_percent:string; commission_mode:"FIRST_PURCHASE"|"EVERY_COURSE"; attribution_days:number; holding_days:number; share_base_url:string }
export type AffiliateCommission = { id:number; referrer_id:number; course_id:number|null; payment_id:number; amount:string; currency:string; status:string; available_at:string; reversal_reason:string|null }
export type AffiliatePayout = { id:number; user_id:number; amount:string; currency:string; status:string; method:string; account_name:string; account_reference:string; payment_reference:string|null; review_note:string }
export type AffiliateEvent = { id:number; affiliate_user_id:number|null; actor_id:number|null; event:string; details:Record<string,unknown>; created_at:string }
export type AffiliatePage<T> = { items:T[]; total_count?:number; limit:number; offset:number }
export async function listAffiliates(offset=0,status=""){return (await http.get<{data:AffiliatePage<AffiliateProfile>}>("/affiliates",{params:{limit:20,offset,status}})).data.data}
export async function affiliateSettings(){return (await http.get<{data:AffiliateSettings}>("/affiliates/settings")).data.data}
export async function saveAffiliateSettings(input:Omit<AffiliateSettings,"commission_percent"> & {commission_percent:number}){return (await http.put<{data:AffiliateSettings}>("/affiliates/settings",input)).data.data}
export async function affiliateCommissions(offset=0,user_id?:number){return (await http.get<{data:AffiliatePage<AffiliateCommission>}>("/affiliates/commissions",{params:{limit:20,offset,user_id}})).data.data}
export async function affiliatePayouts(offset=0,status="",user_id?:number){return (await http.get<{data:AffiliatePage<AffiliatePayout>}>("/affiliates/payouts",{params:{limit:20,offset,status,user_id}})).data.data}
export async function affiliateEvents(offset=0){return (await http.get<{data:AffiliatePage<AffiliateEvent>}>("/affiliates/events",{params:{limit:20,offset}})).data.data}
export function reviewAffiliate(id:number,status:string,note:string){return http.put(`/affiliates/${id}/review`,{status,note})}
export function reviewAffiliatePayout(id:number,status:string,note:string,payment_reference:string){return http.put(`/affiliates/payouts/${id}/review`,{status,note,payment_reference})}
export function reverseAffiliateCommission(id:number,reason:string){return http.post(`/affiliates/commissions/${id}/reverse`,{reason})}

View File

@ -13,7 +13,10 @@ export type LearningItem = {
thumbnail?: string thumbnail?: string
video_url?: string video_url?: string
publish_status: "DRAFT" | "PUBLISHED" publish_status: "DRAFT" | "PUBLISHED"
access_tier?: "FREE" | "PREMIUM" access_tier?: "FREE" | "PREMIUM" | "INHERIT"
effective_access_tier?: "FREE" | "PREMIUM"
price?: number
currency?: string
question_set_id?: number question_set_id?: number
} }

View File

@ -17,6 +17,7 @@ function normalizePayment(raw: unknown): Payment | null {
return { return {
id, id,
user_id: Number(raw.user_id ?? 0), user_id: Number(raw.user_id ?? 0),
course_id: Number.isSafeInteger(Number(raw.course_id)) && Number(raw.course_id) > 0 ? Number(raw.course_id) : undefined,
plan_id: Number(raw.plan_id ?? 0), plan_id: Number(raw.plan_id ?? 0),
subscription_id: Number(raw.subscription_id ?? 0), subscription_id: Number(raw.subscription_id ?? 0),
session_id: String(raw.session_id ?? ""), session_id: String(raw.session_id ?? ""),

View File

@ -1,3 +1,4 @@
import { AffiliatesPage } from "../pages/affiliates/AffiliatesPage";
import { getAccessToken } from "../lib/teamAuthStorage"; import { getAccessToken } from "../lib/teamAuthStorage";
import { Navigate, Route, Routes } from "react-router-dom"; import { Navigate, Route, Routes } from "react-router-dom";
import { LearningHierarchyPage } from "../pages/content-management/LearningHierarchyPage"; import { LearningHierarchyPage } from "../pages/content-management/LearningHierarchyPage";
@ -125,6 +126,7 @@ export function AppRoutes() {
/> />
<Route path="/notifications/all" element={<AllNotificationsPage />} /> <Route path="/notifications/all" element={<AllNotificationsPage />} />
<Route path="/payments" element={<PaymentsPage />} /> <Route path="/payments" element={<PaymentsPage />} />
<Route path="/affiliates" element={<AffiliatesPage />} />
<Route path="/subscriptions/export" element={<SubscriptionsExportPage />} /> <Route path="/subscriptions/export" element={<SubscriptionsExportPage />} />
<Route path="/user-log" element={<UserLogPage />} /> <Route path="/user-log" element={<UserLogPage />} />
<Route path="/app-reviews" element={<AppReviewsPage />} /> <Route path="/app-reviews" element={<AppReviewsPage />} />

View File

@ -107,6 +107,7 @@ const navEntries: NavEntry[] = [
}, },
{ kind: "section", label: "Operations" }, { kind: "section", label: "Operations" },
{ kind: "link", label: "Affiliates", to: "/affiliates", icon: UsersRound },
{ kind: "link", label: "Payments", to: "/payments", icon: CreditCard }, { kind: "link", label: "Payments", to: "/payments", icon: CreditCard },
{ {
kind: "link", kind: "link",

View File

@ -0,0 +1,40 @@
import type { LearningItem, LearningKind } from "../api/learningHierarchy.api"
export type AccessTier = "FREE" | "PREMIUM" | "INHERIT"
export type ContentForm = {
name: string; description: string; thumbnail: string; video_url: string
access_tier: AccessTier; price: string; currency: string
}
export function learningContentForm(kind: LearningKind, item?: LearningItem): ContentForm {
return {
name: item?.name ?? item?.title ?? "", description: item?.description ?? "",
thumbnail: item?.thumbnail ?? "", video_url: item?.video_url ?? "",
access_tier: item?.access_tier ?? (kind === "course" ? "PREMIUM" : "INHERIT"),
price: String(item?.price ?? 0), currency: item?.currency ?? "ETB",
}
}
export function learningContentPayload(kind: Exclude<LearningKind, "quiz">, form: ContentForm) {
const common = { description: form.description, thumbnail: form.thumbnail, access_tier: form.access_tier }
if (kind === "lesson") return { ...common, title: form.name.trim(), video_url: form.video_url }
if (kind === "chapter") return { ...common, name: form.name.trim() }
if (form.access_tier === "INHERIT") throw new Error("Choose Free or Premium for the course.")
const price = Number(form.price)
if (!/^\d+(?:\.\d{1,2})?$/.test(form.price) || !Number.isFinite(price) || price > 9999999999.99) {
throw new Error("Enter a nonnegative course price with at most two decimal places.")
}
const currency = form.currency.trim().toUpperCase()
if (!/^[A-Z]{3}$/.test(currency)) throw new Error("Enter a three-letter currency code, such as ETB.")
return { ...common, name: form.name.trim(), price, currency }
}
export function effectiveLearningAccess(item: LearningItem | null | undefined, parent: "FREE" | "PREMIUM" = "PREMIUM"): "FREE" | "PREMIUM" {
if (item?.effective_access_tier) return item.effective_access_tier
return item?.access_tier && item.access_tier !== "INHERIT" ? item.access_tier : parent
}
export function coursePriceLabel(item: LearningItem): string {
const price = Number(item.price ?? 0)
return price > 0 ? `${price.toLocaleString(undefined, { maximumFractionDigits: 2 })} ${item.currency || "ETB"} - one-time purchase` : "No purchase price configured"
}

View File

@ -101,3 +101,8 @@ export function computePaymentAggregateStats(payments: Payment[]): PaymentAggreg
return { successfulCount, totalRevenue, pendingCount } return { successfulCount, totalRevenue, pendingCount }
} }
export function paymentContentLabel(payment: Pick<Payment, "course_id" | "plan_id" | "plan_name">): string {
if (payment.course_id) return `Course #${payment.course_id}`
return payment.plan_name || (payment.plan_id ? `Legacy plan #${payment.plan_id}` : "Unassigned")
}

View File

@ -0,0 +1,73 @@
import { useCallback, useEffect, useRef, useState, type FormEvent } from "react"
import { Link } from "react-router-dom"
import { toast } from "sonner"
import { Button } from "../../components/ui/button"
import { Input } from "../../components/ui/input"
import { Textarea } from "../../components/ui/textarea"
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "../../components/ui/dialog"
import { notifyApiError } from "../../lib/apiErrors"
import { getNormalizedSessionTeamRole } from "../../lib/teamRole"
import * as api from "../../api/affiliates.api"
type Tab="applications"|"commissions"|"payouts"|"events"|"settings"
type Action={kind:"application"|"payout"|"commission";id:number;status:string}
export function AffiliatesPage(){
const allowed=["ADMIN","SUPER_ADMIN"].includes(getNormalizedSessionTeamRole())
const version=useRef(0)
const [tab,setTab]=useState<Tab>("applications")
const [offset,setOffset]=useState(0),[status,setStatus]=useState("")
const [applications,setApplications]=useState<api.AffiliateProfile[]>([])
const [commissions,setCommissions]=useState<api.AffiliateCommission[]>([])
const [payouts,setPayouts]=useState<api.AffiliatePayout[]>([])
const [events,setEvents]=useState<api.AffiliateEvent[]>([])
const [settings,setSettings]=useState<api.AffiliateSettings|null>(null)
const [total,setTotal]=useState(0),[loading,setLoading]=useState(true),[failed,setFailed]=useState(false),[busy,setBusy]=useState(false)
const [action,setAction]=useState<Action|null>(null),[note,setNote]=useState(""),[reference,setReference]=useState("")
const load=useCallback(async()=>{
if(!allowed)return
const request=++version.current
setLoading(true);setFailed(false)
try{
if(tab==="applications"){const p=await api.listAffiliates(offset,status);if(request!==version.current)return;setApplications(p.items);setTotal(p.total_count??0)}
if(tab==="commissions"){const p=await api.affiliateCommissions(offset);if(request!==version.current)return;setCommissions(p.items);setTotal(p.total_count??0)}
if(tab==="payouts"){const p=await api.affiliatePayouts(offset,status);if(request!==version.current)return;setPayouts(p.items);setTotal(p.total_count??0)}
if(tab==="events"){const p=await api.affiliateEvents(offset);if(request!==version.current)return;setEvents(p.items);setTotal(offset+p.items.length+(p.items.length===20?1:0))}
if(tab==="settings"){const data=await api.affiliateSettings();if(request===version.current)setSettings(data)}
}catch(e){if(request===version.current){setFailed(true);notifyApiError(e,"Unable to load affiliate program")}}
finally{if(request===version.current)setLoading(false)}
},[tab,offset,status,allowed])
useEffect(()=>{void load();return()=>{version.current+=1}},[load])
function open(next:Action){setAction(next);setNote("");setReference("")}
async function submit(e:FormEvent){
e.preventDefault();if(!action||busy)return;setBusy(true)
try{
if(action.kind==="application")await api.reviewAffiliate(action.id,action.status,note.trim())
if(action.kind==="payout")await api.reviewAffiliatePayout(action.id,action.status,note.trim(),reference.trim())
if(action.kind==="commission")await api.reverseAffiliateCommission(action.id,note.trim())
setAction(null);toast.success("Affiliate record updated");await load()
}catch(e){notifyApiError(e,"Unable to update affiliate record")}finally{setBusy(false)}
}
async function save(e:FormEvent){
e.preventDefault();if(!settings||busy)return
const percent=Number(settings.commission_percent)
if(!settings.commission_percent.trim()||!Number.isFinite(percent)||percent<0||percent>100||Math.abs(percent*100-Math.round(percent*100))>0.000001){toast.error("Enter a percentage from 0 to 100 with up to two decimals");return}
setBusy(true)
try{setSettings(await api.saveAffiliateSettings({...settings,commission_percent:percent}));toast.success("Affiliate settings saved")}catch(e){notifyApiError(e,"Unable to save affiliate settings")}finally{setBusy(false)}
}
const card="rounded-xl border bg-white p-5 space-y-3 dark:bg-grayScale-50"
if(!allowed)return <p className="p-6">Administrator access is required to manage the affiliate program.</p>
return <div className="mx-auto max-w-6xl space-y-6 p-6">
<header><h1 className="text-2xl font-bold">Affiliate program</h1><p className="mt-2 text-sm text-grayScale-500">Approve affiliates, review course commissions, and reconcile payouts. All financial changes are audited.</p></header>
<nav className="flex flex-wrap gap-2">{(["applications","commissions","payouts","events","settings"] as Tab[]).map(t=><Button key={t} disabled={busy||loading&&t===tab} variant={tab===t?"default":"outline"} onClick={()=>{setOffset(0);setStatus("");setTab(t)}} className="capitalize">{t}</Button>)}</nav>
{(tab==="applications"||tab==="payouts")&&<label className="flex items-center gap-3">Status<select className="rounded border p-2" value={status} disabled={loading||busy} onChange={e=>{setOffset(0);setStatus(e.target.value)}}><option value="">All</option>{(tab==="applications"?["PENDING","APPROVED","REJECTED","SUSPENDED"]:["REQUESTED","PAID","REJECTED"]).map(s=><option key={s}>{s}</option>)}</select></label>}
{loading?<p role="status">Loading affiliate program...</p>:failed?<div role="alert"><p>Unable to load this view.</p><Button onClick={()=>void load()}>Retry</Button></div>:<>
{tab==="applications"&&<div className="space-y-4">{applications.map(a=><article className={card} key={a.user_id}><div className="flex flex-wrap justify-between gap-2"><Link className="font-semibold underline" to={`/users/${a.user_id}`}>{a.first_name} {a.last_name} ? #{a.user_id}</Link><span>{a.status}</span></div><p>{a.email}</p><p className="whitespace-pre-wrap">{a.application}</p>{a.code&&<p>Referral code: <code>{a.code}</code></p>}{a.review_note&&<p>Review: {a.review_note}</p>}<div className="flex gap-2">{(a.status==="PENDING"?["APPROVED","REJECTED"]:a.status==="APPROVED"?["SUSPENDED"]:a.status==="SUSPENDED"?["APPROVED"]:[]).map(s=><Button key={s} variant="outline" disabled={busy} onClick={()=>open({kind:"application",id:a.user_id,status:s})}>{s==="APPROVED"?"Approve":s==="REJECTED"?"Reject":"Suspend"}</Button>)}</div></article>)}{!applications.length&&<p>No matching applications.</p>}</div>}
{tab==="commissions"&&<div className="space-y-4">{commissions.map(c=><article key={c.id} className={card}><div className="flex justify-between gap-3"><strong>{c.amount} {c.currency}</strong><span>{c.status}</span></div><p>Commission #{c.id} ? Affiliate #{c.referrer_id} ? Course #{c.course_id??"historical"} ? Payment #{c.payment_id}</p><p>Available: {new Date(c.available_at).toLocaleString()}</p>{c.reversal_reason?<p>Reversal: {c.reversal_reason}</p>:<Button variant="outline" onClick={()=>open({kind:"commission",id:c.id,status:"REVERSED"})}>Reverse commission</Button>}</article>)}{!commissions.length&&<p>No commissions.</p>}</div>}
{tab==="payouts"&&<><p className="rounded border p-4 text-sm">Transfer money externally before marking a payout paid. Recording a reference does not send money. Rejected requests release reserved earnings.</p><div className="space-y-4">{payouts.map(p=><article key={p.id} className={card}><div className="flex justify-between"><strong>{p.amount} {p.currency}</strong><span>{p.status}</span></div><p>Payout #{p.id} ? Affiliate #{p.user_id}</p><p>{p.method} ? {p.account_name} ? {p.account_reference}</p>{p.payment_reference&&<p>Transfer reference: {p.payment_reference}</p>}{p.review_note&&<p>Review: {p.review_note}</p>}{p.status==="REQUESTED"&&<div className="flex gap-2"><Button onClick={()=>open({kind:"payout",id:p.id,status:"PAID"})}>Record paid transfer</Button><Button variant="outline" onClick={()=>open({kind:"payout",id:p.id,status:"REJECTED"})}>Reject request</Button></div>}</article>)}{!payouts.length&&<p>No matching payout requests.</p>}</div></>}
{tab==="events"&&<div className="space-y-4">{events.map(e=><article key={e.id} className={card}><strong>{e.event}</strong><p>Affiliate {e.affiliate_user_id??"program"} ? Admin {e.actor_id??"system"} ? {new Date(e.created_at).toLocaleString()}</p><pre className="overflow-x-auto whitespace-pre-wrap text-xs">{JSON.stringify(e.details,null,2)}</pre></article>)}{!events.length&&<p>No audit events.</p>}</div>}
{tab==="settings"&&settings&&<form onSubmit={save} className={`${card} max-w-xl`}><p className="text-sm">Settings apply to future qualifying course payments. Existing commissions keep their original rate and holding period. Zero percent disables new earnings.</p><label className="block">Commission (%)<Input required type="number" min="0" max="100" step="0.01" value={settings.commission_percent} onChange={e=>setSettings({...settings,commission_percent:e.target.value})}/></label><label className="block">Commission policy<select className="block w-full rounded border p-2" value={settings.commission_mode} onChange={e=>setSettings({...settings,commission_mode:e.target.value as api.AffiliateSettings["commission_mode"]})}><option value="FIRST_PURCHASE">First paid purchase only</option><option value="EVERY_COURSE">Every distinct course purchased</option></select></label><label className="block">Attribution window (days)<Input required type="number" min="1" max="365" step="1" value={settings.attribution_days} onChange={e=>setSettings({...settings,attribution_days:Number(e.target.value)})}/></label><label className="block">Earnings hold (days)<Input required type="number" min="0" max="365" step="1" value={settings.holding_days} onChange={e=>setSettings({...settings,holding_days:Number(e.target.value)})}/></label><label className="block">Learner registration URL<Input type="url" value={settings.share_base_url} onChange={e=>setSettings({...settings,share_base_url:e.target.value})} placeholder="https://your-learner-site/register"/></label><p className="text-xs">Share links add ?ref=CODE. The learner client must submit that code after authentication and before the first purchase.</p><Button disabled={busy}>Save settings</Button></form>}
{tab!=="settings"&&<div className="flex items-center gap-4"><Button variant="outline" disabled={offset===0||busy} onClick={()=>setOffset(Math.max(0,offset-20))}>Previous</Button><span>Page {offset/20+1}</span><Button variant="outline" disabled={offset+20>=total||busy} onClick={()=>setOffset(offset+20)}>Next</Button></div>}
</>}
<Dialog open={!!action} onOpenChange={open=>{if(!open&&!busy)setAction(null)}}><DialogContent><DialogHeader><DialogTitle>{action?.kind==="commission"?"Reverse commission":action?.status==="PAID"?"Record completed payout":"Review affiliate record"}</DialogTitle></DialogHeader><form className="space-y-4" onSubmit={submit}><p>Record #{action?.id} ? {action?.status}</p>{action?.kind==="commission"&&<p>Paid commissions become a recovery balance deducted from future payouts. This does not refund the learner.</p>}{action?.status==="PAID"&&<label className="block">External transfer reference<Input required minLength={3} maxLength={120} value={reference} onChange={e=>setReference(e.target.value)}/></label>}<label className="block">Reason / review note<Textarea required minLength={3} maxLength={2000} value={note} onChange={e=>setNote(e.target.value)}/></label><div className="flex justify-end gap-2"><Button type="button" variant="outline" disabled={busy} onClick={()=>setAction(null)}>Cancel</Button><Button disabled={busy||note.trim().length<3||action?.status==="PAID"&&reference.trim().length<3}>{busy?"Saving...":"Confirm"}</Button></div></form></DialogContent></Dialog>
</div>
}

View File

@ -15,6 +15,8 @@ import {
type LearningItem as Item, type LearningKind as Kind, type LearningItem as Item, type LearningKind as Kind,
} from "../../api/learningHierarchy.api" } from "../../api/learningHierarchy.api"
import { learningContentForm, learningContentPayload, effectiveLearningAccess, coursePriceLabel, type AccessTier } from "../../lib/learningContentForm"
type Editor = { kind: Kind; item?: Item } type Editor = { kind: Kind; item?: Item }
export function LearningHierarchyPage() { export function LearningHierarchyPage() {
@ -34,7 +36,7 @@ export function LearningHierarchyPage() {
const [search, setSearch] = useState("") const [search, setSearch] = useState("")
const [editor, setEditor] = useState<Editor | null>(null) const [editor, setEditor] = useState<Editor | null>(null)
const [deleting, setDeleting] = useState<{ item: Item; kind: Kind } | null>(null) const [deleting, setDeleting] = useState<{ item: Item; kind: Kind } | null>(null)
const [form, setForm] = useState({ name: "", description: "", thumbnail: "", video_url: "", access_tier: "FREE" }) const [form, setForm] = useState(() => learningContentForm("course"))
const load = useCallback(async () => { const load = useCallback(async () => {
if (activePath.current !== path) return if (activePath.current !== path) return
@ -60,14 +62,13 @@ export function LearningHierarchyPage() {
function openEditor(next: Editor) { function openEditor(next: Editor) {
setEditor(next) setEditor(next)
const item = next.item const item = next.item
setForm({ name: item?.name ?? item?.title ?? "", description: item?.description ?? "", thumbnail: item?.thumbnail ?? "", video_url: item?.video_url ?? "", access_tier: item?.access_tier ?? "FREE" }) setForm(learningContentForm(next.kind, item))
} }
async function save(event: React.FormEvent) { async function save(event: React.FormEvent) {
event.preventDefault() event.preventDefault()
if (!editor || busy || !form.name.trim()) return if (!editor || busy || !form.name.trim()) return
setBusy(true) setBusy(true)
try { try {
const payload = { ...form, name: form.name.trim() }
if (editor.kind === "quiz") { if (editor.kind === "quiz") {
if (editor.item) { if (editor.item) {
await updateChapterQuiz(editor.item.id, { title: form.name.trim() }) await updateChapterQuiz(editor.item.id, { title: form.name.trim() })
@ -75,7 +76,7 @@ export function LearningHierarchyPage() {
await createChapterQuiz(Number(chapterId), form.name.trim()) await createChapterQuiz(Number(chapterId), form.name.trim())
} }
} else { } else {
const body = editor.kind === "lesson" ? { title: payload.name, description: payload.description, thumbnail: payload.thumbnail, video_url: payload.video_url, access_tier: payload.access_tier } : payload const body = learningContentPayload(editor.kind, form)
if (editor.item) await http.put(`/${collection[editor.kind]}/${editor.item.id}`, body) if (editor.item) await http.put(`/${collection[editor.kind]}/${editor.item.id}`, body)
else await http.post(path, { ...body, publish_status: "DRAFT" }) else await http.post(path, { ...body, publish_status: "DRAFT" })
} }
@ -112,16 +113,21 @@ export function LearningHierarchyPage() {
} }
const title = chapter?.name ?? course?.name ?? "Courses" const title = chapter?.name ?? course?.name ?? "Courses"
const matches = (item: Item) => (kind !== "course" || !item.is_archived) && (item.name ?? item.title ?? "").toLowerCase().includes(search.toLowerCase()) const matches = (item: Item) => (kind !== "course" || !item.is_archived) && (item.name ?? item.title ?? "").toLowerCase().includes(search.toLowerCase())
const courseAccess = effectiveLearningAccess(course)
const parentAccess = chapterId ? effectiveLearningAccess(chapter, courseAccess) : courseAccess
function card(item: Item, itemKind: Kind, index?: number) { function card(item: Item, itemKind: Kind, index?: number) {
const effectiveAccess = effectiveLearningAccess(item, parentAccess)
const accessLabel = itemKind === "quiz" ? `Follows chapter: ${parentAccess.toLowerCase()}` : item.access_tier === "INHERIT" || (!item.access_tier && itemKind !== "course") ? `Inherited: ${effectiveAccess.toLowerCase()}` : effectiveAccess.toLowerCase()
return <article key={item.id} className="rounded-xl border border-grayScale-200 bg-white p-5 dark:bg-grayScale-50"> return <article key={item.id} className="rounded-xl border border-grayScale-200 bg-white p-5 dark:bg-grayScale-50">
<div className="flex flex-wrap items-start justify-between gap-3"> <div className="flex flex-wrap items-start justify-between gap-3">
<div className="min-w-0"><h3 className="text-lg font-semibold">{item.name ?? item.title}</h3><p className="mt-1 text-sm text-grayScale-500">{item.publish_status === "PUBLISHED" ? "Published" : "Draft"}{item.access_tier ? ` · ${item.access_tier.toLowerCase()}` : ""}</p></div> <div className="min-w-0"><h3 className="text-lg font-semibold">{item.name ?? item.title}</h3><p className="mt-1 text-sm text-grayScale-500">{item.publish_status === "PUBLISHED" ? "Published" : "Draft"}{` - ${accessLabel}`}</p></div>
<div className="flex gap-1"> <div className="flex gap-1">
{index !== undefined && !search && <><Button size="icon" variant="ghost" disabled={busy || index === movableIndices[0]} onClick={() => void move(index, -1)} aria-label="Move up"><ArrowUp size={16} /></Button><Button size="icon" variant="ghost" disabled={busy || index === movableIndices[movableIndices.length - 1]} onClick={() => void move(index, 1)} aria-label="Move down"><ArrowDown size={16} /></Button></>} {index !== undefined && !search && <><Button size="icon" variant="ghost" disabled={busy || index === movableIndices[0]} onClick={() => void move(index, -1)} aria-label="Move up"><ArrowUp size={16} /></Button><Button size="icon" variant="ghost" disabled={busy || index === movableIndices[movableIndices.length - 1]} onClick={() => void move(index, 1)} aria-label="Move down"><ArrowDown size={16} /></Button></>}
<Button size="icon" variant="ghost" disabled={busy || item.is_archived} onClick={() => openEditor({ kind: itemKind, item })} aria-label="Edit"><Pencil size={16} /></Button> <Button size="icon" variant="ghost" disabled={busy || item.is_archived} onClick={() => openEditor({ kind: itemKind, item })} aria-label="Edit"><Pencil size={16} /></Button>
<Button size="icon" variant="ghost" disabled={busy || item.is_archived} onClick={() => setDeleting({ item, kind: itemKind })} aria-label="Delete"><Trash2 size={16} /></Button> <Button size="icon" variant="ghost" disabled={busy || item.is_archived} onClick={() => setDeleting({ item, kind: itemKind })} aria-label="Delete"><Trash2 size={16} /></Button>
</div> </div>
</div> </div>
{itemKind === "course" && <p className="mt-2 text-sm font-medium text-grayScale-700">{coursePriceLabel(item)}</p>}
{item.description && <p className="mt-3 line-clamp-3 text-sm text-grayScale-600">{item.description}</p>} {item.description && <p className="mt-3 line-clamp-3 text-sm text-grayScale-600">{item.description}</p>}
{item.video_url && <a className="mt-3 block text-sm text-brand-600 underline" href={item.video_url} target="_blank" rel="noreferrer">View lesson video</a>} {item.video_url && <a className="mt-3 block text-sm text-brand-600 underline" href={item.video_url} target="_blank" rel="noreferrer">View lesson video</a>}
<div className="mt-5 flex flex-wrap gap-2"> <div className="mt-5 flex flex-wrap gap-2">
@ -141,8 +147,9 @@ export function LearningHierarchyPage() {
<section className="space-y-4"><h2 className="text-xl font-semibold capitalize">{collection[kind]}</h2><div className="grid gap-4 md:grid-cols-2">{items.map((item, index) => matches(item) ? card(item, kind, index) : null)}</div>{!items.some(matches) && <p className="rounded-xl border border-dashed p-8 text-center text-grayScale-500">{search ? "No matching content." : `No ${collection[kind]} yet. Add your first ${kind} to get started.`}</p>}</section> <section className="space-y-4"><h2 className="text-xl font-semibold capitalize">{collection[kind]}</h2><div className="grid gap-4 md:grid-cols-2">{items.map((item, index) => matches(item) ? card(item, kind, index) : null)}</div>{!items.some(matches) && <p className="rounded-xl border border-dashed p-8 text-center text-grayScale-500">{search ? "No matching content." : `No ${collection[kind]} yet. Add your first ${kind} to get started.`}</p>}</section>
{chapterId && <section className="space-y-4 border-t pt-6"><div className="flex items-center justify-between"><h2 className="text-xl font-semibold">Chapter quizzes</h2><Button disabled={busy} onClick={() => openEditor({ kind: "quiz" })}><Plus size={16} className="mr-2" />Add quiz</Button></div><div className="grid gap-4 md:grid-cols-2">{quizzes.filter(matches).map(item => card(item, "quiz"))}</div>{!quizzes.some(matches) && <p className="text-grayScale-500">{search ? "No matching quizzes." : "No quizzes yet. Create a quiz, add its questions, then publish it."}</p>}</section>} {chapterId && <section className="space-y-4 border-t pt-6"><div className="flex items-center justify-between"><h2 className="text-xl font-semibold">Chapter quizzes</h2><Button disabled={busy} onClick={() => openEditor({ kind: "quiz" })}><Plus size={16} className="mr-2" />Add quiz</Button></div><div className="grid gap-4 md:grid-cols-2">{quizzes.filter(matches).map(item => card(item, "quiz"))}</div>{!quizzes.some(matches) && <p className="text-grayScale-500">{search ? "No matching quizzes." : "No quizzes yet. Create a quiz, add its questions, then publish it."}</p>}</section>}
</>} </>}
<Dialog open={!!editor} onOpenChange={open => { if (!open && !busy) setEditor(null) }}><DialogContent><DialogHeader><DialogTitle>{editor?.item ? "Edit" : "Add"} {editor?.kind}</DialogTitle></DialogHeader><form onSubmit={save} className="space-y-4"><label className="block space-y-2"><span>Title</span><Input autoFocus required value={form.name} onChange={event => setForm({ ...form, name: event.target.value })} /></label> <Dialog open={!!editor} onOpenChange={open => { if (!open && !busy) setEditor(null) }}><DialogContent className="max-h-[90vh] overflow-y-auto"><DialogHeader><DialogTitle>{editor?.item ? "Edit" : "Add"} {editor?.kind}</DialogTitle></DialogHeader><form onSubmit={save} className="space-y-4"><label className="block space-y-2"><span>Title</span><Input autoFocus required value={form.name} onChange={event => setForm({ ...form, name: event.target.value })} /></label>
{editor?.kind !== "quiz" && <><label className="block space-y-2"><span>Description</span><Textarea value={form.description} onChange={event => setForm({ ...form, description: event.target.value })} /></label><label className="block space-y-2"><span>Thumbnail URL</span><Input type="url" value={form.thumbnail} onChange={event => setForm({ ...form, thumbnail: event.target.value })} /></label><label className="block space-y-2"><span>Access</span><select className="w-full rounded-md border p-2" value={form.access_tier} onChange={event => setForm({ ...form, access_tier: event.target.value })}><option value="FREE">Free</option><option value="PREMIUM">Premium</option></select></label></>} {editor?.kind !== "quiz" && <><label className="block space-y-2"><span>Description</span><Textarea value={form.description} onChange={event => setForm({ ...form, description: event.target.value })} /></label><label className="block space-y-2"><span>Thumbnail URL</span><Input type="url" value={form.thumbnail} onChange={event => setForm({ ...form, thumbnail: event.target.value })} /></label><label className="block space-y-2"><span>Access</span><select className="w-full rounded-md border p-2" value={form.access_tier} onChange={event => setForm({ ...form, access_tier: event.target.value as AccessTier })}>{editor?.kind !== "course" && <option value="INHERIT">Inherit from parent ({parentAccess.toLowerCase()})</option>}<option value="FREE">Free</option><option value="PREMIUM">Premium</option></select><p className="text-xs text-grayScale-500">{editor?.kind === "course" ? "Chapters and lessons follow this access by default. Individual children can override it." : "Inherited access follows parent changes. Choose Free for a preview, or Premium to require a course purchase."}</p></label></>}
{editor?.kind === "course" && <fieldset className="space-y-3 rounded-lg border p-3"><legend className="px-1 font-medium">Course purchase</legend><div className="grid grid-cols-2 gap-3"><label className="space-y-2"><span>Price</span><Input type="number" required min="0" max="9999999999.99" step="0.01" value={form.price} onChange={event => setForm({ ...form, price: event.target.value })} /></label><label className="space-y-2"><span>Currency</span><Input required minLength={3} maxLength={3} pattern="[A-Z]{3}" value={form.currency} onChange={event => setForm({ ...form, currency: event.target.value.toUpperCase() })} placeholder="ETB" /></label></div><p className="text-xs text-grayScale-500">One purchase unlocks this course's premium content. A free course can have a price for premium chapters or lessons.</p>{Number(form.price) === 0 && <p className="text-xs text-amber-700" role="status">Premium content cannot be purchased until a positive course price is set. Free content remains accessible.</p>}</fieldset>}
{editor?.kind === "lesson" && <label className="block space-y-2"><span>Video URL</span><Input type="url" value={form.video_url} onChange={event => setForm({ ...form, video_url: event.target.value })} /></label>} {editor?.kind === "lesson" && <label className="block space-y-2"><span>Video URL</span><Input type="url" value={form.video_url} onChange={event => setForm({ ...form, video_url: event.target.value })} /></label>}
<div className="flex justify-end gap-2"><Button type="button" variant="outline" disabled={busy} onClick={() => setEditor(null)}>Cancel</Button><Button type="submit" disabled={busy || !form.name.trim()}>{busy ? "Saving…" : "Save"}</Button></div></form></DialogContent></Dialog> <div className="flex justify-end gap-2"><Button type="button" variant="outline" disabled={busy} onClick={() => setEditor(null)}>Cancel</Button><Button type="submit" disabled={busy || !form.name.trim()}>{busy ? "Saving…" : "Save"}</Button></div></form></DialogContent></Dialog>
<Dialog open={!!deleting} onOpenChange={open => { if (!open && !busy) setDeleting(null) }}><DialogContent><DialogHeader><DialogTitle>Delete {deleting?.kind}?</DialogTitle></DialogHeader><p>This removes “{deleting?.item.name ?? deleting?.item.title}” and its child content.</p><div className="flex justify-end gap-2"><Button variant="outline" disabled={busy} onClick={() => setDeleting(null)}>Cancel</Button><Button variant="destructive" disabled={busy} onClick={() => void remove()}>{busy ? "Deleting…" : "Delete"}</Button></div></DialogContent></Dialog> <Dialog open={!!deleting} onOpenChange={open => { if (!open && !busy) setDeleting(null) }}><DialogContent><DialogHeader><DialogTitle>Delete {deleting?.kind}?</DialogTitle></DialogHeader><p>This removes “{deleting?.item.name ?? deleting?.item.title}” and its child content.</p><div className="flex justify-end gap-2"><Button variant="outline" disabled={busy} onClick={() => setDeleting(null)}>Cancel</Button><Button variant="destructive" disabled={busy} onClick={() => void remove()}>{busy ? "Deleting…" : "Delete"}</Button></div></DialogContent></Dialog>

View File

@ -1,3 +1,4 @@
import { paymentContentLabel } from "../../lib/payments"
import { import {
ChevronDown, ChevronDown,
ChevronLeft, ChevronLeft,
@ -440,7 +441,7 @@ export function PaymentsPage() {
</div> </div>
<div className="flex flex-wrap items-center gap-2"> <div className="flex flex-wrap items-center gap-2">
<span className="mr-1 text-[11px] font-bold uppercase tracking-wider text-grayScale-400"> <span className="mr-1 text-[11px] font-bold uppercase tracking-wider text-grayScale-400">
Plan Legacy plan category
</span> </span>
{PLAN_CATEGORY_FILTERS.map(({ value, label }) => ( {PLAN_CATEGORY_FILTERS.map(({ value, label }) => (
<FilterChip <FilterChip
@ -561,7 +562,7 @@ export function PaymentsPage() {
<tr className="border-b border-grayScale-100 bg-grayScale-50/80 text-[11px] font-bold uppercase tracking-wider text-grayScale-400"> <tr className="border-b border-grayScale-100 bg-grayScale-50/80 text-[11px] font-bold uppercase tracking-wider text-grayScale-400">
<th className="whitespace-nowrap px-3 py-2.5 sm:px-4">Transaction</th> <th className="whitespace-nowrap px-3 py-2.5 sm:px-4">Transaction</th>
<th className="whitespace-nowrap px-3 py-2.5 sm:px-4">Customer</th> <th className="whitespace-nowrap px-3 py-2.5 sm:px-4">Customer</th>
<th className="whitespace-nowrap px-3 py-2.5 sm:px-4">Plan</th> <th className="whitespace-nowrap px-3 py-2.5 sm:px-4">Course / legacy plan</th>
<th className="whitespace-nowrap px-3 py-2.5 sm:px-4">Amount</th> <th className="whitespace-nowrap px-3 py-2.5 sm:px-4">Amount</th>
<th className="whitespace-nowrap px-3 py-2.5 sm:px-4">Method</th> <th className="whitespace-nowrap px-3 py-2.5 sm:px-4">Method</th>
<th className="whitespace-nowrap px-3 py-2.5 sm:px-4">Status</th> <th className="whitespace-nowrap px-3 py-2.5 sm:px-4">Status</th>
@ -606,7 +607,7 @@ export function PaymentsPage() {
<td className="px-3 py-2.5 sm:px-4"> <td className="px-3 py-2.5 sm:px-4">
<p className="max-w-[160px] truncate font-medium text-grayScale-800"> <p className="max-w-[160px] truncate font-medium text-grayScale-800">
<SearchHighlight <SearchHighlight
text={payment.plan_name || `Plan #${payment.plan_id}`} text={paymentContentLabel(payment)}
query={searchQuery} query={searchQuery}
/> />
</p> </p>
@ -791,11 +792,11 @@ export function PaymentsPage() {
{[ {[
{ k: "Customer", v: paymentCustomerName(selected) }, { k: "Customer", v: paymentCustomerName(selected) },
{ k: "Email", v: selected.user_email || <UnassignedLabel /> }, { k: "Email", v: selected.user_email || <UnassignedLabel /> },
{ k: "Plan", v: selected.plan_name || `Plan #${selected.plan_id}` }, { k: "Course / legacy plan", v: paymentContentLabel(selected) },
{ k: "Category", v: formatPaymentPlanCategory(selected.plan_category) }, ...(selected.course_id ? [{ k: "Access", v: "One-time course purchase" }] : [{ k: "Category", v: formatPaymentPlanCategory(selected.plan_category) }]),
{ k: "Transaction", v: selected.transaction_id || <UnassignedLabel />, mono: true }, { k: "Transaction", v: selected.transaction_id || <UnassignedLabel />, mono: true },
{ k: "Session", v: selected.session_id || <UnassignedLabel />, mono: true }, { k: "Session", v: selected.session_id || <UnassignedLabel />, mono: true },
{ k: "Subscription", v: `#${selected.subscription_id}` }, ...(selected.subscription_id ? [{ k: "Legacy subscription", v: `#${selected.subscription_id}` }] : []),
{ k: "Paid", v: formatPaymentDate(selected.paid_at ?? selected.created_at) }, { k: "Paid", v: formatPaymentDate(selected.paid_at ?? selected.created_at) },
...(selected.expires_at ? [{ k: "Expires", v: formatPaymentDate(selected.expires_at) }] : []), ...(selected.expires_at ? [{ k: "Expires", v: formatPaymentDate(selected.expires_at) }] : []),
].map((row) => ( ].map((row) => (

View File

@ -57,10 +57,11 @@ export function ReferralsTab() {
return ( return (
<Card className="rounded-[6px] border border-grayScale-100"> <Card className="rounded-[6px] border border-grayScale-100">
<CardHeader><CardTitle>Referral commissions</CardTitle></CardHeader> <CardHeader><CardTitle>Affiliate commission rate</CardTitle></CardHeader>
<CardContent> <CardContent>
<a href="/affiliates" className="mb-4 block text-sm underline">Open Affiliate program</a>
<form onSubmit={save} className="max-w-xl space-y-5"> <form onSubmit={save} className="max-w-xl space-y-5">
<p className="text-sm text-grayScale-500">Learners earn a wallet commission on the first successful paid subscription purchased by someone they refer.</p> <p className="text-sm text-grayScale-500">Approved affiliates earn commissions on eligible course purchases. Manage applications, attribution windows, earning holds, and payouts in the Affiliate program.</p>
<div className="space-y-2"> <div className="space-y-2">
<label htmlFor="referral-commission" className="text-sm font-medium">Commission percentage (%)</label> <label htmlFor="referral-commission" className="text-sm font-medium">Commission percentage (%)</label>
<Input id="referral-commission" type="number" min="0" max="100" step="0.01" required <Input id="referral-commission" type="number" min="0" max="100" step="0.01" required

View File

@ -170,7 +170,7 @@ function ActiveSubscriptionsCard({
aria-expanded={expanded} aria-expanded={expanded}
> >
<div className="min-w-0 flex-1"> <div className="min-w-0 flex-1">
<h3 className="text-base font-bold text-grayScale-900">Subscriptions</h3> <h3 className="text-base font-bold text-grayScale-900">Legacy subscriptions</h3>
<p className="mt-0.5 text-xs text-grayScale-500"> <p className="mt-0.5 text-xs text-grayScale-500">
{subscriptions.length} active plan{subscriptions.length === 1 ? "" : "s"} {subscriptions.length} active plan{subscriptions.length === 1 ? "" : "s"}
</p> </p>
@ -318,7 +318,7 @@ function EmptySubscriptionCard({
onClick={() => setExpanded((value) => !value)} onClick={() => setExpanded((value) => !value)}
aria-expanded={expanded} aria-expanded={expanded}
> >
<h3 className="text-base font-bold text-grayScale-900">Subscriptions</h3> <h3 className="text-base font-bold text-grayScale-900">Legacy subscriptions</h3>
<div className="flex shrink-0 items-center gap-2"> <div className="flex shrink-0 items-center gap-2">
<ActiveStatusBadge <ActiveStatusBadge
label={formatStatusLabel(displayStatus || "Unsubscribed")} label={formatStatusLabel(displayStatus || "Unsubscribed")}
@ -411,10 +411,8 @@ export function UserSubscriptionsSection({
const [cancelTarget, setCancelTarget] = useState<UserSubscriptionRecord | null>(null) const [cancelTarget, setCancelTarget] = useState<UserSubscriptionRecord | null>(null)
const [catalogPlans, setCatalogPlans] = useState<SubscriptionPlan[]>([]) const [catalogPlans, setCatalogPlans] = useState<SubscriptionPlan[]>([])
const canApply = hasSubscriptionAdminPermission( // Historical subscriptions no longer grant learning access.
SUBSCRIPTION_ADMIN_PERMISSIONS.apply, const canApply = false
permissions,
)
const canExtend = canApply const canExtend = canApply
const canCancel = hasSubscriptionAdminPermission( const canCancel = hasSubscriptionAdminPermission(
SUBSCRIPTION_ADMIN_PERMISSIONS.cancel, SUBSCRIPTION_ADMIN_PERMISSIONS.cancel,
@ -436,6 +434,7 @@ export function UserSubscriptionsSection({
) )
useEffect(() => { useEffect(() => {
if (!canApply) return
let cancelled = false let cancelled = false
;(async () => { ;(async () => {
try { try {
@ -450,7 +449,7 @@ export function UserSubscriptionsSection({
return () => { return () => {
cancelled = true cancelled = true
} }
}, [userId]) }, [userId, canApply])
const activeCategories = useMemo(() => { const activeCategories = useMemo(() => {
const fromSubs = activePlans const fromSubs = activePlans
@ -498,6 +497,7 @@ export function UserSubscriptionsSection({
return ( return (
<> <>
<div className="w-full space-y-4"> <div className="w-full space-y-4">
<p className="rounded-lg border p-4 text-sm text-grayScale-600">Legacy subscription history. Subscriptions no longer unlock learning content. Learners must purchase each course, including those with an active subscription.</p>
{loading ? ( {loading ? (
<Card className="rounded-2xl border border-grayScale-200 shadow-sm"> <Card className="rounded-2xl border border-grayScale-200 shadow-sm">
<CardContent className="flex items-center gap-2 p-6 text-sm text-grayScale-400"> <CardContent className="flex items-center gap-2 p-6 text-sm text-grayScale-400">

View File

@ -18,6 +18,7 @@ export type PaymentPlanCategory = SubscriptionPlanCategory
export interface Payment { export interface Payment {
id: number id: number
user_id: number user_id: number
course_id?: number
plan_id: number plan_id: number
subscription_id: number subscription_id: number
session_id: string session_id: string