From 911f8248a0bbf92224bc79b9d5e95783d5183f98 Mon Sep 17 00:00:00 2001 From: ASIF RAZA Date: Sat, 14 Nov 2026 14:30:33 +0500 Subject: [PATCH 1/8] feat(payments): admin Polar refunds with fee-adjusted policy, admin enrollments page, and free access for course instructors --- .../[enrollmentId]/enrollment-edit-form.tsx | 64 ++++ .../admin/enrollments/[enrollmentId]/page.tsx | 213 +++++++++++++ .../enrollments/delete-enrollment-button.tsx | 40 +++ .../app/(admin)/admin/enrollments/page.tsx | 192 +++++++++++ .../admin/enrollments/payment-badge.tsx | 52 +++ .../app/(admin)/admin/users/[userId]/page.tsx | 33 +- .../components/admin/admin-action-form.tsx | 7 +- .../admin/admin-workspace-shell.tsx | 2 + .../src/server/actions/admin/enrollments.ts | 49 +++ frontend/src/server/actions/admin/users.ts | 21 ++ frontend/src/shared/api/admin.ts | 87 +++++ server/src/routes/v1/admin.ts | 23 +- server/src/routes/webhook/polar.ts | 23 +- server/src/services/admin/audit.ts | 2 + server/src/services/admin/enrollments.ts | 298 ++++++++++++++++++ server/src/services/admin/users.ts | 17 +- server/src/services/catalog/catalog.ts | 11 +- server/src/services/courses/overview.ts | 13 +- server/src/services/enrollment/checkout.ts | 8 +- .../enrollment/create-self-enrollment.ts | 9 + server/src/services/enrollment/own-course.ts | 32 ++ .../enrollment/resolve-learn-enrollment.ts | 14 +- server/src/services/enrollment/self-enroll.ts | 2 +- .../payments/create-course-checkout.ts | 5 +- .../payments/refund-course-payment.ts | 73 +++++ .../services/payments/refund-polar-order.ts | 104 ++++++ server/src/services/payments/refund-policy.ts | 42 +++ server/src/shared/api/admin.ts | 87 +++++ server/src/validations/admin.ts | 9 + server/src/validations/enrollments.ts | 14 + server/tests/api/admin.test.ts | 108 +++++++ .../tests/unit/services/admin/users.test.ts | 41 +++ .../services/enrollment/own-course.test.ts | 45 +++ .../payments/polar-webhook-route.test.ts | 36 ++- .../payments/refund-course-payment.test.ts | 81 +++++ .../payments/refund-polar-order.test.ts | 99 ++++++ .../services/payments/refund-policy.test.ts | 31 ++ 37 files changed, 1963 insertions(+), 24 deletions(-) create mode 100644 frontend/src/app/(admin)/admin/enrollments/[enrollmentId]/enrollment-edit-form.tsx create mode 100644 frontend/src/app/(admin)/admin/enrollments/[enrollmentId]/page.tsx create mode 100644 frontend/src/app/(admin)/admin/enrollments/delete-enrollment-button.tsx create mode 100644 frontend/src/app/(admin)/admin/enrollments/page.tsx create mode 100644 frontend/src/app/(admin)/admin/enrollments/payment-badge.tsx create mode 100644 frontend/src/server/actions/admin/enrollments.ts create mode 100644 server/src/services/admin/enrollments.ts create mode 100644 server/src/services/enrollment/own-course.ts create mode 100644 server/src/services/payments/refund-course-payment.ts create mode 100644 server/src/services/payments/refund-polar-order.ts create mode 100644 server/src/services/payments/refund-policy.ts create mode 100644 server/tests/unit/services/enrollment/own-course.test.ts create mode 100644 server/tests/unit/services/payments/refund-course-payment.test.ts create mode 100644 server/tests/unit/services/payments/refund-polar-order.test.ts create mode 100644 server/tests/unit/services/payments/refund-policy.test.ts diff --git a/frontend/src/app/(admin)/admin/enrollments/[enrollmentId]/enrollment-edit-form.tsx b/frontend/src/app/(admin)/admin/enrollments/[enrollmentId]/enrollment-edit-form.tsx new file mode 100644 index 000000000..06ada52da --- /dev/null +++ b/frontend/src/app/(admin)/admin/enrollments/[enrollmentId]/enrollment-edit-form.tsx @@ -0,0 +1,64 @@ +import type { ReactNode } from "react"; +import type { AdminEnrollmentDetail } from "@/shared/api/admin"; +import { AdminActionForm } from "@/components/admin/admin-action-form"; +import { adminSelectClassName } from "@/components/admin/admin-ui"; +import { updateEnrollmentAction } from "@/server/actions/admin/enrollments"; + +const LIFECYCLES = [ + ["ACTIVE", "Active — has access"], + ["COMPLETED", "Completed — has access"], + ["PAYMENT_REQUIRED", "Payment required — no access"], + ["PENDING_ACCOUNT", "Pending account — no access"], + ["CANCELLED", "Cancelled — no access"], + ["EXPIRED", "Expired — no access"], +] as const; +const PAYMENT_STATUSES = [ + ["PENDING", "Pending"], + ["SUCCEEDED", "Paid"], + ["FAILED", "Failed"], + ["REFUNDED", "Refunded"], +] as const; + +function Field({ label, hint, children }: { label: string; hint?: string; children: ReactNode }) { + return ( + + ); +} + +function Select({ name, value, options }: { name: string; value: string; options: ReadonlyArray }) { + return ( + + ); +} + +/** Admin edit of the two things that can be changed by hand: course access and payment status. */ +export function EnrollmentEditForm({ enrollment }: { enrollment: AdminEnrollmentDetail }) { + const payment = enrollment.payment; + return ( + + +
+ + + + ) : ( +

No payment record, so there is no payment status to change.

+ )} +
+
+ ); +} diff --git a/frontend/src/app/(admin)/admin/enrollments/[enrollmentId]/page.tsx b/frontend/src/app/(admin)/admin/enrollments/[enrollmentId]/page.tsx new file mode 100644 index 000000000..097d18053 --- /dev/null +++ b/frontend/src/app/(admin)/admin/enrollments/[enrollmentId]/page.tsx @@ -0,0 +1,213 @@ +import Link from "next/link"; +import type { ReactNode } from "react"; +import type { AdminEnrollmentDetail } from "@/shared/api/admin"; +import { serverApiFetchOrNotFound } from "@/lib/api-server"; +import { formatPriceCents } from "@/lib/format-price"; +import { Badge } from "@/components/ui/badge"; +import { requireRole } from "@/server/auth/guards"; +import { AdminBackLink, AdminPanel, AdminSection } from "@/components/admin/admin-ui"; +import { PaymentStatusBadge, discountKindLabel, providerLabel, wasCharged } from "../payment-badge"; +import { DeleteEnrollmentButton } from "../delete-enrollment-button"; +import { EnrollmentEditForm } from "./enrollment-edit-form"; + +const dateTime = new Intl.DateTimeFormat(undefined, { dateStyle: "medium", timeStyle: "short" }); +const when = (iso: string | null) => (iso ? dateTime.format(new Date(iso)) : "—"); + +function Field({ label, children, strong }: { label: string; children: ReactNode; strong?: boolean }) { + return ( +
+
{label}
+
{children}
+
+ ); +} + +function StatTile({ label, value, hint }: { label: string; value: string; hint?: string }) { + return ( +
+

{label}

+

{value}

+ {hint ?

{hint}

: null} +
+ ); +} + +export default async function AdminEnrollmentDetailPage({ params }: { params: Promise<{ enrollmentId: string }> }) { + await requireRole("ADMIN"); + const { enrollmentId } = await params; + const enrollment = await serverApiFetchOrNotFound( + `/api/v1/admin/enrollments/${encodeURIComponent(enrollmentId)}` + ); + const { learner, course, payment } = enrollment; + const money = (cents: number) => formatPriceCents(cents, payment?.currency); + const charged = wasCharged(payment?.status); + + return ( +
+ ← Back to enrollments + +
+
+

Enrollment

+

{course.title}

+

+ {learner.userId ? ( + + {learner.name ?? learner.email} + + ) : ( + {learner.email ?? "Unknown learner"} + )} + {learner.name && learner.email ? · {learner.email} : null} +

+
+
+ + {enrollment.lifecycle.replace(/_/g, " ").toLowerCase()} + {enrollment.source.toLowerCase()} + {payment?.provider ? {providerLabel(payment.provider)} : null} + +
+
+ + {payment ? ( + <> +
+ 0 ? `${money(payment.amountCents)} due` : undefined} + /> + + +
+ +
+ + +
+ {money(payment.originalAmountCents)} + −{money(payment.discountAmountCents)} + −{money(payment.organizationContributionCents)} + {money(payment.learnerAmountCents)} + {money(payment.amountCents)} + {payment.fundingSource?.replace(/_/g, " ") ?? "—"} +
+
+
+ + + +
+ {money(payment.platformRevenueCents)} + {money(payment.instructorShareCents)} + {payment.instructorPayoutStatus.replace(/_/g, " ").toLowerCase()} + {when(payment.instructorPayoutPaidAt)} + + + {enrollment.instructor.name ?? enrollment.instructor.email} + + +
+
+
+
+ + + +
+ {payment.provider ? providerLabel(payment.provider) : "—"} + + {payment.providerRef ?? "—"} + + {payment.currency} + {when(payment.createdAt)} + {when(payment.paidAt)} + {when(payment.updatedAt)} +
+ {payment.status === "SUCCEEDED" && payment.provider === "polar" && learner.userId ? ( +

+ To refund this payment, use the{" "} + + learner's account page + + . +

+ ) : null} +
+
+ + ) : ( + +

+ No payment is recorded for this enrollment. It was free, or access was granted without a charge. +

+
+ )} + + + + {enrollment.discounts.length === 0 ? ( +

No coupon or campaign was used. The learner was charged the full price.

+ ) : ( +
    + {enrollment.discounts.map((discount) => ( +
  • +
    +
    + {discountKindLabel(discount.kind)} +

    {discount.label}

    +
    +

    + {discount.code ? {discount.code} : "No code"} + {discount.autoApplied ? " · applied automatically" : ""} + {discount.organizationName ? ` · from ${discount.organizationName}` : ""} + {discount.status ? ` · ${discount.status.toLowerCase()}` : ""} + {discount.appliedAt ? ` · ${when(discount.appliedAt)}` : ""} +

    +
    +

    {discount.percentOff}% off

    +
  • + ))} +
+ )} +
+
+ + + +
+ {when(enrollment.createdAt)} + {when(enrollment.startedAt)} + {when(enrollment.completedAt)} + {enrollment.percentComplete}% · {enrollment.status.replace(/_/g, " ").toLowerCase()} + {enrollment.organization?.name ?? "—"} + + {enrollment.id} + +
+
+
+ + + + + + +
+ ); +} diff --git a/frontend/src/app/(admin)/admin/enrollments/delete-enrollment-button.tsx b/frontend/src/app/(admin)/admin/enrollments/delete-enrollment-button.tsx new file mode 100644 index 000000000..5f5613580 --- /dev/null +++ b/frontend/src/app/(admin)/admin/enrollments/delete-enrollment-button.tsx @@ -0,0 +1,40 @@ +import { Trash2 } from "lucide-react"; +import { AdminActionForm } from "@/components/admin/admin-action-form"; +import { deleteEnrollmentAction } from "@/server/actions/admin/enrollments"; + +/** Trash icon that deletes the enrollment and everything attached to it, after a confirm. */ +export function DeleteEnrollmentButton({ + enrollmentId, + learner, + courseTitle, + paid, + redirectToList, +}: { + enrollmentId: string; + learner: string; + courseTitle: string; + paid: string | null; + redirectToList?: boolean; +}) { + return ( + } + confirm={{ + question: `Delete ${learner}'s enrollment in ${courseTitle}?`, + description: + "This permanently removes the enrollment from the database with its progress, answers, payment record and certificate. " + + (paid ? `The ${paid} payment is not refunded; refund it first if the learner should get money back. ` : "") + + "This cannot be undone.", + confirmLabel: "Delete permanently", + }} + > + + {redirectToList ? : null} + + ); +} diff --git a/frontend/src/app/(admin)/admin/enrollments/page.tsx b/frontend/src/app/(admin)/admin/enrollments/page.tsx new file mode 100644 index 000000000..34a92b92c --- /dev/null +++ b/frontend/src/app/(admin)/admin/enrollments/page.tsx @@ -0,0 +1,192 @@ +import Link from "next/link"; +import type { AdminEnrollmentsView } from "@/shared/api/admin"; +import { serverApiFetch } from "@/lib/api-server"; +import { formatPriceCents } from "@/lib/format-price"; +import { Badge } from "@/components/ui/badge"; +import { requireRole } from "@/server/auth/guards"; +import { DeleteEnrollmentButton } from "./delete-enrollment-button"; +import { + AdminEmptyState, + AdminPageHeader, + AdminTable, + AdminTableBody, + AdminTableCell, + AdminTableHead, + AdminTableHeaderCell, + AdminTableRow, +} from "@/components/admin/admin-ui"; +import { buildListQuery } from "@/components/admin/admin-list-controls"; +import { AdminLiveFilterBar } from "@/components/admin/admin-live-filter-bar"; +import { AdminPagination } from "@/components/admin/admin-pagination"; +import { DiscountBadge, PaymentStatusBadge, providerLabel, wasCharged } from "./payment-badge"; + +type SearchParams = { query?: string; payment?: string; lifecycle?: string; discount?: string; page?: string }; + +const dateFormat = new Intl.DateTimeFormat(undefined, { dateStyle: "medium" }); + +export default async function AdminEnrollmentsPage({ searchParams }: { searchParams: Promise }) { + await requireRole("ADMIN"); + const sp = await searchParams; + const filters = { query: sp.query, payment: sp.payment, lifecycle: sp.lifecycle, discount: sp.discount }; + const filtering = Boolean(sp.query || sp.payment || sp.lifecycle || sp.discount); + + const listQuery = buildListQuery({ ...filters, page: sp.page && sp.page !== "1" ? sp.page : undefined }); + const { enrollments, page } = await serverApiFetch( + `/api/v1/admin/enrollments${listQuery ? `?${listQuery}` : ""}` + ); + + const hrefFor = (next: number) => { + const qs = buildListQuery({ ...filters, page: next > 1 ? String(next) : undefined }); + return `/admin/enrollments${qs ? `?${qs}` : ""}`; + }; + + return ( +
+ + + + + {enrollments.length === 0 ? ( + + ) : ( + + + + Learner + Course + Enrolled + Payment + Discount + List price + Learner paid + + Actions + + + + + {enrollments.map((row) => { + const payment = row.payment; + return ( + + + + {row.learner.name ?? row.learner.email ?? "Unknown learner"} + + {row.learner.name && row.learner.email ? ( +

{row.learner.email}

+ ) : null} +
+ +

{row.course.title}

+
+ {row.lifecycle.replace(/_/g, " ").toLowerCase()} + {row.source.toLowerCase()} + {payment?.provider ? ( + + {providerLabel(payment.provider)} + + ) : null} +
+
+ + {dateFormat.format(new Date(row.createdAt))} + + + + + + {row.discounts.length > 0 ? ( +
+ {row.discounts.map((discount) => ( + + ))} +
+ ) : ( + — + )} +
+ + {payment ? formatPriceCents(payment.originalAmountCents, payment.currency) : "—"} + + + {payment && wasCharged(payment.status) ? ( + formatPriceCents(payment.amountCents, payment.currency) + ) : payment && payment.amountCents > 0 ? ( + + {formatPriceCents(payment.amountCents, payment.currency)} due + + ) : ( + formatPriceCents(0, payment?.currency) + )} + + + + +
+ ); + })} +
+
+ )} + +
+ ); +} diff --git a/frontend/src/app/(admin)/admin/enrollments/payment-badge.tsx b/frontend/src/app/(admin)/admin/enrollments/payment-badge.tsx new file mode 100644 index 000000000..b108c5446 --- /dev/null +++ b/frontend/src/app/(admin)/admin/enrollments/payment-badge.tsx @@ -0,0 +1,52 @@ +import type { AdminEnrollmentDiscount, AdminPaymentStatus } from "@/shared/api/admin"; +import { Badge } from "@/components/ui/badge"; + +const LABELS: Record = { + PENDING: "Pending", + SUCCEEDED: "Paid", + FAILED: "Failed", + REFUNDED: "Refunded", +}; + +/** Payment status for an enrollment; no payment row means free or granted by an admin. */ +export function PaymentStatusBadge({ status }: { status: AdminPaymentStatus | null }) { + if (!status) return No payment; + const variant = status === "SUCCEEDED" ? "secondary" : status === "FAILED" || status === "REFUNDED" ? "destructive" : "outline"; + return {LABELS[status]}; +} + +/** Whether money changed hands: a completed payment, or one that was later refunded. */ +export function wasCharged(status: AdminPaymentStatus | null | undefined) { + return status === "SUCCEEDED" || status === "REFUNDED"; +} + +const DISCOUNT_KIND_LABELS: Record = { + campaign: "Campaign", + instructor_coupon: "Coupon", + organization_coupon: "Org coupon", + admin_enrollment: "Admin enrollment", +}; + +/** Short badge for one coupon or campaign, e.g. "Campaign · BLACKFRIDAY · 30% off". */ +export function DiscountBadge({ discount }: { discount: AdminEnrollmentDiscount }) { + if (discount.kind === "admin_enrollment") { + return Admin enrollment · {discount.percentOff}% off; + } + const parts = [DISCOUNT_KIND_LABELS[discount.kind], discount.code ?? discount.label, `${discount.percentOff}% off`]; + return ( + + {parts.join(" · ")} + + ); +} + +export function discountKindLabel(kind: AdminEnrollmentDiscount["kind"]) { + return DISCOUNT_KIND_LABELS[kind]; +} + +const PROVIDER_LABELS: Record = { polar: "Polar", admin: "Admin", manual: "Manual" }; + +/** Who took the payment: polar, admin, manual, or another provider name as stored. */ +export function providerLabel(provider: string) { + return PROVIDER_LABELS[provider] ?? provider; +} diff --git a/frontend/src/app/(admin)/admin/users/[userId]/page.tsx b/frontend/src/app/(admin)/admin/users/[userId]/page.tsx index dd0ab1053..3ea1bddc0 100644 --- a/frontend/src/app/(admin)/admin/users/[userId]/page.tsx +++ b/frontend/src/app/(admin)/admin/users/[userId]/page.tsx @@ -1,5 +1,6 @@ import Link from "next/link"; -import type { AdminCoursesView, AdminUserDetail } from "@/shared/api/admin"; +import type { AdminCoursesView, AdminRefundBreakdown, AdminUserDetail } from "@/shared/api/admin"; +import { formatPriceCents } from "@/lib/format-price"; import { serverApiFetch, serverApiFetchOrNotFound } from "@/lib/api-server"; import { Badge } from "@/components/ui/badge"; import { AdminActionForm } from "@/components/admin/admin-action-form"; @@ -7,6 +8,7 @@ import { AdminEnrollUserDialog } from "@/components/admin/admin-enroll-user-dial import { requireRole } from "@/server/auth/guards"; import { forceVerifyEmailAction, + refundEnrollmentAction, reinstateUserAction, removeUserEnrollmentAction, revokeUserSessionsAction, @@ -28,6 +30,16 @@ import { adminSelectClassName, } from "@/components/admin/admin-ui"; +/** The confirm text for a refund: every amount, and what happens to access. */ +function refundDescription(refund: AdminRefundBreakdown, email: string, courseTitle: string) { + const money = (cents: number) => formatPriceCents(cents, refund.currency); + return ( + `${email} paid ${money(refund.paidCents)}. Polar sends back ${money(refund.refundCents)}, keeping Polar’s fees: ` + + `${money(refund.fixedFeeCents)} transaction fee, ${money(refund.internationalFeeCents)} international fee (1.5%) and ` + + `${money(refund.platformFeeCents)} Polar fee (5%), all charged by Polar. Their access to ${courseTitle} ends straight away. A refund cannot be undone.` + ); +} + function StatTile({ label, value }: { label: string; value: string | number }) { return (
@@ -310,6 +322,24 @@ export default async function AdminUserDetailPage({ {row.lastActiveAt ? new Date(row.lastActiveAt).toLocaleDateString() : "—"} +
+ {row.refund ? ( + + + + + ) : null} +
))} diff --git a/frontend/src/components/admin/admin-action-form.tsx b/frontend/src/components/admin/admin-action-form.tsx index 18a2955b5..69b4c53e8 100644 --- a/frontend/src/components/admin/admin-action-form.tsx +++ b/frontend/src/components/admin/admin-action-form.tsx @@ -43,6 +43,7 @@ export function AdminActionForm({ buttonClassName, feedbackClassName, confirm, + icon, }: { action: (state: AdminActionState, formData: FormData) => Promise; children?: React.ReactNode; @@ -55,6 +56,8 @@ export function AdminActionForm({ buttonClassName?: string; feedbackClassName?: string; confirm?: Confirmation; + /** Renders an icon-only button; `submitLabel` becomes its accessible name and tooltip. */ + icon?: React.ReactNode; }) { const [state, formAction] = useActionState(action, initial); const formRef = useRef(null); @@ -102,8 +105,10 @@ export function AdminActionForm({ // open. The confirm step validates instead. formNoValidate={confirm ? true : undefined} loadingLabel={pendingLabel ?? submitLabel} + aria-label={icon ? submitLabel : undefined} + title={icon ? submitLabel : undefined} > - {submitLabel} + {icon ?? submitLabel} {state.message ? ( diff --git a/frontend/src/components/admin/admin-workspace-shell.tsx b/frontend/src/components/admin/admin-workspace-shell.tsx index 9ebeaded4..78dd92f49 100644 --- a/frontend/src/components/admin/admin-workspace-shell.tsx +++ b/frontend/src/components/admin/admin-workspace-shell.tsx @@ -11,6 +11,7 @@ import { History, LayoutDashboard, LineChart, + Receipt, Users, Wallet, } from "lucide-react"; @@ -67,6 +68,7 @@ export function AdminWorkspaceShell({ title: "Catalog & sales", items: [ { label: "Courses", href: "/admin/courses", icon: BookOpen, active: pathname.startsWith("/admin/courses") }, + { label: "Enrollments", href: "/admin/enrollments", icon: Receipt, active: pathname.startsWith("/admin/enrollments") }, { label: "Discounts", href: "/admin/discounts", icon: BadgePercent, active: pathname.startsWith("/admin/discounts") }, ], }, diff --git a/frontend/src/server/actions/admin/enrollments.ts b/frontend/src/server/actions/admin/enrollments.ts new file mode 100644 index 000000000..37dba929c --- /dev/null +++ b/frontend/src/server/actions/admin/enrollments.ts @@ -0,0 +1,49 @@ +"use server"; + +import { revalidatePath } from "next/cache"; +import { redirect } from "next/navigation"; +import { adminCall } from "./call"; +import { runAdminAction, type AdminActionState } from "./action-result"; + +function revalidateEnrollmentPages(enrollmentId: string) { + revalidatePath("/admin/enrollments"); + revalidatePath(`/admin/enrollments/${enrollmentId}`); + revalidatePath("/admin/users", "layout"); + revalidatePath("/admin/course-access"); + revalidatePath("/admin/audit"); +} + +/** Deletes the enrollment and everything attached to it (progress, payment, certificate). */ +export async function deleteEnrollmentAction(_prev: AdminActionState, formData: FormData): Promise { + const enrollmentId = String(formData.get("enrollmentId") ?? ""); + if (!enrollmentId) return { ok: false, message: "Missing enrollment." }; + const result = await runAdminAction(async () => { + await adminCall(`/api/v1/admin/enrollments/${encodeURIComponent(enrollmentId)}`, { method: "DELETE" }); + revalidateEnrollmentPages(enrollmentId); + return "Enrollment deleted."; + }); + // From the detail page there is nothing left to show, so go back to the list. + if (result.ok && formData.get("redirectTo") === "list") redirect("/admin/enrollments"); + return result; +} + +const text = (formData: FormData, name: string) => { + const value = formData.get(name); + return typeof value === "string" ? value.trim() : ""; +}; + +/** Saves the two editable fields: course access (lifecycle) and payment status. */ +export async function updateEnrollmentAction(_prev: AdminActionState, formData: FormData): Promise { + const enrollmentId = text(formData, "enrollmentId"); + if (!enrollmentId) return { ok: false, message: "Missing enrollment." }; + const lifecycle = text(formData, "lifecycle") || undefined; + const paymentStatus = text(formData, "paymentStatus") || undefined; + return runAdminAction(async () => { + await adminCall(`/api/v1/admin/enrollments/${encodeURIComponent(enrollmentId)}`, { + method: "PATCH", + json: { lifecycle, paymentStatus }, + }); + revalidateEnrollmentPages(enrollmentId); + return "Enrollment saved."; + }); +} diff --git a/frontend/src/server/actions/admin/users.ts b/frontend/src/server/actions/admin/users.ts index 91161097a..bcc26ce11 100644 --- a/frontend/src/server/actions/admin/users.ts +++ b/frontend/src/server/actions/admin/users.ts @@ -191,6 +191,27 @@ export async function reinstateUserAction( }); } +/** + * Refunds a course paid through Polar, less the fees kept back, and ends the learner's access. + * The server works out the amount; this only asks for it. + */ +export async function refundEnrollmentAction(_prev: AdminActionState, formData: FormData): Promise { + const userId = String(formData.get("userId") ?? ""); + const enrollmentId = String(formData.get("enrollmentId") ?? ""); + if (!enrollmentId) return { ok: false, message: "Missing enrollment." }; + return runAdminAction(async () => { + await adminCall(`/api/v1/admin/enrollments/${encodeURIComponent(enrollmentId)}/refund`, { + method: "POST", + json: { reason: "customer_request" }, + }); + if (userId) revalidatePath(`/admin/users/${userId}`); + revalidatePath("/admin/users"); + revalidatePath("/admin/course-access"); + revalidatePath("/admin/audit"); + return "Refund sent through Polar and course access removed."; + }); +} + /** Removes an enrollment from a user account. */ export async function removeUserEnrollmentAction( _prev: AdminActionState, diff --git a/frontend/src/shared/api/admin.ts b/frontend/src/shared/api/admin.ts index e97fc4d1a..ee1887c69 100644 --- a/frontend/src/shared/api/admin.ts +++ b/frontend/src/shared/api/admin.ts @@ -235,10 +235,22 @@ export type AdminUserDetail = { lifecycle: EnrollmentLifecycle; percentComplete: number; lastActiveAt: string | null; + /** What a refund would return, for a course paid through Polar and not refunded yet; otherwise null. */ + refund: AdminRefundBreakdown | null; }>; coursesOwned: Array<{ id: string; title: string; slug: string; status: CourseStatus }>; }; +/** A refund less Polar’s fees on the payment: $0.50 transaction fee, 1.5% international fee, 5% Polar fee. */ +export type AdminRefundBreakdown = { + currency: string; + paidCents: number; + fixedFeeCents: number; + internationalFeeCents: number; + platformFeeCents: number; + refundCents: number; +}; + export const ADMIN_ERROR_CODES = { REQUEST_ALREADY_REVIEWED: "REQUEST_ALREADY_REVIEWED", COURSE_NOT_PUBLISHED: "COURSE_NOT_PUBLISHED", @@ -305,3 +317,78 @@ export type AdminRevenueReport = { byFundingSource: Record; }; + +export type AdminPaymentStatus = "PENDING" | "SUCCEEDED" | "FAILED" | "REFUNDED"; + +/** The money recorded for one enrollment. Every amount is in minor units of `currency`. */ +export type AdminEnrollmentPayment = { + status: AdminPaymentStatus; + currency: string; + /** What the learner is charged; for Polar this is the fixed price sent to checkout. */ + amountCents: number; + originalAmountCents: number; + discountAmountCents: number; + organizationContributionCents: number; + learnerAmountCents: number; + platformRevenueCents: number; + instructorShareCents: number; + instructorPayoutPercent: number; + instructorPayoutStatus: "NOT_DUE" | "PENDING" | "PAID"; + fundingSource: string | null; + provider: string | null; + providerRef: string | null; + paidAt: string | null; +}; + +/** A coupon or campaign applied to an enrollment's price. */ +export type AdminEnrollmentDiscount = { + /** + * campaign: a platform discount campaign; instructor_coupon: a course coupon; organization_coupon: + * from an organization's pool; admin_enrollment: an admin enrolled the learner without charge. + */ + kind: "campaign" | "instructor_coupon" | "organization_coupon" | "admin_enrollment"; + id: string; + label: string; + code: string | null; + percentOff: number; + autoApplied: boolean; + /** Organization coupons only: ISSUED, REDEEMED or CANCELLED. */ + status: string | null; + appliedAt: string | null; + organizationName: string | null; +}; + +export type AdminEnrollmentRow = { + id: string; + createdAt: string; + lifecycle: EnrollmentLifecycle; + source: "DIRECT" | "INVITE" | "SELF" | "PATHMENT"; + /** userId is null for an organization learner who has not created an account yet. */ + learner: { userId: string | null; name: string | null; email: string | null }; + course: { id: string; title: string; slug: string }; + payment: AdminEnrollmentPayment | null; + discounts: AdminEnrollmentDiscount[]; +}; + +export type AdminEnrollmentsView = { + enrollments: AdminEnrollmentRow[]; + page: AdminPageInfo; +}; + +export type AdminEnrollmentDetail = AdminEnrollmentRow & { + status: "ASSIGNED" | "IN_PROGRESS" | "COMPLETED" | "DROPPED"; + startedAt: string | null; + completedAt: string | null; + percentComplete: number; + instructor: { id: string; name: string | null; email: string }; + organization: { id: string; name: string } | null; + payment: + | (AdminEnrollmentPayment & { + createdAt: string; + updatedAt: string; + instructorPayoutPaidAt: string | null; + /** For a refunded payment, the refund less Polar's fees that our refund policy sends back. */ + refund: AdminRefundBreakdown | null; + }) + | null; +}; diff --git a/server/src/routes/v1/admin.ts b/server/src/routes/v1/admin.ts index cc361caa8..1c7bce116 100644 --- a/server/src/routes/v1/admin.ts +++ b/server/src/routes/v1/admin.ts @@ -2,7 +2,9 @@ import { instructorWithdrawalsEnabled, requireInstructorWithdrawals } from "../. import { prisma } from "../../db/prisma.js"; import { approveManualAccess, listManualInstructorPayouts, markManualInstructorPayoutPaid, rejectManualAccess } from "../../services/enrollment/manual-access.js"; import { created, noContent, ok } from "../../utils/responses.js"; -import { enrollmentParams } from "../../validations/enrollments.js"; +import { adminEnrollmentUpdateBody, enrollmentParams, refundBody } from "../../validations/enrollments.js"; +import { previewCourseRefund, refundCoursePayment } from "../../services/payments/refund-course-payment.js"; +import { getEnrollmentDetail, listEnrollments, updateEnrollment } from "../../services/admin/enrollments.js"; import { Router } from "express"; import { userRateLimit } from "../../middlewares/rate-limit.js"; import * as admin from "../../controllers/admin.js"; @@ -50,6 +52,8 @@ import { rejectWithdrawalBody, withdrawalIdParams, enrollUserBody, + listEnrollmentsQuery, + type ListEnrollmentsQuery, } from "../../validations/admin.js"; // Platform administration: organisations and their integration access, @@ -97,6 +101,23 @@ router.post("/manual-access/:enrollmentId/reject", validateParams(enrollmentPara await rejectManualAccess(req.params.enrollmentId as string, req.user!); ok(res, { rejected: true }); }); +// Every enrollment with what was charged for it, for the admin enrollments page. +router.get("/enrollments", validateQuery(listEnrollmentsQuery), async (req, res) => { + ok(res, await listEnrollments(req.query as ListEnrollmentsQuery)); +}); +router.get("/enrollments/:enrollmentId", validateParams(enrollmentParams), async (req, res) => { + ok(res, await getEnrollmentDetail(req.params.enrollmentId as string)); +}); +router.patch("/enrollments/:enrollmentId", validate({ params: enrollmentParams, body: adminEnrollmentUpdateBody }), async (req, res) => { + ok(res, await updateEnrollment(req.user!, req.params.enrollmentId as string, req.body)); +}); +// Refunds return the payment less the card fees kept back (refund-policy.ts) and end course access. +router.get("/enrollments/:enrollmentId/refund", validateParams(enrollmentParams), async (req, res) => { + ok(res, await previewCourseRefund(req.params.enrollmentId as string)); +}); +router.post("/enrollments/:enrollmentId/refund", validateParams(enrollmentParams), validateBody(refundBody), async (req, res) => { + ok(res, await refundCoursePayment(req.params.enrollmentId as string, req.user!, req.body)); +}); router.get("/manual-payouts", async (_req, res) => ok(res, await listManualInstructorPayouts())); router.post("/manual-payouts/:enrollmentId/paid", validateParams(enrollmentParams), async (req, res) => { await markManualInstructorPayoutPaid(req.params.enrollmentId as string, req.user!); diff --git a/server/src/routes/webhook/polar.ts b/server/src/routes/webhook/polar.ts index f3882bde0..d9d3a954a 100644 --- a/server/src/routes/webhook/polar.ts +++ b/server/src/routes/webhook/polar.ts @@ -2,8 +2,13 @@ import { Router, type Request, type Response } from "express"; import { webhooks } from "@polar-sh/sdk/2026-10"; import { env } from "../../config/env.js"; import { fulfillPolarOrderPaid } from "../../services/payments/fulfill-polar-order.js"; +import { revokePolarOrderRefund } from "../../services/payments/refund-polar-order.js"; import { logger } from "../../utils/logger.js"; +function orderMetadata(metadata: unknown): Record | null { + return metadata && typeof metadata === "object" && !Array.isArray(metadata) ? (metadata as Record) : null; +} + const router = Router(); function webhookHeaders(req: Request): Record { @@ -45,18 +50,22 @@ router.post("/", async (req: Request, res: Response) => { try { if (event.type === "order.paid") { const order = event.data; - const metadata = - order.metadata && typeof order.metadata === "object" && !Array.isArray(order.metadata) - ? (order.metadata as Record) - : null; await fulfillPolarOrderPaid({ orderId: order.id, checkoutId: order.checkout_id, - metadata, + metadata: orderMetadata(order.metadata), }); } else if (event.type === "order.refunded") { - // Product is non-refundable; keep access and log for ops visibility. - logger.info({ orderId: event.data.id, type: event.type }, "polar refund event ignored (non-refundable product)"); + // A full refund removes course access; a partial one keeps it (see revokePolarOrderRefund). + const order = event.data; + await revokePolarOrderRefund({ + orderId: order.id, + checkoutId: order.checkout_id, + metadata: orderMetadata(order.metadata), + status: order.status, + refundedAmount: order.refunded_amount, + totalAmount: order.total_amount, + }); } res.status(200).json({ received: true }); } catch (error) { diff --git a/server/src/services/admin/audit.ts b/server/src/services/admin/audit.ts index 9371387f6..95c2318ab 100644 --- a/server/src/services/admin/audit.ts +++ b/server/src/services/admin/audit.ts @@ -23,6 +23,7 @@ export const ADMIN_AUDIT_ACTIONS = { MANUAL_ACCESS_APPROVE: "manual-access.approve", MANUAL_ACCESS_REJECT: "manual-access.reject", MANUAL_INSTRUCTOR_PAYOUT_PAID: "manual-instructor-payout.paid", + PAYMENT_REFUND: "payment.refund", INSTRUCTOR_WITHDRAWAL_PAID: "instructor-withdrawal.paid", INSTRUCTOR_WITHDRAWAL_REJECT: "instructor-withdrawal.reject", ORGANIZATION_GRANT_CREDITS: "organization.grant-credits", @@ -43,6 +44,7 @@ export const ADMIN_AUDIT_ACTIONS = { USER_REINSTATE: "user.reinstate", USER_ENROLL: "user.enroll", USER_REMOVE_ENROLLMENT: "user.remove-enrollment", + ENROLLMENT_UPDATE: "enrollment.update", MFA_ENABLE: "mfa.enable", MFA_DISABLE: "mfa.disable", MFA_RESET: "mfa.reset", diff --git a/server/src/services/admin/enrollments.ts b/server/src/services/admin/enrollments.ts new file mode 100644 index 000000000..cb29bc646 --- /dev/null +++ b/server/src/services/admin/enrollments.ts @@ -0,0 +1,298 @@ +import type { Prisma } from "../../generated/prisma/index.js"; +import { prisma } from "../../db/prisma.js"; +import type { + AdminEnrollmentDetail, + AdminEnrollmentDiscount, + AdminEnrollmentPayment, + AdminEnrollmentRow, + AdminEnrollmentsView, +} from "../../shared/api/admin.js"; +import { ConflictError, NotFoundError } from "../../utils/errors.js"; +import type { AdminEnrollmentUpdateBody } from "../../validations/enrollments.js"; +import { ADMIN_AUDIT_ACTIONS, recordAdminAction, type AdminActor } from "./audit.js"; +import type { ListEnrollmentsQuery } from "../../validations/admin.js"; +import { refundBreakdown } from "../payments/refund-policy.js"; +import { pageInfo, resolvePaging } from "./paging.js"; + +// Every enrollment with the money recorded against it, so an admin can see what each learner paid. + +const paymentSelect = { + status: true, + currency: true, + amountCents: true, + originalAmountCents: true, + discountAmountCents: true, + organizationContributionCents: true, + learnerAmountCents: true, + platformRevenueCents: true, + instructorShareCents: true, + instructorPayoutPercent: true, + instructorPayoutStatus: true, + fundingSource: true, + provider: true, + providerRef: true, + paidAt: true, +} satisfies Prisma.PaymentSelect; + +const rowSelect = { + id: true, + createdAt: true, + lifecycle: true, + source: true, + user: { select: { id: true, name: true, email: true } }, + learnerProfile: { select: { email: true } }, + course: { select: { id: true, title: true, slug: true } }, + payment: { select: paymentSelect }, + instructorCouponRedemption: { + select: { + percentOff: true, + redeemedAt: true, + coupon: { + select: { + id: true, + label: true, + code: true, + autoApply: true, + campaign: { select: { id: true, label: true, code: true, autoApply: true } }, + }, + }, + }, + }, + couponUsage: { + select: { + status: true, + percentOff: true, + displayLabel: true, + issuedAt: true, + redeemedAt: true, + pool: { select: { id: true, label: true, code: true } }, + organization: { select: { name: true } }, + }, + }, +} satisfies Prisma.EnrollmentSelect; + +type RowRecord = Prisma.EnrollmentGetPayload<{ select: typeof rowSelect }>; +type PaymentRecord = Prisma.PaymentGetPayload<{ select: typeof paymentSelect }>; + +/** Admin enrollments carry a payment row with this provider (see adminWaiverSnapshot). */ +export const ADMIN_ENROLLMENT_PROVIDER = "admin"; + +const HAS_COUPON: Prisma.EnrollmentWhereInput = { + OR: [{ instructorCouponRedemption: { isNot: null } }, { couponUsage: { isNot: null } }], +}; +const IS_ADMIN_ENROLLMENT: Prisma.EnrollmentWhereInput = { payment: { is: { provider: ADMIN_ENROLLMENT_PROVIDER } } }; +const DISCOUNT_FILTERS: Record, Prisma.EnrollmentWhereInput> = { + true: HAS_COUPON, + admin: IS_ADMIN_ENROLLMENT, + false: { NOT: { OR: [HAS_COUPON, IS_ADMIN_ENROLLMENT] } }, +}; + +/** Coupons and campaigns behind an enrollment's discount; an empty list means full price. */ +function toDiscounts(row: Pick): AdminEnrollmentDiscount[] { + const discounts: AdminEnrollmentDiscount[] = []; + const payment = row.payment; + if (payment?.provider === ADMIN_ENROLLMENT_PROVIDER) { + discounts.push({ + kind: "admin_enrollment", + id: row.id, + label: "Admin enrollment", + code: null, + percentOff: payment.originalAmountCents > 0 ? Math.round((payment.discountAmountCents / payment.originalAmountCents) * 100) : 100, + autoApplied: false, + status: null, + appliedAt: payment.paidAt?.toISOString() ?? null, + organizationName: null, + }); + } + const redemption = row.instructorCouponRedemption; + if (redemption) { + const { coupon } = redemption; + const base = { percentOff: redemption.percentOff, status: null, appliedAt: redemption.redeemedAt.toISOString(), organizationName: null }; + discounts.push( + coupon.campaign + ? { + ...base, + kind: "campaign", + id: coupon.campaign.id, + label: coupon.campaign.label, + code: coupon.campaign.code ?? coupon.code, + autoApplied: coupon.campaign.autoApply, + } + : { ...base, kind: "instructor_coupon", id: coupon.id, label: coupon.label, code: coupon.code, autoApplied: coupon.autoApply }, + ); + } + const usage = row.couponUsage; + if (usage) { + discounts.push({ + kind: "organization_coupon", + id: usage.pool.id, + label: usage.displayLabel || usage.pool.label, + code: usage.pool.code, + percentOff: usage.percentOff, + autoApplied: false, + status: usage.status, + appliedAt: (usage.redeemedAt ?? usage.issuedAt).toISOString(), + organizationName: usage.organization.name, + }); + } + return discounts; +} + +function buildEnrollmentWhere(filters: ListEnrollmentsQuery): Prisma.EnrollmentWhereInput { + const contains = (value: string) => ({ contains: value, mode: "insensitive" as const }); + const discount = filters.discount ? DISCOUNT_FILTERS[filters.discount] : null; + return { + ...(discount ? { AND: [discount] } : {}), + ...(filters.lifecycle ? { lifecycle: filters.lifecycle } : {}), + ...(filters.payment === "NONE" + ? { payment: { is: null } } + : filters.payment + ? { payment: { is: { status: filters.payment } } } + : {}), + ...(filters.query + ? { + OR: [ + { user: { is: { email: contains(filters.query) } } }, + { user: { is: { name: contains(filters.query) } } }, + { learnerProfile: { is: { email: contains(filters.query) } } }, + { course: { title: contains(filters.query) } }, + ], + } + : {}), + }; +} + +function toPayment(payment: PaymentRecord): AdminEnrollmentPayment { + return { ...payment, paidAt: payment.paidAt?.toISOString() ?? null }; +} + +function toRow(row: RowRecord): AdminEnrollmentRow { + return { + id: row.id, + createdAt: row.createdAt.toISOString(), + lifecycle: row.lifecycle, + source: row.source, + learner: { + userId: row.user?.id ?? null, + name: row.user?.name ?? null, + email: row.user?.email ?? row.learnerProfile?.email ?? null, + }, + course: row.course, + payment: row.payment ? toPayment(row.payment) : null, + discounts: toDiscounts(row), + }; +} + +export async function listEnrollments(filters: ListEnrollmentsQuery = {}): Promise { + const where = buildEnrollmentWhere(filters); + const paging = resolvePaging(filters, await prisma.enrollment.count({ where })); + const rows = await prisma.enrollment.findMany({ + where, + orderBy: [{ createdAt: "desc" }, { id: "desc" }], + skip: paging.skip, + take: paging.take, + select: rowSelect, + }); + return { enrollments: rows.map(toRow), page: pageInfo(paging) }; +} + +export async function getEnrollmentDetail(enrollmentId: string): Promise { + const row = await prisma.enrollment.findUnique({ + where: { id: enrollmentId }, + select: { + ...rowSelect, + status: true, + startedAt: true, + completedAt: true, + percentComplete: true, + organization: { select: { id: true, name: true } }, + course: { select: { id: true, title: true, slug: true, mentor: { select: { id: true, name: true, email: true } } } }, + payment: { select: { ...paymentSelect, createdAt: true, updatedAt: true, instructorPayoutPaidAt: true } }, + }, + }); + if (!row) throw new NotFoundError("Enrollment not found"); + + const { mentor, ...course } = row.course; + const base = toRow({ ...row, course, payment: null }); + const payment = row.payment; + return { + ...base, + discounts: toDiscounts(row), + status: row.status, + startedAt: row.startedAt?.toISOString() ?? null, + completedAt: row.completedAt?.toISOString() ?? null, + percentComplete: row.percentComplete, + instructor: mentor, + organization: row.organization, + payment: payment + ? { + ...toPayment(payment), + createdAt: payment.createdAt.toISOString(), + updatedAt: payment.updatedAt.toISOString(), + instructorPayoutPaidAt: payment.instructorPayoutPaidAt?.toISOString() ?? null, + refund: + payment.status === "REFUNDED" && payment.provider === "polar" + ? { currency: payment.currency, ...refundBreakdown(payment.amountCents) } + : null, + } + : null, + }; +} + +/** + * Admin edit of an enrollment's course access (lifecycle) and its payment status. Access follows + * `lifecycle` as stored, so this grants or ends access by hand. It only changes our records; no + * money moves through Polar. + */ +export async function updateEnrollment( + actor: AdminActor, + enrollmentId: string, + body: AdminEnrollmentUpdateBody, +): Promise { + const existing = await prisma.enrollment.findUnique({ + where: { id: enrollmentId }, + select: { + lifecycle: true, + course: { select: { title: true } }, + user: { select: { email: true } }, + learnerProfile: { select: { email: true } }, + payment: { select: { status: true, paidAt: true } }, + }, + }); + if (!existing) throw new NotFoundError("Enrollment not found"); + if (body.paymentStatus && !existing.payment) { + throw new ConflictError("This enrollment has no payment record, so there is no payment status to change.", "NO_PAYMENT"); + } + + await prisma.$transaction(async (tx) => { + if (body.lifecycle && body.lifecycle !== existing.lifecycle) { + await tx.enrollment.update({ where: { id: enrollmentId }, data: { lifecycle: body.lifecycle } }); + } + if (body.paymentStatus && body.paymentStatus !== existing.payment?.status) { + await tx.payment.update({ + where: { enrollmentId }, + data: { + status: body.paymentStatus, + // Marking a payment completed for the first time records it as paid now. + ...(body.paymentStatus === "SUCCEEDED" && !existing.payment?.paidAt ? { paidAt: new Date() } : {}), + }, + }); + } + await recordAdminAction(tx, { + actor, + action: ADMIN_AUDIT_ACTIONS.ENROLLMENT_UPDATE, + targetType: "Enrollment", + targetId: enrollmentId, + summary: `Edited ${existing.user?.email ?? existing.learnerProfile?.email ?? "learner"}'s enrollment in ${existing.course.title}`, + metadata: { + before: { lifecycle: existing.lifecycle, paymentStatus: existing.payment?.status ?? null }, + after: { + lifecycle: body.lifecycle ?? existing.lifecycle, + paymentStatus: body.paymentStatus ?? existing.payment?.status ?? null, + }, + }, + }); + }); + + return getEnrollmentDetail(enrollmentId); +} diff --git a/server/src/services/admin/users.ts b/server/src/services/admin/users.ts index 1fe4399b7..5ebaa9091 100644 --- a/server/src/services/admin/users.ts +++ b/server/src/services/admin/users.ts @@ -1,4 +1,5 @@ -import type { AdminBulkResult, AdminUserDetail, AdminUsersView } from "../../shared/api/admin.js"; +import type { AdminBulkResult, AdminRefundBreakdown, AdminUserDetail, AdminUsersView } from "../../shared/api/admin.js"; +import { refundBreakdown } from "../payments/refund-policy.js"; import { ADMIN_ERROR_CODES } from "../../shared/api/admin.js"; import type { Prisma } from "../../generated/prisma/index.js"; import { prisma } from "../../db/prisma.js"; @@ -153,6 +154,18 @@ export async function exportUsers(filters: ListUsersQuery = {}): Promise 0 ? { currency: payment.currency, ...breakdown } : null; +} + export async function getUserDetail(userId: string): Promise { const user = await prisma.user.findUnique({ where: { id: userId }, @@ -186,6 +199,7 @@ export async function getUserDetail(userId: string): Promise { percentComplete: true, lastActiveAt: true, course: { select: { title: true, slug: true } }, + payment: { select: { provider: true, providerRef: true, status: true, amountCents: true, currency: true } }, }, }, coursesOwned: { @@ -222,6 +236,7 @@ export async function getUserDetail(userId: string): Promise { lifecycle: row.lifecycle, percentComplete: row.percentComplete, lastActiveAt: row.lastActiveAt?.toISOString() ?? null, + refund: refundOffer(row.payment), })), coursesOwned: user.coursesOwned, }; diff --git a/server/src/services/catalog/catalog.ts b/server/src/services/catalog/catalog.ts index 175a5e78c..111be5a32 100644 --- a/server/src/services/catalog/catalog.ts +++ b/server/src/services/catalog/catalog.ts @@ -3,6 +3,7 @@ import { prisma } from "../../db/prisma.js"; import { NotFoundError } from "../../utils/errors.js"; import { resolveCourseFamily } from "../../shared/lib/course-tracks.js"; import { enrollmentGrantsContentAccess } from "../enrollment/lifecycle.js"; +import { isCourseInstructor } from "../enrollment/own-course.js"; import { readReleaseContent, variantForRelease, type ReleaseModule } from "../courses/releases.js"; const summarySelect = { @@ -20,6 +21,7 @@ const summarySelect = { pricingType: true, priceCents: true, currency: true, + mentorId: true, mentor: { select: { name: true } }, ratingAverage: true, ratingCount: true, @@ -71,7 +73,7 @@ export async function listCatalog(userId: string | undefined): Promise { + return courses.map(({ mentor, mentorId: _mentorId, _count, familySlug: _family, variantFamily: _variants, activeReleaseId: _release, ...course }) => { const modules = releaseModules.get(course.id); return { ...course, @@ -113,7 +115,7 @@ export async function getCatalogCourse(courseSlug: string, userId: string | unde select: { lifecycle: true }, }) : null; - const { mentor, _count, status: _status, familySlug: _family, variantFamily: _variants, activeReleaseId: _release, ...rest } = course; + const { mentor, mentorId, _count, status: _status, familySlug: _family, variantFamily: _variants, activeReleaseId: _release, ...rest } = course; const releaseModules = (await activeReleaseModules([course])).get(course.id); const modules = releaseModules ? releaseModules.map((module) => ({ @@ -133,7 +135,10 @@ export async function getCatalogCourse(courseSlug: string, userId: string | unde moduleCount: modules.length, chapterCount: modules.reduce((sum, module) => sum + module.chapters.length, 0), enrollmentLifecycle: enrollment?.lifecycle ?? null, - access: !enrollment + // The course's instructor opens it free (see own-course.ts), so the catalog never asks them to pay. + access: isCourseInstructor(userId, { mentorId }) + ? "active" + : !enrollment ? "none" : enrollmentGrantsContentAccess(enrollment.lifecycle) ? "active" diff --git a/server/src/services/courses/overview.ts b/server/src/services/courses/overview.ts index 54ace1cb7..2540c7739 100644 --- a/server/src/services/courses/overview.ts +++ b/server/src/services/courses/overview.ts @@ -5,6 +5,7 @@ import { BadRequestError, NotFoundError } from "../../utils/errors.js"; import type { SessionUser } from "../../types/auth.js"; import { shouldBypassProgressGating } from "../auth/seed-access.js"; import { enrollmentGrantsContentAccess } from "../enrollment/lifecycle.js"; +import { ensureOwnCourseEnrollment, isCourseInstructor } from "../enrollment/own-course.js"; import { redeemCouponOnCourseOpen } from "../coupons/redeem.js"; import { pickDefaultOpenModule, resolveContinueChapterPath, syllabusForEnrollment } from "../progress/enrollment-syllabus.js"; import { releaseForEnrollment, releaseModulesWithBlocks, upgradeEnrollmentToRelease } from "./releases.js"; @@ -29,6 +30,7 @@ export async function getCourseOverview(courseSlug: string, user: SessionUser): availableVariantSlugs: true, status: true, activeReleaseId: true, + mentorId: true, mentor: { select: { name: true } }, modules: { where: { archivedAt: null }, @@ -54,12 +56,15 @@ export async function getCourseOverview(courseSlug: string, user: SessionUser): }); if (!course) throw new NotFoundError("Course not found"); - const { mentor, modules: courseModules, sequential, familySlug, variantFamily, availableVariantSlugs, activeReleaseId, ...courseFields } = course; + const { mentor, mentorId: _mentorId, modules: courseModules, sequential, familySlug, variantFamily, availableVariantSlugs, activeReleaseId, ...courseFields } = course; const base = { course: { ...courseFields, instructorName: mentor.name } }; - const enrollment = await prisma.enrollment.findUnique({ - where: { courseId_userId: { courseId: course.id, userId: user.id } }, - }); + // The course's instructor opens it free, so they are never shown a payment step (see own-course.ts). + const enrollment = isCourseInstructor(user.id, course) + ? await ensureOwnCourseEnrollment(prisma, { courseId: course.id, userId: user.id }) + : await prisma.enrollment.findUnique({ + where: { courseId_userId: { courseId: course.id, userId: user.id } }, + }); const myRatingRow = await prisma.courseRating.findUnique({ where: { courseId_userId: { courseId: course.id, userId: user.id } }, select: { rating: true, review: true, updatedAt: true }, diff --git a/server/src/services/enrollment/checkout.ts b/server/src/services/enrollment/checkout.ts index cccf8573e..8dc8eaf2d 100644 --- a/server/src/services/enrollment/checkout.ts +++ b/server/src/services/enrollment/checkout.ts @@ -19,13 +19,19 @@ export async function loadCheckout(courseSlug: string, userId: string): Promise< priceCents: true, currency: true, status: true, + mentorId: true, mentor: { select: { name: true } }, }, }); if (!course || course.status !== "PUBLISHED") throw new NotFoundError("Course not found"); - const { status: _status, mentor, ...rest } = course; + const { status: _status, mentor, mentorId, ...rest } = course; const courseFields = { ...rest, instructorName: mentor.name }; + // The instructor never pays for their own course; the checkout page sends them to the course. + if (mentorId === userId) { + return { course: courseFields, enrollment: null, state: "already_paid", automaticDiscount: null, organizationDiscount: null, amountDueCents: 0 }; + } + const enrollment = await prisma.enrollment.findUnique({ where: { courseId_userId: { courseId: course.id, userId } }, select: { id: true, lifecycle: true, payment: { select: { amountCents: true } }, instructorCouponRedemption: { select: { id: true } }, couponUsage: { select: { status: true, percentOff: true, displayLabel: true } } }, diff --git a/server/src/services/enrollment/create-self-enrollment.ts b/server/src/services/enrollment/create-self-enrollment.ts index 8b167989b..2eb7de1d4 100644 --- a/server/src/services/enrollment/create-self-enrollment.ts +++ b/server/src/services/enrollment/create-self-enrollment.ts @@ -3,6 +3,7 @@ import { assignmentForNewEnrollment } from "../courses/variant-assignment.js"; import { lifecycleForSignedInEnrollment } from "./lifecycle.js"; import { rankLearnerCoupons } from "../financials/coupon-priority.js"; import { settleAssignment } from "../financials/settlement.js"; +import { ensureOwnCourseEnrollment, isCourseInstructor } from "./own-course.js"; export class SelfEnrollmentError extends Error { readonly code: @@ -26,6 +27,8 @@ export type SelfEnrollmentResult = { lifecycle: ReturnType; created: boolean; couponApplied?: boolean; + /** The learner is the course's instructor: free access, no payment, no new-enrollment notice. */ + ownCourse?: boolean; }; export async function createSelfEnrollment( @@ -42,6 +45,7 @@ export async function createSelfEnrollment( priceCents: true, currency: true, instructorPayoutPercent: true, + mentorId: true, }, }); if (!course) throw new SelfEnrollmentError("COURSE_NOT_FOUND", "Course not found."); @@ -49,6 +53,11 @@ export async function createSelfEnrollment( throw new SelfEnrollmentError("NOT_PUBLISHED", "This course is not open for enrollment."); } + if (isCourseInstructor(input.userId, course)) { + const row = await ensureOwnCourseEnrollment(db, { courseId: course.id, userId: input.userId }); + return { enrollmentId: row.id, courseSlug: course.slug, lifecycle: "ACTIVE", created: false, couponApplied: false, ownCourse: true }; + } + const couponCode = input.couponCode?.trim().toUpperCase(); const defaultLifecycle = lifecycleForSignedInEnrollment(course.pricingType); diff --git a/server/src/services/enrollment/own-course.ts b/server/src/services/enrollment/own-course.ts new file mode 100644 index 000000000..c37bdd5a7 --- /dev/null +++ b/server/src/services/enrollment/own-course.ts @@ -0,0 +1,32 @@ +import type { Enrollment, Prisma, PrismaClient } from "../../generated/prisma/index.js"; +import { enrollmentGrantsContentAccess } from "./lifecycle.js"; + +type Db = PrismaClient | Prisma.TransactionClient; + +/** The instructor of a course never pays for it: they get the same free access as the instructor preview. */ +export function isCourseInstructor(userId: string | undefined | null, course: { mentorId: string }): boolean { + return Boolean(userId) && course.mentorId === userId; +} + +/** + * Opens the instructor's own course for them, with no payment and no coupon, matching the instructor + * preview in resolve-learn-enrollment.ts. Reuses an earlier enrollment (for example one left awaiting + * payment) instead of making a second one. A payment row it already has is left as it is. + */ +export async function ensureOwnCourseEnrollment(db: Db, input: { courseId: string; userId: string }): Promise { + const where = { courseId_userId: { courseId: input.courseId, userId: input.userId } }; + const existing = await db.enrollment.findUnique({ where }); + if (existing && enrollmentGrantsContentAccess(existing.lifecycle)) return existing; + if (existing) { + return db.enrollment.update({ + where: { id: existing.id }, + data: { lifecycle: "ACTIVE", status: "IN_PROGRESS", startedAt: existing.startedAt ?? new Date() }, + }); + } + // upsert so two tabs opening the course at once do not trip the (courseId, userId) unique key. + return db.enrollment.upsert({ + where, + create: { ...input, lifecycle: "ACTIVE", status: "IN_PROGRESS", source: "DIRECT", startedAt: new Date() }, + update: {}, + }); +} diff --git a/server/src/services/enrollment/resolve-learn-enrollment.ts b/server/src/services/enrollment/resolve-learn-enrollment.ts index bc2b8cc58..759c2b6e6 100644 --- a/server/src/services/enrollment/resolve-learn-enrollment.ts +++ b/server/src/services/enrollment/resolve-learn-enrollment.ts @@ -3,6 +3,8 @@ import { prisma } from "../../db/prisma.js"; import { NotFoundError } from "../../utils/errors.js"; import { isMentorOfCourse } from "../auth/access-rules.js"; import { enrollmentGrantsContentAccess } from "./lifecycle.js"; +import { adminWaiverSnapshot } from "../financials/settlement.js"; +import { ensureOwnCourseEnrollment, isCourseInstructor } from "./own-course.js"; export type LearnAccessDenial = | "not_enrolled" @@ -27,10 +29,15 @@ export async function resolveLearnEnrollment( ): Promise { const course = await prisma.course.findUnique({ where: { id: courseId }, - select: { id: true, mentorId: true }, + select: { id: true, mentorId: true, priceCents: true, pricingType: true }, }); if (!course) throw new NotFoundError("Course not found"); + // The course's own instructor always gets in free, even over an earlier enrollment left awaiting payment. + if (isCourseInstructor(user.id, course)) { + return ensureOwnCourseEnrollment(prisma, { courseId, userId: user.id }); + } + let enrollment = await prisma.enrollment.findUnique({ where: { courseId_userId: { courseId, userId: user.id } }, }); @@ -44,6 +51,11 @@ export async function resolveLearnEnrollment( status: "IN_PROGRESS", source: "DIRECT", startedAt: new Date(), + // An admin previewing a course gets the same no-charge record as an admin enrollment, + // so the admin enrollments page labels it. Instructors previewing their own course get none. + ...(user.role === "ADMIN" + ? { payment: { create: adminWaiverSnapshot({ originalAmountCents: course.priceCents, pricingType: course.pricingType }) } } + : {}), }, }); } diff --git a/server/src/services/enrollment/self-enroll.ts b/server/src/services/enrollment/self-enroll.ts index b407c3463..1cf394269 100644 --- a/server/src/services/enrollment/self-enroll.ts +++ b/server/src/services/enrollment/self-enroll.ts @@ -9,7 +9,7 @@ import { SelfEnrollmentError, createSelfEnrollment } from "./create-self-enrollm export async function selfEnroll(userId: string, courseId: string, couponCode?: string): Promise { try { const result = await createSelfEnrollment(prisma, { userId, courseId, couponCode }); - if (result.created) await dispatchNotification(() => notifyMentorNewEnrollment(result.enrollmentId)); + if (result.created && !result.ownCourse) await dispatchNotification(() => notifyMentorNewEnrollment(result.enrollmentId)); return result; } catch (error) { if (!(error instanceof SelfEnrollmentError)) throw error; diff --git a/server/src/services/payments/create-course-checkout.ts b/server/src/services/payments/create-course-checkout.ts index 5820b8c37..ab1fc08b7 100644 --- a/server/src/services/payments/create-course-checkout.ts +++ b/server/src/services/payments/create-course-checkout.ts @@ -24,12 +24,15 @@ export async function createCourseCheckout( where: { id: enrollmentId, userId }, include: { user: { select: { id: true, email: true, name: true } }, - course: { select: { id: true, slug: true, title: true, description: true, status: true, pricingType: true, priceCents: true, currency: true } }, + course: { select: { id: true, slug: true, title: true, description: true, status: true, pricingType: true, priceCents: true, currency: true, mentorId: true } }, payment: true, }, }); if (!enrollment || !enrollment.user) throw new NotFoundError("Enrollment not found"); if (enrollment.userId !== userId) throw new ForbiddenError("You do not own this enrollment."); + if (enrollment.course.mentorId === userId) { + throw new ConflictError("Instructors do not pay for their own course.", "PAYMENT_NOT_REQUIRED"); + } if (enrollment.lifecycle !== "PAYMENT_REQUIRED") { throw new ConflictError("This enrollment is not awaiting payment.", "PAYMENT_NOT_REQUIRED"); } diff --git a/server/src/services/payments/refund-course-payment.ts b/server/src/services/payments/refund-course-payment.ts new file mode 100644 index 000000000..d9f587ab7 --- /dev/null +++ b/server/src/services/payments/refund-course-payment.ts @@ -0,0 +1,73 @@ +import { prisma } from "../../db/prisma.js"; +import { ADMIN_AUDIT_ACTIONS, recordAdminAction, type AdminActor } from "../admin/audit.js"; +import { BadRequestError, ConflictError, NotFoundError } from "../../utils/errors.js"; +import { getPolarClient, requirePolarConfig } from "./polar.js"; +import { endAccessForRefund } from "./refund-polar-order.js"; +import { refundBreakdown, type RefundBreakdown } from "./refund-policy.js"; + +export const REFUND_REASONS = ["customer_request", "duplicate", "fraudulent", "service_disruption", "satisfaction_guarantee", "other"] as const; +export type RefundReasonInput = (typeof REFUND_REASONS)[number]; + +export type CourseRefundResult = RefundBreakdown & { refundId: string; enrollmentId: string }; + +/** What a refund of this enrollment would return, without making it. For a confirm screen. */ +export async function previewCourseRefund(enrollmentId: string): Promise { + const payment = await refundablePayment(enrollmentId); + return refundBreakdown(payment.amountCents); +} + +/** + * Refund a course bought through Polar, keeping back Polar’s payment fees (see refund-policy.ts), and + * end the learner's access straight away. Polar then sends order.refunded; that webhook finds the + * payment already REFUNDED and changes nothing. + */ +export async function refundCoursePayment( + enrollmentId: string, + actor: AdminActor, + input: { reason?: RefundReasonInput; comment?: string | null } = {}, +): Promise { + requirePolarConfig(); + const payment = await refundablePayment(enrollmentId); + const breakdown = refundBreakdown(payment.amountCents); + if (breakdown.refundCents < 1) { + throw new BadRequestError("The fees kept back are as much as the payment, so there is nothing to refund.", "REFUND_TOO_SMALL"); + } + + const refund = await getPolarClient().refunds.create({ + order_id: payment.providerRef, + amount: breakdown.refundCents, + reason: input.reason ?? "customer_request", + comment: + input.comment?.trim() || + `Refund less Polar fees: transaction ${breakdown.fixedFeeCents}, international ${breakdown.internationalFeeCents}, Polar ${breakdown.platformFeeCents} cents.`, + metadata: { enrollmentId, refundedBy: actor.id }, + }); + + // The money has gone back. If the database write below fails, the order.refunded webhook still + // ends access, because the refund it reports is at the policy amount. + await prisma.$transaction(async (tx) => { + await endAccessForRefund(tx, { id: enrollmentId, payment: { ...payment, provider: "polar" } }); + await recordAdminAction(tx, { + actor, + action: ADMIN_AUDIT_ACTIONS.PAYMENT_REFUND, + targetType: "Enrollment", + targetId: enrollmentId, + summary: `Refunded ${breakdown.refundCents} of ${breakdown.paidCents} cents through Polar and removed course access.`, + metadata: { refundId: refund.id, orderId: payment.providerRef, ...breakdown, reason: input.reason ?? "customer_request" }, + }); + }); + + return { ...breakdown, refundId: refund.id, enrollmentId }; +} + +async function refundablePayment(enrollmentId: string) { + const enrollment = await prisma.enrollment.findUnique({ where: { id: enrollmentId }, include: { payment: true } }); + if (!enrollment) throw new NotFoundError("Enrollment not found"); + const payment = enrollment.payment; + if (!payment || payment.provider !== "polar" || !payment.providerRef) { + throw new ConflictError("This enrollment was not paid through Polar, so it cannot be refunded here.", "NOT_A_POLAR_PAYMENT"); + } + if (payment.status === "REFUNDED") throw new ConflictError("This payment has already been refunded.", "ALREADY_REFUNDED"); + if (payment.status !== "SUCCEEDED") throw new ConflictError("Only a completed payment can be refunded.", "PAYMENT_NOT_COMPLETED"); + return { ...payment, providerRef: payment.providerRef }; +} diff --git a/server/src/services/payments/refund-polar-order.ts b/server/src/services/payments/refund-polar-order.ts new file mode 100644 index 000000000..819757c91 --- /dev/null +++ b/server/src/services/payments/refund-polar-order.ts @@ -0,0 +1,104 @@ +import type { Prisma } from "../../generated/prisma/index.js"; +import { prisma } from "../../db/prisma.js"; +import { logger } from "../../utils/logger.js"; +import { refundEndsAccess } from "./refund-policy.js"; + +export type PolarOrderRefundedInput = { + orderId: string; + checkoutId: string | null; + metadata: Record | null | undefined; + /** Polar's order status after the refund: "refunded" or "partially_refunded". */ + status: string; + refundedAmount: number; + totalAmount: number; +}; + +export type PolarRefundOutcome = + | { revoked: true; enrollmentId: string } + | { revoked: false; enrollmentId: string | null; reason: "no-enrollment" | "goodwill" | "already-refunded" | "not-polar" }; + +type RefundableEnrollment = { + id: string; + payment: { status: string; provider: string | null; instructorPayoutStatus: string; instructorShareCents: number } | null; +}; + +function metadataString(metadata: Record | null | undefined, key: string): string | null { + const value = metadata?.[key]; + return typeof value === "string" && value.trim() ? value.trim() : null; +} + +/** + * End course access for a refunded payment: the enrollment becomes CANCELLED + DROPPED (as an + * admin removal does, so the learner can enrol again), the payment REFUNDED, and an instructor + * payout not yet paid is no longer owed. Guarded on the payment still being SUCCEEDED, so the admin + * refund and Polar's webhook can both call it and only the first one changes anything. + * Returns whether this call made the change. + */ +export async function endAccessForRefund(tx: Prisma.TransactionClient, enrollment: RefundableEnrollment): Promise { + const payoutAlreadyPaid = enrollment.payment?.instructorPayoutStatus === "PAID"; + const refunded = await tx.payment.updateMany({ + where: { enrollmentId: enrollment.id, status: "SUCCEEDED" }, + data: { + status: "REFUNDED", + // A payout already paid stays recorded as paid; it needs a manual adjustment (logged below). + ...(payoutAlreadyPaid ? {} : { instructorPayoutStatus: "NOT_DUE" as const }), + }, + }); + if (!refunded.count) return false; + await tx.enrollment.update({ + where: { id: enrollment.id }, + data: { lifecycle: "CANCELLED", status: "DROPPED" }, + }); + if (payoutAlreadyPaid) + logger.warn( + { enrollmentId: enrollment.id, instructorShareCents: enrollment.payment?.instructorShareCents }, + "refund after the instructor share was paid out: needs a manual adjustment", + ); + return true; +} + +/** + * Polar reported order.refunded. A refund at or above the refund policy amount (paid minus the + * Polar’s payment fees kept back) ends access; a smaller one is goodwill and access stays. Idempotent, + * because Polar retries webhooks and the admin refund may already have ended access. + */ +export async function revokePolarOrderRefund(input: PolarOrderRefundedInput): Promise { + const enrollmentIdFromMeta = metadataString(input.metadata, "enrollmentId"); + const include = { payment: true } as const; + + const enrollment = + (enrollmentIdFromMeta ? await prisma.enrollment.findUnique({ where: { id: enrollmentIdFromMeta }, include }) : null) ?? + // order.paid stores the order id on the payment; before that it held the checkout id. + (await prisma.enrollment.findFirst({ where: { payment: { provider: "polar", providerRef: input.orderId } }, include })) ?? + (input.checkoutId + ? await prisma.enrollment.findFirst({ where: { payment: { provider: "polar", providerRef: input.checkoutId } }, include }) + : null); + + if (!enrollment?.payment) { + logger.warn({ orderId: input.orderId, checkoutId: input.checkoutId, enrollmentIdFromMeta }, "polar order.refunded with no matching enrollment"); + return { revoked: false, enrollmentId: null, reason: "no-enrollment" }; + } + + // Never touch access that was not bought through Polar, even if metadata points at it. + if (enrollment.payment.provider !== "polar") { + logger.warn({ orderId: input.orderId, enrollmentId: enrollment.id, provider: enrollment.payment.provider }, "polar refund for an enrollment not paid through polar"); + return { revoked: false, enrollmentId: enrollment.id, reason: "not-polar" }; + } + + if (enrollment.payment.status === "REFUNDED") { + return { revoked: false, enrollmentId: enrollment.id, reason: "already-refunded" }; + } + + if (!refundEndsAccess({ status: input.status, refundedCents: input.refundedAmount, paidCents: enrollment.payment.amountCents })) { + logger.info( + { orderId: input.orderId, enrollmentId: enrollment.id, refundedAmount: input.refundedAmount, paidCents: enrollment.payment.amountCents }, + "polar goodwill refund below the policy amount: course access kept", + ); + return { revoked: false, enrollmentId: enrollment.id, reason: "goodwill" }; + } + + const changed = await prisma.$transaction((tx) => endAccessForRefund(tx, enrollment)); + if (!changed) return { revoked: false, enrollmentId: enrollment.id, reason: "already-refunded" }; + logger.info({ orderId: input.orderId, enrollmentId: enrollment.id }, "polar refund: course access removed"); + return { revoked: true, enrollmentId: enrollment.id }; +} diff --git a/server/src/services/payments/refund-policy.ts b/server/src/services/payments/refund-policy.ts new file mode 100644 index 000000000..8d29e79d1 --- /dev/null +++ b/server/src/services/payments/refund-policy.ts @@ -0,0 +1,42 @@ +// How much of a course payment comes back on a refund. The fees on the sale are not returned: a +// fixed transaction fee per payment, an international card fee and Polar’s 5% fee: all charged by Polar, +// the payment handler, and not returned when a payment is refunded. Edorax adds no fee of its own. Change them +// here only; the admin refund, the webhook and any screen showing the amount all read these. + +/** Kept back on every refund, in cents. */ +export const REFUND_FIXED_FEE_CENTS = 50; +/** Kept back on every refund, as a share of the amount paid: 1.5%, in basis points. */ +export const REFUND_INTERNATIONAL_FEE_BPS = 150; +/** Polar's own fee on the payment, kept back on every refund: 5%, in basis points. Not an Edorax fee. */ +export const REFUND_PLATFORM_FEE_BPS = 500; + +export type RefundBreakdown = { + paidCents: number; + fixedFeeCents: number; + internationalFeeCents: number; + platformFeeCents: number; + /** What the learner gets back. 0 when the fees would take all of it. */ + refundCents: number; +}; + +const share = (cents: number, bps: number) => Math.round((cents * bps) / 10_000); + +/** The refund for a payment: paid − $0.50 − 1.5% − 5% of paid, each percentage rounded to the nearest cent. */ +export function refundBreakdown(paidCents: number): RefundBreakdown { + const paid = Math.max(0, Math.round(paidCents)); + const internationalFeeCents = share(paid, REFUND_INTERNATIONAL_FEE_BPS); + const platformFeeCents = share(paid, REFUND_PLATFORM_FEE_BPS); + const refundCents = Math.max(0, paid - REFUND_FIXED_FEE_CENTS - internationalFeeCents - platformFeeCents); + return { paidCents: paid, fixedFeeCents: REFUND_FIXED_FEE_CENTS, internationalFeeCents, platformFeeCents, refundCents }; +} + +/** + * Whether a refund on an order ends the learner's access. A full refund does, and so does one at + * or above the policy amount, which is how every refund under this policy arrives: the fees kept + * back make it "partially refunded" to Polar. A smaller refund is goodwill and access stays. + */ +export function refundEndsAccess(input: { status: string; refundedCents: number; paidCents: number }) { + if (input.status === "refunded") return true; + const policy = refundBreakdown(input.paidCents).refundCents; + return input.refundedCents > 0 && input.refundedCents >= policy; +} diff --git a/server/src/shared/api/admin.ts b/server/src/shared/api/admin.ts index 17a35da3b..642c381d5 100644 --- a/server/src/shared/api/admin.ts +++ b/server/src/shared/api/admin.ts @@ -234,10 +234,22 @@ export type AdminUserDetail = { lifecycle: EnrollmentLifecycle; percentComplete: number; lastActiveAt: string | null; + /** What a refund would return, for a course paid through Polar and not refunded yet; otherwise null. */ + refund: AdminRefundBreakdown | null; }>; coursesOwned: Array<{ id: string; title: string; slug: string; status: CourseStatus }>; }; +/** A refund less Polar’s fees on the payment: $0.50 transaction fee, 1.5% international fee, 5% Polar fee. */ +export type AdminRefundBreakdown = { + currency: string; + paidCents: number; + fixedFeeCents: number; + internationalFeeCents: number; + platformFeeCents: number; + refundCents: number; +}; + export const ADMIN_ERROR_CODES = { REQUEST_ALREADY_REVIEWED: "REQUEST_ALREADY_REVIEWED", COURSE_NOT_PUBLISHED: "COURSE_NOT_PUBLISHED", @@ -304,3 +316,78 @@ export type AdminRevenueReport = { byFundingSource: Record; }; + +export type AdminPaymentStatus = "PENDING" | "SUCCEEDED" | "FAILED" | "REFUNDED"; + +/** The money recorded for one enrollment. Every amount is in minor units of `currency`. */ +export type AdminEnrollmentPayment = { + status: AdminPaymentStatus; + currency: string; + /** What the learner is charged; for Polar this is the fixed price sent to checkout. */ + amountCents: number; + originalAmountCents: number; + discountAmountCents: number; + organizationContributionCents: number; + learnerAmountCents: number; + platformRevenueCents: number; + instructorShareCents: number; + instructorPayoutPercent: number; + instructorPayoutStatus: "NOT_DUE" | "PENDING" | "PAID"; + fundingSource: string | null; + provider: string | null; + providerRef: string | null; + paidAt: string | null; +}; + +/** A coupon or campaign applied to an enrollment's price. */ +export type AdminEnrollmentDiscount = { + /** + * campaign: a platform discount campaign; instructor_coupon: a course coupon; organization_coupon: + * from an organization's pool; admin_enrollment: an admin enrolled the learner without charge. + */ + kind: "campaign" | "instructor_coupon" | "organization_coupon" | "admin_enrollment"; + id: string; + label: string; + code: string | null; + percentOff: number; + autoApplied: boolean; + /** Organization coupons only: ISSUED, REDEEMED or CANCELLED. */ + status: string | null; + appliedAt: string | null; + organizationName: string | null; +}; + +export type AdminEnrollmentRow = { + id: string; + createdAt: string; + lifecycle: EnrollmentLifecycle; + source: "DIRECT" | "INVITE" | "SELF" | "PATHMENT"; + /** userId is null for an organization learner who has not created an account yet. */ + learner: { userId: string | null; name: string | null; email: string | null }; + course: { id: string; title: string; slug: string }; + payment: AdminEnrollmentPayment | null; + discounts: AdminEnrollmentDiscount[]; +}; + +export type AdminEnrollmentsView = { + enrollments: AdminEnrollmentRow[]; + page: AdminPageInfo; +}; + +export type AdminEnrollmentDetail = AdminEnrollmentRow & { + status: "ASSIGNED" | "IN_PROGRESS" | "COMPLETED" | "DROPPED"; + startedAt: string | null; + completedAt: string | null; + percentComplete: number; + instructor: { id: string; name: string | null; email: string }; + organization: { id: string; name: string } | null; + payment: + | (AdminEnrollmentPayment & { + createdAt: string; + updatedAt: string; + instructorPayoutPaidAt: string | null; + /** For a refunded payment, the refund less Polar's fees that our refund policy sends back. */ + refund: AdminRefundBreakdown | null; + }) + | null; +}; diff --git a/server/src/validations/admin.ts b/server/src/validations/admin.ts index 2feda25b1..7217b2473 100644 --- a/server/src/validations/admin.ts +++ b/server/src/validations/admin.ts @@ -204,3 +204,12 @@ export const grantOrganizationCreditsBody = z.object({ }); export type GrantOrganizationCreditsBody = z.infer; + +export const listEnrollmentsQuery = listQuery.extend({ + /** A payment status, or "NONE" for enrollments with no payment row (free or admin-granted). */ + payment: z.enum(["PENDING", "SUCCEEDED", "FAILED", "REFUNDED", "NONE"]).optional(), + lifecycle: z.enum(["PENDING_ACCOUNT", "PAYMENT_REQUIRED", "ACTIVE", "COMPLETED", "CANCELLED", "EXPIRED"]).optional(), + /** "true": a coupon or campaign was applied; "admin": enrolled by an admin; "false": full price. */ + discount: z.enum(["true", "admin", "false"]).optional(), +}); +export type ListEnrollmentsQuery = z.infer; diff --git a/server/src/validations/enrollments.ts b/server/src/validations/enrollments.ts index e1c1d2288..7271183a1 100644 --- a/server/src/validations/enrollments.ts +++ b/server/src/validations/enrollments.ts @@ -3,3 +3,17 @@ import { id, params } from "./common.js"; export const selfEnrollBody = z.object({ courseId: id, couponCode: z.string().trim().min(3).max(32).optional() }); export const enrollmentParams = params("enrollmentId"); +export const refundBody = z.object({ + reason: z.enum(["customer_request", "duplicate", "fraudulent", "service_disruption", "satisfaction_guarantee", "other"]).optional(), + comment: z.string().trim().max(500).optional(), +}); + +/** Admin edit of an enrollment: course access and payment status only. Only the fields sent change. */ +export const adminEnrollmentUpdateBody = z + .object({ + lifecycle: z.enum(["PENDING_ACCOUNT", "PAYMENT_REQUIRED", "ACTIVE", "COMPLETED", "CANCELLED", "EXPIRED"]).optional(), + paymentStatus: z.enum(["PENDING", "SUCCEEDED", "FAILED", "REFUNDED"]).optional(), + }) + .strict() + .refine((body) => body.lifecycle !== undefined || body.paymentStatus !== undefined, { message: "Nothing to update." }); +export type AdminEnrollmentUpdateBody = z.infer; diff --git a/server/tests/api/admin.test.ts b/server/tests/api/admin.test.ts index f1fcda640..737423260 100644 --- a/server/tests/api/admin.test.ts +++ b/server/tests/api/admin.test.ts @@ -959,3 +959,111 @@ describe("metrics", () => { expect((await request(app).get("/api/v1/admin/metrics").set(await mentor())).status).toBe(403); }); }); + +describe("enrollments and what was paid", () => { + it("lists enrollments with their payment and shows one in full", async () => { + await prisma.payment.create({ + data: { + enrollmentId: fx.enrollment.id, + amountCents: 4500, + currency: "USD", + status: "SUCCEEDED", + provider: "polar", + providerRef: `order-${fx.tag}`, + originalAmountCents: 5000, + discountAmountCents: 500, + learnerAmountCents: 4500, + platformRevenueCents: 1350, + instructorShareCents: 3150, + instructorPayoutPercent: 70, + paidAt: new Date(), + }, + }); + try { + const list = await request(app).get(`/api/v1/admin/enrollments?query=${fx.tag}&payment=SUCCEEDED`).set(admin()); + expect(list.status).toBe(200); + const row = list.body.data.enrollments.find((r: { id: string }) => r.id === fx.enrollment.id); + expect(row.learner.email).toBe(fx.learner.email); + expect(row.payment).toMatchObject({ status: "SUCCEEDED", amountCents: 4500, originalAmountCents: 5000 }); + expect(row.discounts).toEqual([]); + expect(list.body.data.page.total).toBeGreaterThanOrEqual(1); + + const none = await request(app).get(`/api/v1/admin/enrollments?query=${fx.tag}&payment=NONE`).set(admin()); + expect(none.body.data.enrollments.some((r: { id: string }) => r.id === fx.enrollment.id)).toBe(false); + + const detail = await request(app).get(`/api/v1/admin/enrollments/${fx.enrollment.id}`).set(admin()); + expect(detail.status).toBe(200); + expect(detail.body.data.instructor.id).toBe(fx.mentor.id); + expect(detail.body.data.payment).toMatchObject({ amountCents: 4500, discountAmountCents: 500, refund: null }); + + expect((await request(app).get("/api/v1/admin/enrollments/missing-enrollment").set(admin())).status).toBe(404); + expect((await request(app).get("/api/v1/admin/enrollments").set(await mentor())).status).toBe(403); + } finally { + await prisma.payment.deleteMany({ where: { enrollmentId: fx.enrollment.id } }); + } + }); + + it("edits an enrollment's access and payment, then deletes it completely", async () => { + const enrollment = await prisma.enrollment.create({ + data: { courseId: fx.course.id, userId: fx.unverified.id, lifecycle: "PAYMENT_REQUIRED", source: "SELF" }, + }); + + const noPayment = await request(app).patch(`/api/v1/admin/enrollments/${enrollment.id}`).set(admin()).send({ paymentStatus: "SUCCEEDED" }); + expect(noPayment.status).toBe(409); + await prisma.payment.create({ data: { enrollmentId: enrollment.id, amountCents: 1999, status: "PENDING" } }); + const amounts = await request(app).patch(`/api/v1/admin/enrollments/${enrollment.id}`).set(admin()).send({ amountCents: 1 }); + expect(amounts.status).toBe(400); + + const coupon = await prisma.instructorCoupon.create({ + data: { courseId: fx.course.id, createdById: fx.mentor.id, label: "Launch week", code: `LAUNCH${fx.tag}`, percentOff: 20, maxRedemptions: 10 }, + }); + await prisma.instructorCouponRedemption.create({ + data: { couponId: coupon.id, enrollmentId: enrollment.id, userId: fx.unverified.id, percentOff: 20 }, + }); + const discounted = await request(app).get(`/api/v1/admin/enrollments?query=${fx.tag}&discount=true`).set(admin()); + const discountedRow = discounted.body.data.enrollments.find((r: { id: string }) => r.id === enrollment.id); + expect(discountedRow.discounts).toMatchObject([{ kind: "instructor_coupon", label: "Launch week", code: `LAUNCH${fx.tag}`, percentOff: 20 }]); + const fullPrice = await request(app).get(`/api/v1/admin/enrollments?query=${fx.tag}&discount=false`).set(admin()); + expect(fullPrice.body.data.enrollments.some((r: { id: string }) => r.id === enrollment.id)).toBe(false); + + const edited = await request(app) + .patch(`/api/v1/admin/enrollments/${enrollment.id}`) + .set(admin()) + .send({ lifecycle: "ACTIVE", paymentStatus: "SUCCEEDED" }); + expect(edited.status).toBe(200); + expect(edited.body.data.lifecycle).toBe("ACTIVE"); + expect(edited.body.data.payment).toMatchObject({ status: "SUCCEEDED", amountCents: 1999 }); + expect(edited.body.data.payment.paidAt).not.toBeNull(); + + const audit = await prisma.adminAuditLog.findFirst({ where: { targetId: enrollment.id, action: "enrollment.update" } }); + expect(audit?.actorId).toBe(adminId); + + const empty = await request(app).patch(`/api/v1/admin/enrollments/${enrollment.id}`).set(admin()).send({}); + expect(empty.status).toBe(400); + const bad = await request(app).patch(`/api/v1/admin/enrollments/${enrollment.id}`).set(admin()).send({ lifecycle: "OPEN" }); + expect(bad.status).toBe(400); + + const removed = await request(app).delete(`/api/v1/admin/enrollments/${enrollment.id}`).set(admin()); + expect(removed.status).toBe(204); + expect(await prisma.enrollment.findUnique({ where: { id: enrollment.id } })).toBeNull(); + expect(await prisma.payment.findUnique({ where: { enrollmentId: enrollment.id } })).toBeNull(); + }); + + it("labels an admin enrollment as its discount and filters by it", async () => { + const enrolled = await request(app).post(`/api/v1/admin/users/${fx.unverified.id}/enroll`).set(admin()).send({ courseId: fx.course.id }); + expect(enrolled.status).toBeLessThan(300); + const enrollment = await prisma.enrollment.findFirstOrThrow({ where: { userId: fx.unverified.id, courseId: fx.course.id } }); + try { + const list = await request(app).get(`/api/v1/admin/enrollments?query=${fx.tag}&discount=admin`).set(admin()); + const row = list.body.data.enrollments.find((r: { id: string }) => r.id === enrollment.id); + expect(row.payment.provider).toBe("admin"); + expect(row.discounts).toMatchObject([{ kind: "admin_enrollment", label: "Admin enrollment" }]); + const fullPrice = await request(app).get(`/api/v1/admin/enrollments?query=${fx.tag}&discount=false`).set(admin()); + expect(fullPrice.body.data.enrollments.some((r: { id: string }) => r.id === enrollment.id)).toBe(false); + const detail = await request(app).get(`/api/v1/admin/enrollments/${enrollment.id}`).set(admin()); + expect(detail.body.data.discounts[0].kind).toBe("admin_enrollment"); + } finally { + await prisma.enrollment.delete({ where: { id: enrollment.id } }); + } + }); +}); diff --git a/server/tests/unit/services/admin/users.test.ts b/server/tests/unit/services/admin/users.test.ts index 4d37e8c74..19c12542d 100644 --- a/server/tests/unit/services/admin/users.test.ts +++ b/server/tests/unit/services/admin/users.test.ts @@ -321,4 +321,45 @@ describe("confirmed-enrollment filtering in user list and detail", () => { }) ); }); + + it("offers a refund, less fees, only for a completed Polar purchase", async () => { + const enrollment = (id: string, payment: Record | null) => ({ + id, + courseId: "course-1", + lifecycle: "ACTIVE", + percentComplete: 10, + lastActiveAt: null, + course: { title: "Course", slug: "course" }, + payment, + }); + const polar = { provider: "polar", providerRef: "ord_1", status: "SUCCEEDED", amountCents: 1000, currency: "USD" }; + db.user.findUnique.mockResolvedValue({ + id: "user-1", + email: "learner@test.local", + name: "Learner", + role: "MENTEE", + emailVerified: new Date(), + zipImportEnabled: false, + testerEnabled: false, + suspendedAt: null, + suspensionNote: null, + totpEnabledAt: null, + createdAt: new Date("2026-11-01T00:00:00Z"), + _count: { enrollments: 4, coursesOwned: 0, sessions: 0 }, + enrollments: [ + enrollment("polar", polar), + enrollment("manual", { ...polar, provider: "manual" }), + enrollment("free", null), + enrollment("tiny", { ...polar, amountCents: 50 }), + ], + coursesOwned: [], + }); + + const detail = await getUserDetail("user-1"); + const refund = Object.fromEntries(detail.enrollments.map((row) => [row.id, row.refund])); + expect(refund.polar).toEqual({ currency: "USD", paidCents: 1000, fixedFeeCents: 50, internationalFeeCents: 15, platformFeeCents: 50, refundCents: 885 }); + expect(refund.manual).toBeNull(); + expect(refund.free).toBeNull(); + expect(refund.tiny).toBeNull(); + }); }); diff --git a/server/tests/unit/services/enrollment/own-course.test.ts b/server/tests/unit/services/enrollment/own-course.test.ts new file mode 100644 index 000000000..fd617b1d8 --- /dev/null +++ b/server/tests/unit/services/enrollment/own-course.test.ts @@ -0,0 +1,45 @@ +import { describe, expect, it, vi } from "vitest"; +import { ensureOwnCourseEnrollment, isCourseInstructor } from "../../../../src/services/enrollment/own-course.js"; + +function fakeDb(existing: Record | null) { + return { + enrollment: { + findUnique: vi.fn().mockResolvedValue(existing), + update: vi.fn().mockImplementation(({ data }) => Promise.resolve({ ...existing, ...data })), + upsert: vi.fn().mockImplementation(({ create }) => Promise.resolve({ id: "new", ...create })), + }, + payment: { create: vi.fn() }, + }; +} + +describe("isCourseInstructor", () => { + it("matches only the course's own instructor", () => { + expect(isCourseInstructor("m1", { mentorId: "m1" })).toBe(true); + expect(isCourseInstructor("m2", { mentorId: "m1" })).toBe(false); + expect(isCourseInstructor(undefined, { mentorId: "m1" })).toBe(false); + }); +}); + +describe("ensureOwnCourseEnrollment", () => { + it("creates an active enrollment with no payment row", async () => { + const db = fakeDb(null); + const row = await ensureOwnCourseEnrollment(db as never, { courseId: "c1", userId: "m1" }); + expect(row).toMatchObject({ lifecycle: "ACTIVE", status: "IN_PROGRESS", source: "DIRECT" }); + expect(db.enrollment.upsert.mock.calls[0][0].create).not.toHaveProperty("payment"); + expect(db.payment.create).not.toHaveBeenCalled(); + }); + + it("opens an enrollment left awaiting payment", async () => { + const db = fakeDb({ id: "e1", lifecycle: "PAYMENT_REQUIRED", status: "ASSIGNED", startedAt: null }); + const row = await ensureOwnCourseEnrollment(db as never, { courseId: "c1", userId: "m1" }); + expect(row).toMatchObject({ id: "e1", lifecycle: "ACTIVE", status: "IN_PROGRESS" }); + expect(db.enrollment.upsert).not.toHaveBeenCalled(); + }); + + it("leaves an active enrollment alone", async () => { + const existing = { id: "e1", lifecycle: "COMPLETED", status: "COMPLETED" }; + const db = fakeDb(existing); + expect(await ensureOwnCourseEnrollment(db as never, { courseId: "c1", userId: "m1" })).toBe(existing); + expect(db.enrollment.update).not.toHaveBeenCalled(); + }); +}); diff --git a/server/tests/unit/services/payments/polar-webhook-route.test.ts b/server/tests/unit/services/payments/polar-webhook-route.test.ts index 9bb698722..c09be7fbd 100644 --- a/server/tests/unit/services/payments/polar-webhook-route.test.ts +++ b/server/tests/unit/services/payments/polar-webhook-route.test.ts @@ -4,6 +4,7 @@ import request from "supertest"; const validateEvent = vi.hoisted(() => vi.fn()); const fulfillPolarOrderPaid = vi.hoisted(() => vi.fn()); +const revokePolarOrderRefund = vi.hoisted(() => vi.fn()); vi.mock("@polar-sh/sdk/2026-10", () => { class PolarWebhookVerificationError extends Error {} @@ -22,6 +23,7 @@ vi.mock("../../../../src/config/env.js", () => ({ })); vi.mock("../../../../src/services/payments/fulfill-polar-order.js", () => ({ fulfillPolarOrderPaid })); +vi.mock("../../../../src/services/payments/refund-polar-order.js", () => ({ revokePolarOrderRefund })); vi.mock("../../../../src/utils/logger.js", () => ({ logger: { warn: vi.fn(), info: vi.fn(), error: vi.fn() } })); import polarWebhookRoutes from "../../../../src/routes/webhook/polar.js"; @@ -80,10 +82,17 @@ describe("POST /webhooks/polar", () => { expect(fulfillPolarOrderPaid).not.toHaveBeenCalled(); }); - it("acknowledges refund events without fulfilling", async () => { + it("passes a refund to the revoke handler, not to fulfilment", async () => { validateEvent.mockResolvedValue({ type: "order.refunded", - data: { id: "ord_refund" }, + data: { + id: "ord_refund", + checkout_id: "chk_1", + metadata: { enrollmentId: "enr_1" }, + status: "refunded", + refunded_amount: 1000, + total_amount: 1000, + }, }); const res = await request(app()) @@ -93,5 +102,28 @@ describe("POST /webhooks/polar", () => { expect(res.status).toBe(200); expect(fulfillPolarOrderPaid).not.toHaveBeenCalled(); + expect(revokePolarOrderRefund).toHaveBeenCalledWith({ + orderId: "ord_refund", + checkoutId: "chk_1", + metadata: { enrollmentId: "enr_1" }, + status: "refunded", + refundedAmount: 1000, + totalAmount: 1000, + }); + }); + + it("answers 500 when the refund cannot be applied, so Polar retries", async () => { + validateEvent.mockResolvedValue({ + type: "order.refunded", + data: { id: "ord_refund", checkout_id: null, metadata: {}, status: "refunded", refunded_amount: 1000, total_amount: 1000 }, + }); + revokePolarOrderRefund.mockRejectedValueOnce(new Error("database down")); + + const res = await request(app()) + .post("/webhooks/polar") + .set("Content-Type", "application/json") + .send(Buffer.from("{}")); + + expect(res.status).toBe(500); }); }); diff --git a/server/tests/unit/services/payments/refund-course-payment.test.ts b/server/tests/unit/services/payments/refund-course-payment.test.ts new file mode 100644 index 000000000..d4d9f33a0 --- /dev/null +++ b/server/tests/unit/services/payments/refund-course-payment.test.ts @@ -0,0 +1,81 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const db = vi.hoisted(() => ({ + enrollment: { findUnique: vi.fn(), update: vi.fn() }, + payment: { updateMany: vi.fn() }, + $transaction: vi.fn(), +})); +const refundsCreate = vi.hoisted(() => vi.fn()); +const recordAdminAction = vi.hoisted(() => vi.fn()); + +vi.mock("../../../../src/db/prisma.js", () => ({ prisma: db })); +vi.mock("../../../../src/utils/logger.js", () => ({ logger: { warn: vi.fn(), info: vi.fn(), error: vi.fn() } })); +vi.mock("../../../../src/services/payments/polar.js", () => ({ + requirePolarConfig: () => ({}), + getPolarClient: () => ({ refunds: { create: refundsCreate } }), +})); +vi.mock("../../../../src/services/admin/audit.js", () => ({ + recordAdminAction, + ADMIN_AUDIT_ACTIONS: { PAYMENT_REFUND: "payment.refund" }, +})); + +import { previewCourseRefund, refundCoursePayment } from "../../../../src/services/payments/refund-course-payment.js"; + +const admin = { id: "admin_1", email: "admin@example.com" }; +const enrollment = (payment: Record = {}) => ({ + id: "enr_1", + lifecycle: "ACTIVE", + payment: { status: "SUCCEEDED", provider: "polar", providerRef: "ord_1", amountCents: 1000, instructorPayoutStatus: "PENDING", instructorShareCents: 700, ...payment }, +}); + +describe("refundCoursePayment", () => { + beforeEach(() => { + vi.clearAllMocks(); + db.$transaction.mockImplementation(async (fn) => fn(db)); + db.payment.updateMany.mockResolvedValue({ count: 1 }); + refundsCreate.mockResolvedValue({ id: "ref_1" }); + }); + + it("refunds the payment less $0.50, 1.5% and 5% through Polar, ends access and records who did it", async () => { + db.enrollment.findUnique.mockResolvedValue(enrollment()); + + const result = await refundCoursePayment("enr_1", admin, { reason: "customer_request" }); + + expect(refundsCreate).toHaveBeenCalledWith( + expect.objectContaining({ order_id: "ord_1", amount: 885, reason: "customer_request", metadata: { enrollmentId: "enr_1", refundedBy: "admin_1" } }), + ); + expect(result).toMatchObject({ refundId: "ref_1", paidCents: 1000, fixedFeeCents: 50, internationalFeeCents: 15, platformFeeCents: 50, refundCents: 885 }); + expect(db.payment.updateMany).toHaveBeenCalledWith(expect.objectContaining({ data: expect.objectContaining({ status: "REFUNDED" }) })); + expect(db.enrollment.update).toHaveBeenCalledWith({ where: { id: "enr_1" }, data: { lifecycle: "CANCELLED", status: "DROPPED" } }); + expect(recordAdminAction).toHaveBeenCalledWith(db, expect.objectContaining({ actor: admin, action: "payment.refund", targetId: "enr_1" })); + }); + + it("previews the same amounts without refunding", async () => { + db.enrollment.findUnique.mockResolvedValue(enrollment()); + await expect(previewCourseRefund("enr_1")).resolves.toEqual({ paidCents: 1000, fixedFeeCents: 50, internationalFeeCents: 15, platformFeeCents: 50, refundCents: 885 }); + expect(refundsCreate).not.toHaveBeenCalled(); + }); + + it("refuses when the fees would take the whole payment", async () => { + db.enrollment.findUnique.mockResolvedValue(enrollment({ amountCents: 50 })); + await expect(refundCoursePayment("enr_1", admin)).rejects.toThrow(/nothing to refund/); + expect(refundsCreate).not.toHaveBeenCalled(); + }); + + it("refuses a payment that is already refunded, or not made through Polar", async () => { + db.enrollment.findUnique.mockResolvedValueOnce(enrollment({ status: "REFUNDED" })); + await expect(refundCoursePayment("enr_1", admin)).rejects.toThrow(/already been refunded/); + db.enrollment.findUnique.mockResolvedValueOnce(enrollment({ provider: "manual" })); + await expect(refundCoursePayment("enr_1", admin)).rejects.toThrow(/not paid through Polar/); + expect(refundsCreate).not.toHaveBeenCalled(); + }); + + it("changes nothing in the database when Polar refuses the refund", async () => { + db.enrollment.findUnique.mockResolvedValue(enrollment()); + refundsCreate.mockRejectedValue(new Error("Polar said no")); + + await expect(refundCoursePayment("enr_1", admin)).rejects.toThrow(/Polar said no/); + expect(db.payment.updateMany).not.toHaveBeenCalled(); + expect(db.enrollment.update).not.toHaveBeenCalled(); + }); +}); diff --git a/server/tests/unit/services/payments/refund-polar-order.test.ts b/server/tests/unit/services/payments/refund-polar-order.test.ts new file mode 100644 index 000000000..b80fb6df4 --- /dev/null +++ b/server/tests/unit/services/payments/refund-polar-order.test.ts @@ -0,0 +1,99 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const db = vi.hoisted(() => ({ + enrollment: { findUnique: vi.fn(), findFirst: vi.fn(), update: vi.fn() }, + payment: { updateMany: vi.fn() }, + $transaction: vi.fn(), +})); +const logger = vi.hoisted(() => ({ warn: vi.fn(), info: vi.fn(), error: vi.fn() })); + +vi.mock("../../../../src/db/prisma.js", () => ({ prisma: db })); +vi.mock("../../../../src/utils/logger.js", () => ({ logger })); + +import { revokePolarOrderRefund } from "../../../../src/services/payments/refund-polar-order.js"; + +const paidEnrollment = (payment: Record = {}) => ({ + id: "enr_1", + lifecycle: "ACTIVE", + payment: { status: "SUCCEEDED", provider: "polar", providerRef: "ord_1", amountCents: 1000, instructorPayoutStatus: "PENDING", instructorShareCents: 700, ...payment }, +}); + +// $10.00 paid, refunded by the policy: 1000 - 50 - 15 - 50 = 885 cents, which Polar calls partially refunded. +const policyRefund = { orderId: "ord_1", checkoutId: "chk_1", metadata: { enrollmentId: "enr_1" }, status: "partially_refunded", refundedAmount: 885, totalAmount: 1000 }; + +describe("revokePolarOrderRefund", () => { + beforeEach(() => { + vi.clearAllMocks(); + db.$transaction.mockImplementation(async (fn) => fn(db)); + db.enrollment.findFirst.mockResolvedValue(null); + db.payment.updateMany.mockResolvedValue({ count: 1 }); + }); + + it("removes access for a refund at the policy amount and cancels an unpaid instructor payout", async () => { + db.enrollment.findUnique.mockResolvedValue(paidEnrollment()); + + await expect(revokePolarOrderRefund(policyRefund)).resolves.toEqual({ revoked: true, enrollmentId: "enr_1" }); + expect(db.payment.updateMany).toHaveBeenCalledWith({ + where: { enrollmentId: "enr_1", status: "SUCCEEDED" }, + data: { status: "REFUNDED", instructorPayoutStatus: "NOT_DUE" }, + }); + expect(db.enrollment.update).toHaveBeenCalledWith({ where: { id: "enr_1" }, data: { lifecycle: "CANCELLED", status: "DROPPED" } }); + }); + + it("removes access for a full refund too", async () => { + db.enrollment.findUnique.mockResolvedValue(paidEnrollment()); + const result = await revokePolarOrderRefund({ ...policyRefund, status: "refunded", refundedAmount: 1000 }); + expect(result).toEqual({ revoked: true, enrollmentId: "enr_1" }); + }); + + it("finds the enrollment by order id when the metadata has none", async () => { + db.enrollment.findFirst.mockImplementation(async ({ where }) => (where.payment.providerRef === "ord_1" ? paidEnrollment() : null)); + const result = await revokePolarOrderRefund({ ...policyRefund, metadata: null }); + expect(result).toEqual({ revoked: true, enrollmentId: "enr_1" }); + }); + + it("keeps access for a goodwill refund below the policy amount", async () => { + db.enrollment.findUnique.mockResolvedValue(paidEnrollment()); + + const result = await revokePolarOrderRefund({ ...policyRefund, refundedAmount: 300 }); + expect(result).toEqual({ revoked: false, enrollmentId: "enr_1", reason: "goodwill" }); + expect(db.payment.updateMany).not.toHaveBeenCalled(); + }); + + it("changes nothing when the admin refund already ended access", async () => { + db.enrollment.findUnique.mockResolvedValue({ ...paidEnrollment({ status: "REFUNDED" }), lifecycle: "CANCELLED" }); + + const result = await revokePolarOrderRefund(policyRefund); + expect(result).toEqual({ revoked: false, enrollmentId: "enr_1", reason: "already-refunded" }); + expect(db.$transaction).not.toHaveBeenCalled(); + }); + + it("changes nothing when another delivery won the race", async () => { + db.enrollment.findUnique.mockResolvedValue(paidEnrollment()); + db.payment.updateMany.mockResolvedValue({ count: 0 }); + + const result = await revokePolarOrderRefund(policyRefund); + expect(result).toEqual({ revoked: false, enrollmentId: "enr_1", reason: "already-refunded" }); + expect(db.enrollment.update).not.toHaveBeenCalled(); + }); + + it("never removes access that was not paid through Polar", async () => { + db.enrollment.findUnique.mockResolvedValue(paidEnrollment({ provider: "manual" })); + const result = await revokePolarOrderRefund(policyRefund); + expect(result).toEqual({ revoked: false, enrollmentId: "enr_1", reason: "not-polar" }); + }); + + it("keeps an instructor payout that was already paid, and flags it", async () => { + db.enrollment.findUnique.mockResolvedValue(paidEnrollment({ instructorPayoutStatus: "PAID" })); + + await revokePolarOrderRefund(policyRefund); + expect(db.payment.updateMany).toHaveBeenCalledWith({ where: { enrollmentId: "enr_1", status: "SUCCEEDED" }, data: { status: "REFUNDED" } }); + expect(logger.warn).toHaveBeenCalledWith(expect.objectContaining({ enrollmentId: "enr_1" }), expect.stringMatching(/manual adjustment/)); + }); + + it("reports an order it cannot match without failing", async () => { + db.enrollment.findUnique.mockResolvedValue(null); + const result = await revokePolarOrderRefund({ ...policyRefund, metadata: null, checkoutId: null }); + expect(result).toEqual({ revoked: false, enrollmentId: null, reason: "no-enrollment" }); + }); +}); diff --git a/server/tests/unit/services/payments/refund-policy.test.ts b/server/tests/unit/services/payments/refund-policy.test.ts new file mode 100644 index 000000000..ff251b3fb --- /dev/null +++ b/server/tests/unit/services/payments/refund-policy.test.ts @@ -0,0 +1,31 @@ +import { describe, expect, it } from "vitest"; +import { refundBreakdown, refundEndsAccess } from "../../../../src/services/payments/refund-policy.js"; + +describe("refundBreakdown", () => { + it("keeps back $0.50, 1.5% and the 5% platform fee of what was paid", () => { + expect(refundBreakdown(1000)).toEqual({ paidCents: 1000, fixedFeeCents: 50, internationalFeeCents: 15, platformFeeCents: 50, refundCents: 885 }); + expect(refundBreakdown(4999).refundCents).toBe(4999 - 50 - 75 - 250); + }); + + it("rounds the international fee to the nearest cent", () => { + expect(refundBreakdown(100).internationalFeeCents).toBe(2); // 1.5 cents + expect(refundBreakdown(1033).internationalFeeCents).toBe(15); // 15.495 cents + }); + + it("never goes below zero when the fees are as much as the payment", () => { + expect(refundBreakdown(50).refundCents).toBe(0); + expect(refundBreakdown(0).refundCents).toBe(0); + }); +}); + +describe("refundEndsAccess", () => { + it("ends access for a full refund or one at the policy amount", () => { + expect(refundEndsAccess({ status: "refunded", refundedCents: 1000, paidCents: 1000 })).toBe(true); + expect(refundEndsAccess({ status: "partially_refunded", refundedCents: 885, paidCents: 1000 })).toBe(true); + }); + + it("keeps access for a smaller goodwill refund", () => { + expect(refundEndsAccess({ status: "partially_refunded", refundedCents: 884, paidCents: 1000 })).toBe(false); + expect(refundEndsAccess({ status: "partially_refunded", refundedCents: 0, paidCents: 30 })).toBe(false); + }); +}); From 46db91951875c0b0b5748dc876c58f3d45692589 Mon Sep 17 00:00:00 2001 From: ASIF RAZA Date: Tue, 17 Nov 2026 23:10:36 +0500 Subject: [PATCH 2/8] feat(payments): configurable 4-fee refund policy, 3-mode admin refunds (Full, Standard, Custom), and app settings console --- .../app/(admin)/admin/settings/app/page.tsx | 22 ++ .../src/app/(admin)/admin/settings/page.tsx | 5 + .../admin/admin-workspace-shell.tsx | 7 + .../components/admin/app-settings-view.tsx | 224 +++++++++++ .../components/admin/refund-policy-form.tsx | 360 ++++++++++++++++++ .../src/server/actions/admin/refund-policy.ts | 19 + frontend/src/shared/api/admin.ts | 36 +- .../migration.sql | 11 + server/prisma/schema.prisma | 11 + server/src/controllers/admin.ts | 18 + server/src/routes/v1/admin.ts | 5 + server/src/services/admin/app-settings.ts | 87 +++++ server/src/services/admin/audit.ts | 3 +- server/src/services/admin/refund-policy.ts | 71 ++++ .../payments/refund-course-payment.ts | 160 ++++++-- .../services/payments/refund-polar-order.ts | 16 +- server/src/services/payments/refund-policy.ts | 185 +++++++-- server/src/shared/api/admin.ts | 34 +- server/src/validations/admin.ts | 16 + server/src/validations/enrollments.ts | 30 +- .../tests/unit/services/admin/users.test.ts | 10 +- .../payments/refund-course-payment.test.ts | 125 +++++- .../payments/refund-polar-order.test.ts | 65 +++- .../services/payments/refund-policy.test.ts | 176 ++++++++- 24 files changed, 1593 insertions(+), 103 deletions(-) create mode 100644 frontend/src/app/(admin)/admin/settings/app/page.tsx create mode 100644 frontend/src/app/(admin)/admin/settings/page.tsx create mode 100644 frontend/src/components/admin/app-settings-view.tsx create mode 100644 frontend/src/components/admin/refund-policy-form.tsx create mode 100644 frontend/src/server/actions/admin/refund-policy.ts create mode 100644 server/prisma/migrations/20261117220000_add_app_settings/migration.sql create mode 100644 server/src/services/admin/app-settings.ts create mode 100644 server/src/services/admin/refund-policy.ts diff --git a/frontend/src/app/(admin)/admin/settings/app/page.tsx b/frontend/src/app/(admin)/admin/settings/app/page.tsx new file mode 100644 index 000000000..574ef86f2 --- /dev/null +++ b/frontend/src/app/(admin)/admin/settings/app/page.tsx @@ -0,0 +1,22 @@ +import { serverApiFetch } from "@/lib/api-server"; +import { requireRole } from "@/server/auth/guards"; +import { AdminPageHeader } from "@/components/admin/admin-ui"; +import { AppSettingsDashboard } from "@/components/admin/app-settings-view"; +import type { AppSettingsView } from "@/shared/api/admin"; + +export default async function AdminAppSettingsPage() { + await requireRole("ADMIN"); + const data = await serverApiFetch("/api/v1/admin/settings/app"); + + return ( +
+ + + +
+ ); +} diff --git a/frontend/src/app/(admin)/admin/settings/page.tsx b/frontend/src/app/(admin)/admin/settings/page.tsx new file mode 100644 index 000000000..eb6ec9fa1 --- /dev/null +++ b/frontend/src/app/(admin)/admin/settings/page.tsx @@ -0,0 +1,5 @@ +import { redirect } from "next/navigation"; + +export default function AdminSettingsRedirectPage() { + redirect("/admin/settings/app"); +} diff --git a/frontend/src/components/admin/admin-workspace-shell.tsx b/frontend/src/components/admin/admin-workspace-shell.tsx index 107f81b08..10a3c30fb 100644 --- a/frontend/src/components/admin/admin-workspace-shell.tsx +++ b/frontend/src/components/admin/admin-workspace-shell.tsx @@ -13,6 +13,7 @@ import { LineChart, Receipt, MonitorDown, + SlidersHorizontal, Users, Wallet, } from "lucide-react"; @@ -95,6 +96,12 @@ export function AdminWorkspaceShell({ icon: MonitorDown, active: pathname.startsWith("/admin/desktop-updates"), }, + { + label: "App settings", + href: "/admin/settings/app", + icon: SlidersHorizontal, + active: pathname === "/admin/settings" || pathname.startsWith("/admin/settings/app"), + }, { label: "Audit log", href: "/admin/audit", icon: History, active: pathname.startsWith("/admin/audit") }, ], }, diff --git a/frontend/src/components/admin/app-settings-view.tsx b/frontend/src/components/admin/app-settings-view.tsx new file mode 100644 index 000000000..62d448226 --- /dev/null +++ b/frontend/src/components/admin/app-settings-view.tsx @@ -0,0 +1,224 @@ +"use client"; + +import { useState } from "react"; +import { RefundPolicyForm } from "@/components/admin/refund-policy-form"; +import { Badge } from "@/components/ui/badge"; +import { Input } from "@/components/ui/input"; +import { + Activity, + Bot, + CheckCircle2, + Cpu, + CreditCard, + DollarSign, + Flame, + Search, + ShieldCheck, + SlidersHorizontal, + XCircle, +} from "lucide-react"; +import type { AppSettingsView, FeatureFlagInfo } from "@/shared/api/admin"; + +export function AppSettingsDashboard({ data }: { data: AppSettingsView }) { + const [activeTab, setActiveTab] = useState<"policy" | "flags" | "payment">("policy"); + const [filterQuery, setFilterQuery] = useState(""); + const [categoryFilter, setCategoryFilter] = useState("all"); + + const filteredFlags = data.featureFlags.filter((flag) => { + const matchesQuery = + flag.name.toLowerCase().includes(filterQuery.toLowerCase()) || + flag.key.toLowerCase().includes(filterQuery.toLowerCase()) || + flag.description.toLowerCase().includes(filterQuery.toLowerCase()); + const matchesCategory = categoryFilter === "all" || flag.category === categoryFilter; + return matchesQuery && matchesCategory; + }); + + const enabledCount = data.featureFlags.filter((f) => f.enabled).length; + + return ( +
+ {/* Top Navigation Tabs */} +
+ + + + + +
+ + {/* Tab 1: Refund Policy Form */} + {activeTab === "policy" && } + + {/* Tab 2: Feature Flags */} + {activeTab === "flags" && ( +
+ {/* Filter Bar */} +
+
+ + setFilterQuery(e.target.value)} + className="pl-9 text-xs" + /> +
+ +
+ {[ + { id: "all", label: "All categories" }, + { id: "gamification", label: "Gamification" }, + { id: "infra", label: "System & Cron" }, + ].map((cat) => ( + + ))} +
+
+ + {/* Feature Flags Grid */} +
+ {filteredFlags.map((flag) => { + const CategoryIcon = flag.category === "gamification" ? Flame : Cpu; + + return ( +
+
+
+
+
+ +
+
+

{flag.name}

+ {flag.key} +
+
+ + {flag.enabled ? ( + + + Enabled + + ) : ( + + + Disabled + + )} +
+ +

{flag.description}

+
+ +
+ Category: {flag.category} + Env-configured +
+
+ ); + })} +
+ + {filteredFlags.length === 0 && ( +
+ No feature flags found matching your filter. +
+ )} +
+ )} + + {/* Tab 3: Payment Gateway Overview */} + {activeTab === "payment" && ( +
+
+
+
+

Polar payment integration

+

Gateway status and checkout configuration.

+
+ + {data.polar.configured ? ( + + + Active & Connected + + ) : ( + + + Not configured + + )} +
+ +
+
+
Environment
+
{data.polar.environment || "Sandbox"}
+
+ +
+
Refund Modes Supported
+
Standard, Full, Custom
+
+ +
+
Currency
+
USD ($)
+
+
+
+
+ )} +
+ ); +} diff --git a/frontend/src/components/admin/refund-policy-form.tsx b/frontend/src/components/admin/refund-policy-form.tsx new file mode 100644 index 000000000..eb24994ec --- /dev/null +++ b/frontend/src/components/admin/refund-policy-form.tsx @@ -0,0 +1,360 @@ +"use client"; + +import { useState, useTransition } from "react"; +import { saveRefundPolicyAction } from "@/server/actions/admin/refund-policy"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { toast } from "@/components/ui/app-toast"; +import { Calculator, Check, RotateCcw, AlertTriangle } from "lucide-react"; +import type { RefundPolicy, RefundPolicyView } from "@/shared/api/admin"; + +const DEFAULTS: RefundPolicy = { + fixedFeeCents: 50, + internationalFeeBps: 150, + polarFeeBps: 500, + edoraxFeeBps: 0, +}; + +export function RefundPolicyForm({ initial }: { initial: RefundPolicyView }) { + const [fixedFeeCents, setFixedFeeCents] = useState(initial.policy.fixedFeeCents); + const [internationalFeeBps, setInternationalFeeBps] = useState(initial.policy.internationalFeeBps); + const [polarFeeBps, setPolarFeeBps] = useState(initial.policy.polarFeeBps); + const [edoraxFeeBps, setEdoraxFeeBps] = useState(initial.policy.edoraxFeeBps); + + // Example test amount in cents (default $20.00 = 2000 cents) + const [exampleCents, setExampleCents] = useState(2000); + + const [isPending, startTransition] = useTransition(); + const [feedback, setFeedback] = useState<{ ok: boolean; message: string } | null>(null); + + // Derived percentages + const totalBps = (internationalFeeBps || 0) + (polarFeeBps || 0) + (edoraxFeeBps || 0); + const totalPercent = (totalBps / 100).toFixed(2); + const isInvalidTotal = totalBps >= 10000; + + // Real-time breakdown calculation on the example amount + const paid = Math.max(0, exampleCents || 0); + const intlFee = Math.round((paid * (internationalFeeBps || 0)) / 10000); + const polarFee = Math.round((paid * (polarFeeBps || 0)) / 10000); + const edoraxFee = Math.round((paid * (edoraxFeeBps || 0)) / 10000); + const fixedFee = Math.max(0, fixedFeeCents || 0); + const totalFeesKept = fixedFee + intlFee + polarFee + edoraxFee; + const standardRefund = Math.max(0, paid - totalFeesKept); + const fullRefund = paid; + + function resetToDefaults() { + setFixedFeeCents(DEFAULTS.fixedFeeCents); + setInternationalFeeBps(DEFAULTS.internationalFeeBps); + setPolarFeeBps(DEFAULTS.polarFeeBps); + setEdoraxFeeBps(DEFAULTS.edoraxFeeBps); + setFeedback(null); + } + + function handleSubmit(e: React.FormEvent) { + e.preventDefault(); + if (isInvalidTotal) { + toast("Total percentage fee must stay below 100%.", "error"); + return; + } + + startTransition(async () => { + const res = await saveRefundPolicyAction({ + fixedFeeCents: Number(fixedFeeCents), + internationalFeeBps: Number(internationalFeeBps), + polarFeeBps: Number(polarFeeBps), + edoraxFeeBps: Number(edoraxFeeBps), + }); + + setFeedback(res); + if (res.ok) { + toast(res.message, "success"); + } else { + toast(res.message, "error"); + } + }); + } + + return ( +
+
+
+
+

Standard refund fee policy

+

+ Configure the fees retained by Edorax and Polar when an admin issues a standard refund. +

+
+ +
+ +
+ {/* Fixed Fee */} +
+ +
+ setFixedFeeCents(Math.max(0, parseInt(e.target.value, 10) || 0))} + required + className="pr-12" + /> + + cents + +
+

+ Fixed card gateway processing charge retained on every refund (default: 50¢). +

+
+ + {/* International Fee */} +
+ +
+ setInternationalFeeBps(Math.max(0, parseInt(e.target.value, 10) || 0))} + required + className="pr-12" + /> + + bps + +
+

+ International card assessment fee (100 bps = 1.00%, default: 150 bps = 1.5%). +

+
+ + {/* Polar Fee */} +
+ +
+ setPolarFeeBps(Math.max(0, parseInt(e.target.value, 10) || 0))} + required + className="pr-12" + /> + + bps + +
+

+ Polar processor fee not returned upon refund (default: 500 bps = 5.0%). +

+
+ + {/* Edorax Fee */} +
+ +
+ setEdoraxFeeBps(Math.max(0, parseInt(e.target.value, 10) || 0))} + required + className="pr-12" + /> + + bps + +
+

+ Edorax internal administrative fee retained (default: 0 bps = 0.0%). +

+
+
+ + {/* Total Fee Indicator */} +
+ Total percentage fee: + + {totalPercent}% ({totalBps} bps) + +
+ + {isInvalidTotal && ( +
+ + The total fee rate must be under 100% (under 10,000 basis points). +
+ )} + + {feedback?.message && ( +

+ {feedback.message} +

+ )} + +
+ +
+
+ + {/* Live Preview Calculator Card */} +
+
+
+
+ +
+
+

Live refund preview

+

+ See how the saved policy applies to any order amount in real time. +

+
+
+ +
+ + setExampleCents(Math.max(100, (parseFloat(e.target.value) || 0) * 100))} + className="h-8 w-24 text-right tabular-nums text-xs" + /> +
+
+ +
+ {/* Option 1: Standard Refund */} +
+
+ Option 1: Standard + + Default + +
+
+

+ ${(standardRefund / 100).toFixed(2)} +

+

Learner refund (minus fees)

+
+
+
+ Fixed fee: + -${(fixedFee / 100).toFixed(2)} +
+
+ International card fee: + -${(intlFee / 100).toFixed(2)} +
+
+ Polar platform fee: + -${(polarFee / 100).toFixed(2)} +
+
+ Edorax platform fee: + -${(edoraxFee / 100).toFixed(2)} +
+
+ Total fees kept: + -${(totalFeesKept / 100).toFixed(2)} +
+
+
+ + {/* Option 2: Full Refund */} +
+
+ + Option 2: Full + +
+
+

+ ${(fullRefund / 100).toFixed(2)} +

+

Full purchase returned

+
+
+

+ Edorax absorbs the ${(totalFeesKept / 100).toFixed(2)} in + fees. Requires an admin justification reason. +

+
+
+ + {/* Option 3: Custom Refund */} +
+
+ + Option 3: Custom + +
+
+

+ $0.01 – ${(fullRefund / 100).toFixed(2)} +

+

Admin-specified amount

+
+
+

+ Admin specifies an exact amount up to the order maximum. Requires an admin justification reason. +

+
+
+
+
+
+ ); +} diff --git a/frontend/src/server/actions/admin/refund-policy.ts b/frontend/src/server/actions/admin/refund-policy.ts new file mode 100644 index 000000000..7df5d9365 --- /dev/null +++ b/frontend/src/server/actions/admin/refund-policy.ts @@ -0,0 +1,19 @@ +"use server"; + +import { revalidatePath } from "next/cache"; +import { adminCall } from "./call"; +import { runAdminAction, type AdminActionState } from "./action-result"; +import type { RefundPolicy, RefundPolicyView } from "@/shared/api/admin"; + +const PATH = "/api/v1/admin/settings/refund-policy"; + +export async function saveRefundPolicyAction(policy: RefundPolicy): Promise { + return runAdminAction(async () => { + await adminCall(PATH, { method: "PUT", json: policy }); + revalidatePath("/admin/settings/refund-policy"); + revalidatePath("/admin/settings"); + revalidatePath("/admin/course-access"); + revalidatePath("/admin/audit"); + return "Refund policy saved successfully."; + }); +} diff --git a/frontend/src/shared/api/admin.ts b/frontend/src/shared/api/admin.ts index ee1887c69..3fafc1c81 100644 --- a/frontend/src/shared/api/admin.ts +++ b/frontend/src/shared/api/admin.ts @@ -241,16 +241,50 @@ export type AdminUserDetail = { coursesOwned: Array<{ id: string; title: string; slug: string; status: CourseStatus }>; }; -/** A refund less Polar’s fees on the payment: $0.50 transaction fee, 1.5% international fee, 5% Polar fee. */ +/** A refund less fees: fixed transaction fee, international fee, Polar fee, Edorax fee. */ export type AdminRefundBreakdown = { currency: string; paidCents: number; fixedFeeCents: number; internationalFeeCents: number; platformFeeCents: number; + edoraxFeeCents: number; refundCents: number; }; +export type RefundPolicy = { + fixedFeeCents: number; + internationalFeeBps: number; + polarFeeBps: number; + edoraxFeeBps: number; +}; + +export type FeatureFlagInfo = { + key: string; + name: string; + description: string; + enabled: boolean; + category: "gamification" | "infra"; +}; + +export type AppSettingsView = { + refundPolicy: RefundPolicyView; + featureFlags: FeatureFlagInfo[]; + polar: { + configured: boolean; + environment: string; + }; +}; + +export type RefundPolicyView = { + policy: RefundPolicy; + example: { + paidCents: number; + standardRefundCents: number; + fullRefundCents: number; + }; +}; + export const ADMIN_ERROR_CODES = { REQUEST_ALREADY_REVIEWED: "REQUEST_ALREADY_REVIEWED", COURSE_NOT_PUBLISHED: "COURSE_NOT_PUBLISHED", diff --git a/server/prisma/migrations/20261117220000_add_app_settings/migration.sql b/server/prisma/migrations/20261117220000_add_app_settings/migration.sql new file mode 100644 index 000000000..581e4669f --- /dev/null +++ b/server/prisma/migrations/20261117220000_add_app_settings/migration.sql @@ -0,0 +1,11 @@ +-- Migration: add_app_settings +-- Creates a generic key-value store for platform-wide settings editable by admins. +-- The first use-case is the refund policy (key = 'refund_policy', value = JSON). + +CREATE TABLE "app_settings" ( + "key" VARCHAR(80) NOT NULL, + "value" TEXT NOT NULL, + "updatedAt" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "app_settings_pkey" PRIMARY KEY ("key") +); diff --git a/server/prisma/schema.prisma b/server/prisma/schema.prisma index 414d0af87..51b579f3b 100644 --- a/server/prisma/schema.prisma +++ b/server/prisma/schema.prisma @@ -1729,3 +1729,14 @@ model DesktopUpdatePolicy { @@map("desktop_update_policies") } + +/// Generic key-value store for platform-wide settings editable by admins. +/// Each row holds one JSON-encoded value identified by a stable string key. +model AppSetting { + key String @id @db.VarChar(80) + /// JSON-encoded value. The shape is key-specific and validated in the service layer. + value String @db.Text + updatedAt DateTime @updatedAt + + @@map("app_settings") +} diff --git a/server/src/controllers/admin.ts b/server/src/controllers/admin.ts index 040c69461..a31c7e8a9 100644 --- a/server/src/controllers/admin.ts +++ b/server/src/controllers/admin.ts @@ -12,6 +12,8 @@ import * as courseAccess from "../services/admin/course-access.js"; import * as profile from "../services/admin/profile.js"; import * as audit from "../services/admin/audit.js"; import * as desktopUpdates from "../services/admin/desktop-updates.js"; +import * as refundPolicySvc from "../services/admin/refund-policy.js"; +import * as appSettingsSvc from "../services/admin/app-settings.js"; import * as appActivity from "../services/activity/reports.js"; import type { AppActivityUsersQuery } from "../validations/activity.js"; import type { @@ -33,6 +35,7 @@ import type { ListUsersQuery, MetricsQuery, PageQuery, + RefundPolicyBody, SuspendUserBody, TotpCodeBody, } from "../validations/admin.js"; @@ -397,3 +400,18 @@ export async function saveDesktopUpdates(req: Request, res: Response) { const { platforms, fields } = req.body as DesktopUpdatesBody; ok(res, await desktopUpdates.saveDesktopUpdatePolicies({ id: req.user!.id, email: req.user!.email }, platforms, fields)); } + +// GET /api/v1/admin/settings/refund-policy +export async function getRefundPolicy(_req: Request, res: Response) { + ok(res, await refundPolicySvc.getRefundPolicyAdmin()); +} + +// PUT /api/v1/admin/settings/refund-policy +export async function saveRefundPolicy(req: Request, res: Response) { + ok(res, await refundPolicySvc.updateRefundPolicyAdmin(req.body as RefundPolicyBody, { id: req.user!.id, email: req.user!.email })); +} + +// GET /api/v1/admin/settings/app +export async function getAppSettings(_req: Request, res: Response) { + ok(res, await appSettingsSvc.getAppSettingsAdmin()); +} diff --git a/server/src/routes/v1/admin.ts b/server/src/routes/v1/admin.ts index f35a9f9b5..45e3f9aec 100644 --- a/server/src/routes/v1/admin.ts +++ b/server/src/routes/v1/admin.ts @@ -44,6 +44,7 @@ import { metricsQuery, orgIdParams, listAuditQuery, + refundPolicyBody, requestIdParams, suspendUserBody, totpCodeBody, @@ -250,4 +251,8 @@ router.put("/desktop-updates", validateBody(desktopUpdatesBody), admin.saveDeskt router.get("/audit", validateQuery(listAuditQuery), admin.listAudit); router.get("/audit/export", admin.exportAuditCsv); +router.get("/settings/refund-policy", admin.getRefundPolicy); +router.put("/settings/refund-policy", validateBody(refundPolicyBody), admin.saveRefundPolicy); +router.get("/settings/app", admin.getAppSettings); + export default router; diff --git a/server/src/services/admin/app-settings.ts b/server/src/services/admin/app-settings.ts new file mode 100644 index 000000000..8e0f92a6c --- /dev/null +++ b/server/src/services/admin/app-settings.ts @@ -0,0 +1,87 @@ +// Admin service: platform overview, feature flags and gateway configurations. + +import { env, polarPaymentsConfigured, rateLimitsEnabled } from "../../config/env.js"; +import { getRefundPolicyAdmin, type RefundPolicyView } from "./refund-policy.js"; + +export type FeatureFlagInfo = { + key: string; + name: string; + description: string; + enabled: boolean; + category: "gamification" | "infra"; +}; + +export type AppSettingsView = { + refundPolicy: RefundPolicyView; + featureFlags: FeatureFlagInfo[]; + polar: { + configured: boolean; + environment: string; + }; +}; + +/** Gathers platform settings, policy, and active feature flags for the Admin App Settings Console. */ +export async function getAppSettingsAdmin(): Promise { + const refundPolicy = await getRefundPolicyAdmin(); + + const featureFlags: FeatureFlagInfo[] = [ + { + key: "GAMIFICATION_XP", + name: "XP Ledger & Progression", + description: "Experience points awarded for quizzes and lessons", + enabled: env.GAMIFICATION_XP !== false, + category: "gamification", + }, + { + key: "GAMIFICATION_LEADERBOARDS", + name: "Weekly League Leaderboards", + description: "Weekly competitive league resets and tier promotions", + enabled: env.GAMIFICATION_LEADERBOARDS !== false, + category: "gamification", + }, + { + key: "GAMIFICATION_STREAK_FREEZES", + name: "Daily Streak Freezes", + description: "Learners hold up to 2 streak freezes to maintain daily momentum", + enabled: env.GAMIFICATION_STREAK_FREEZES !== false, + category: "gamification", + }, + { + key: "GAMIFICATION_CAREER_LEVELS", + name: "Career Mastery Tiers", + description: "Verified mastery milestones that permanently promote career rank", + enabled: env.GAMIFICATION_CAREER_LEVELS !== false, + category: "gamification", + }, + { + key: "GAMIFICATION_CREDITS", + name: "Build Credits", + description: "Redeemable build credits ledger for project builds and lab runs", + enabled: env.GAMIFICATION_CREDITS !== false, + category: "gamification", + }, + { + key: "BACKGROUND_JOBS", + name: "Cron Scheduled Workers", + description: "Daily midnight resets, streak checks, and retention cleanups", + enabled: env.JOBS_ENABLED !== false, + category: "infra", + }, + { + key: "RATE_LIMITS", + name: "API Rate Limiting", + description: "Per-user and per-IP endpoint request throttling", + enabled: Boolean(rateLimitsEnabled), + category: "infra", + }, + ]; + + return { + refundPolicy, + featureFlags, + polar: { + configured: Boolean(polarPaymentsConfigured), + environment: env.POLAR_ENVIRONMENT, + }, + }; +} diff --git a/server/src/services/admin/audit.ts b/server/src/services/admin/audit.ts index 874b25471..e6a862ede 100644 --- a/server/src/services/admin/audit.ts +++ b/server/src/services/admin/audit.ts @@ -50,6 +50,7 @@ export const ADMIN_AUDIT_ACTIONS = { MFA_DISABLE: "mfa.disable", MFA_RESET: "mfa.reset", MFA_RECOVERY_REGENERATE: "mfa.recovery-regenerate", + REFUND_POLICY_CHANGED: "refund-policy.changed", } as const; export type AdminAuditActionKey = (typeof ADMIN_AUDIT_ACTIONS)[keyof typeof ADMIN_AUDIT_ACTIONS]; @@ -57,7 +58,7 @@ export type AdminAuditActionKey = (typeof ADMIN_AUDIT_ACTIONS)[keyof typeof ADMI export type AdminAuditEntry = { actor: AdminActor; action: AdminAuditActionKey; - targetType: "Organization" | "User" | "CourseRequest" | "InstructorAccessRequest" | "Course" | "CourseDiscountCampaign" | "Enrollment" | "Payment" | "InstructorWithdrawal" | "DesktopUpdatePolicy"; + targetType: "Organization" | "User" | "CourseRequest" | "InstructorAccessRequest" | "Course" | "CourseDiscountCampaign" | "Enrollment" | "Payment" | "InstructorWithdrawal" | "DesktopUpdatePolicy" | "Platform"; targetId?: string | null; summary: string; metadata?: Prisma.InputJsonValue; diff --git a/server/src/services/admin/refund-policy.ts b/server/src/services/admin/refund-policy.ts new file mode 100644 index 000000000..fd8a40862 --- /dev/null +++ b/server/src/services/admin/refund-policy.ts @@ -0,0 +1,71 @@ +// Admin service: read and update the platform-wide refund policy. +// The policy drives what the learner gets back on a Standard refund, the +// refund dialog options and the webhook access-revocation threshold. + +import { ADMIN_AUDIT_ACTIONS, type AdminActor } from "./audit.js"; +import { + DEFAULT_REFUND_POLICY, + getRefundPolicy, + refundBreakdown, + saveRefundPolicy, + validateRefundPolicy, + type RefundPolicy, +} from "../payments/refund-policy.js"; +import { prisma } from "../../db/prisma.js"; +import { BadRequestError } from "../../utils/errors.js"; + +export type RefundPolicyView = { + policy: RefundPolicy; + /** Example: a $20 domestic order. */ + example: { + paidCents: number; + standardRefundCents: number; + fullRefundCents: number; + }; +}; + +/** Returns the live saved policy plus an example calculation for the settings UI. */ +export async function getRefundPolicyAdmin(): Promise { + const policy = await getRefundPolicy(); + const examplePaid = 2000; // $20.00 + const bd = refundBreakdown(examplePaid, policy); + return { + policy, + example: { + paidCents: examplePaid, + standardRefundCents: bd.refundCents, + fullRefundCents: examplePaid, + }, + }; +} + +/** Validates, saves and audit-logs a new refund policy. */ +export async function updateRefundPolicyAdmin( + newPolicy: unknown, + actor: AdminActor, +): Promise { + if (!validateRefundPolicy(newPolicy)) { + throw new BadRequestError( + "Invalid refund policy: all values must be non-negative integers and total percentage must be under 100%.", + "INVALID_REFUND_POLICY", + ); + } + + const previous = await getRefundPolicy(); + await saveRefundPolicy(newPolicy as RefundPolicy); + + await prisma.adminAuditLog.create({ + data: { + actorId: actor.id, + actorEmail: actor.email, + action: ADMIN_AUDIT_ACTIONS.REFUND_POLICY_CHANGED, + targetType: "Platform", + summary: `Updated refund policy: fixed ${newPolicy.fixedFeeCents}c, international ${newPolicy.internationalFeeBps}bps, Polar ${newPolicy.polarFeeBps}bps, Edorax ${newPolicy.edoraxFeeBps}bps.`, + metadata: { previous, updated: newPolicy }, + }, + }); + + return getRefundPolicyAdmin(); +} + +export { DEFAULT_REFUND_POLICY }; diff --git a/server/src/services/payments/refund-course-payment.ts b/server/src/services/payments/refund-course-payment.ts index d9f587ab7..a93ce0343 100644 --- a/server/src/services/payments/refund-course-payment.ts +++ b/server/src/services/payments/refund-course-payment.ts @@ -3,71 +3,175 @@ import { ADMIN_AUDIT_ACTIONS, recordAdminAction, type AdminActor } from "../admi import { BadRequestError, ConflictError, NotFoundError } from "../../utils/errors.js"; import { getPolarClient, requirePolarConfig } from "./polar.js"; import { endAccessForRefund } from "./refund-polar-order.js"; -import { refundBreakdown, type RefundBreakdown } from "./refund-policy.js"; +import { + allRefundOptions, + getRefundPolicy, + refundBreakdown, + resolveRefundCents, + type AllRefundOptions, + type RefundMode, +} from "./refund-policy.js"; -export const REFUND_REASONS = ["customer_request", "duplicate", "fraudulent", "service_disruption", "satisfaction_guarantee", "other"] as const; +export const REFUND_REASONS = [ + "customer_request", + "duplicate", + "fraudulent", + "service_disruption", + "satisfaction_guarantee", + "other", +] as const; export type RefundReasonInput = (typeof REFUND_REASONS)[number]; -export type CourseRefundResult = RefundBreakdown & { refundId: string; enrollmentId: string }; +export type CourseRefundResult = { + refundId: string; + enrollmentId: string; + mode: RefundMode; + refundCents: number; +}; -/** What a refund of this enrollment would return, without making it. For a confirm screen. */ -export async function previewCourseRefund(enrollmentId: string): Promise { +// ─── Preview ────────────────────────────────────────────────────────────────── + +/** + * Returns all three option amounts for the confirm dialog without issuing anything. + * Uses the live saved policy so the UI shows the same numbers as the actual refund. + */ +export async function previewCourseRefund(enrollmentId: string): Promise { const payment = await refundablePayment(enrollmentId); - return refundBreakdown(payment.amountCents); + const policy = await getRefundPolicy(); + // alreadyRefundedCents is 0 for the current single-refund model; kept for future partial refunds. + return allRefundOptions(payment.amountCents, 0, policy); } +// ─── Issue refund ───────────────────────────────────────────────────────────── + +export type RefundInput = { + mode: RefundMode; + /** Required when mode === "CUSTOM". Max = order amount. */ + customCents?: number; + reason?: RefundReasonInput; + comment?: string | null; + /** End the learner's access immediately. Defaults to true. */ + revokeAccess?: boolean; +}; + /** - * Refund a course bought through Polar, keeping back Polar’s payment fees (see refund-policy.ts), and - * end the learner's access straight away. Polar then sends order.refunded; that webhook finds the + * Refund a course bought through Polar. + * + * - FULL: returns everything remaining; Edorax absorbs the fees. Requires a reason. + * - STANDARD: returns paid minus the saved policy fees. No reason required. + * - CUSTOM: admin types an amount from $0.01 up to the full order amount. Requires a reason. + * + * Access is ended immediately (revokeAccess defaults to true). The Polar webhook then finds the * payment already REFUNDED and changes nothing. */ export async function refundCoursePayment( enrollmentId: string, actor: AdminActor, - input: { reason?: RefundReasonInput; comment?: string | null } = {}, + input: RefundInput, ): Promise { requirePolarConfig(); + + const { mode, customCents, reason, comment, revokeAccess = true } = input; + + // Validate that a reason is provided for FULL and CUSTOM modes. + if ((mode === "FULL" || mode === "CUSTOM") && !reason) { + throw new BadRequestError( + `A reason is required for ${mode} refunds.`, + "REASON_REQUIRED", + ); + } + const payment = await refundablePayment(enrollmentId); - const breakdown = refundBreakdown(payment.amountCents); - if (breakdown.refundCents < 1) { - throw new BadRequestError("The fees kept back are as much as the payment, so there is nothing to refund.", "REFUND_TOO_SMALL"); + const policy = await getRefundPolicy(); + + let refundCents: number; + try { + refundCents = resolveRefundCents(mode, payment.amountCents, 0, policy, customCents); + } catch (err) { + const isInvalidAmount = err instanceof Error && err.message === "INVALID_AMOUNT"; + // For STANDARD mode, INVALID_AMOUNT means the fees ate the whole payment. + if (isInvalidAmount && mode === "STANDARD") { + throw new BadRequestError( + "The fees kept back are as much as the payment, so there is nothing to refund.", + "REFUND_TOO_SMALL", + ); + } + throw new BadRequestError( + "The refund amount is invalid or exceeds the order total.", + "REFUND_INVALID_AMOUNT", + ); + } + + if (refundCents < 1) { + throw new BadRequestError( + "The fees kept back are as much as the payment, so there is nothing to refund.", + "REFUND_TOO_SMALL", + ); } + // Build the Polar comment from the breakdown for Standard refunds. + const breakdown = refundBreakdown(payment.amountCents, policy); + const defaultComment = + mode === "STANDARD" + ? `Refund less fees: fixed ${breakdown.fixedFeeCents}c, international ${breakdown.internationalFeeCents}c, Polar ${breakdown.platformFeeCents}c, Edorax ${breakdown.edoraxFeeCents}c.` + : mode === "FULL" + ? "Full refund (Edorax absorbed fees)." + : `Custom refund of ${refundCents} cents.`; + const refund = await getPolarClient().refunds.create({ order_id: payment.providerRef, - amount: breakdown.refundCents, - reason: input.reason ?? "customer_request", - comment: - input.comment?.trim() || - `Refund less Polar fees: transaction ${breakdown.fixedFeeCents}, international ${breakdown.internationalFeeCents}, Polar ${breakdown.platformFeeCents} cents.`, - metadata: { enrollmentId, refundedBy: actor.id }, + amount: refundCents, + reason: reason ?? "customer_request", + comment: comment?.trim() || defaultComment, + metadata: { enrollmentId, refundedBy: actor.id, refundMode: mode }, }); - // The money has gone back. If the database write below fails, the order.refunded webhook still - // ends access, because the refund it reports is at the policy amount. + // Money has gone back. If the DB write below fails the order.refunded webhook still ends access, + // because refundCents >= Standard amount for FULL/STANDARD, and handles CUSTOM gracefully. await prisma.$transaction(async (tx) => { - await endAccessForRefund(tx, { id: enrollmentId, payment: { ...payment, provider: "polar" } }); + if (revokeAccess) { + await endAccessForRefund(tx, { id: enrollmentId, payment: { ...payment, provider: "polar" } }); + } await recordAdminAction(tx, { actor, action: ADMIN_AUDIT_ACTIONS.PAYMENT_REFUND, targetType: "Enrollment", targetId: enrollmentId, - summary: `Refunded ${breakdown.refundCents} of ${breakdown.paidCents} cents through Polar and removed course access.`, - metadata: { refundId: refund.id, orderId: payment.providerRef, ...breakdown, reason: input.reason ?? "customer_request" }, + summary: `Refunded ${refundCents} of ${payment.amountCents} cents (${mode}) through Polar${revokeAccess ? " and removed course access" : ""}.`, + metadata: { + refundId: refund.id, + orderId: payment.providerRef, + mode, + refundCents, + paidCents: payment.amountCents, + revokeAccess, + policySnapshot: policy, + reason: reason ?? "customer_request", + }, }); }); - return { ...breakdown, refundId: refund.id, enrollmentId }; + return { refundId: refund.id, enrollmentId, mode, refundCents }; } +// ─── Shared guard ───────────────────────────────────────────────────────────── + async function refundablePayment(enrollmentId: string) { - const enrollment = await prisma.enrollment.findUnique({ where: { id: enrollmentId }, include: { payment: true } }); + const enrollment = await prisma.enrollment.findUnique({ + where: { id: enrollmentId }, + include: { payment: true }, + }); if (!enrollment) throw new NotFoundError("Enrollment not found"); const payment = enrollment.payment; if (!payment || payment.provider !== "polar" || !payment.providerRef) { - throw new ConflictError("This enrollment was not paid through Polar, so it cannot be refunded here.", "NOT_A_POLAR_PAYMENT"); + throw new ConflictError( + "This enrollment was not paid through Polar, so it cannot be refunded here.", + "NOT_A_POLAR_PAYMENT", + ); } - if (payment.status === "REFUNDED") throw new ConflictError("This payment has already been refunded.", "ALREADY_REFUNDED"); - if (payment.status !== "SUCCEEDED") throw new ConflictError("Only a completed payment can be refunded.", "PAYMENT_NOT_COMPLETED"); + if (payment.status === "REFUNDED") + throw new ConflictError("This payment has already been refunded.", "ALREADY_REFUNDED"); + if (payment.status !== "SUCCEEDED") + throw new ConflictError("Only a completed payment can be refunded.", "PAYMENT_NOT_COMPLETED"); return { ...payment, providerRef: payment.providerRef }; } diff --git a/server/src/services/payments/refund-polar-order.ts b/server/src/services/payments/refund-polar-order.ts index 819757c91..3f389e297 100644 --- a/server/src/services/payments/refund-polar-order.ts +++ b/server/src/services/payments/refund-polar-order.ts @@ -1,7 +1,7 @@ import type { Prisma } from "../../generated/prisma/index.js"; import { prisma } from "../../db/prisma.js"; import { logger } from "../../utils/logger.js"; -import { refundEndsAccess } from "./refund-policy.js"; +import { getRefundPolicy, refundEndsAccess } from "./refund-policy.js"; export type PolarOrderRefundedInput = { orderId: string; @@ -58,9 +58,12 @@ export async function endAccessForRefund(tx: Prisma.TransactionClient, enrollmen } /** - * Polar reported order.refunded. A refund at or above the refund policy amount (paid minus the - * Polar’s payment fees kept back) ends access; a smaller one is goodwill and access stays. Idempotent, - * because Polar retries webhooks and the admin refund may already have ended access. + * Polar reported order.refunded. A refund at or above the Standard policy amount (paid minus fees) + * ends access; a smaller one is goodwill and access stays. Idempotent, because Polar retries + * webhooks and the admin refund may already have ended access. + * + * The access decision always uses the live saved policy so it stays consistent with admin-issued + * refunds even if the policy has been updated since the payment was made. */ export async function revokePolarOrderRefund(input: PolarOrderRefundedInput): Promise { const enrollmentIdFromMeta = metadataString(input.metadata, "enrollmentId"); @@ -89,7 +92,10 @@ export async function revokePolarOrderRefund(input: PolarOrderRefundedInput): Pr return { revoked: false, enrollmentId: enrollment.id, reason: "already-refunded" }; } - if (!refundEndsAccess({ status: input.status, refundedCents: input.refundedAmount, paidCents: enrollment.payment.amountCents })) { + // Load the live policy to decide the Standard threshold. + const policy = await getRefundPolicy(); + + if (!refundEndsAccess({ status: input.status, refundedCents: input.refundedAmount, paidCents: enrollment.payment.amountCents, policy })) { logger.info( { orderId: input.orderId, enrollmentId: enrollment.id, refundedAmount: input.refundedAmount, paidCents: enrollment.payment.amountCents }, "polar goodwill refund below the policy amount: course access kept", diff --git a/server/src/services/payments/refund-policy.ts b/server/src/services/payments/refund-policy.ts index 8d29e79d1..273561dc1 100644 --- a/server/src/services/payments/refund-policy.ts +++ b/server/src/services/payments/refund-policy.ts @@ -1,42 +1,183 @@ // How much of a course payment comes back on a refund. The fees on the sale are not returned: a -// fixed transaction fee per payment, an international card fee and Polar’s 5% fee: all charged by Polar, -// the payment handler, and not returned when a payment is refunded. Edorax adds no fee of its own. Change them -// here only; the admin refund, the webhook and any screen showing the amount all read these. +// fixed transaction fee per payment, an international card fee, Polar's 5% fee and Edorax's own +// fee (currently 0). These four values are stored in the database so an admin can update them; +// the defaults below seed the first run. The admin refund, the webhook and every preview screen +// all call getRefundPolicy() so they always read the same live values. -/** Kept back on every refund, in cents. */ -export const REFUND_FIXED_FEE_CENTS = 50; -/** Kept back on every refund, as a share of the amount paid: 1.5%, in basis points. */ -export const REFUND_INTERNATIONAL_FEE_BPS = 150; -/** Polar's own fee on the payment, kept back on every refund: 5%, in basis points. Not an Edorax fee. */ -export const REFUND_PLATFORM_FEE_BPS = 500; +import { prisma } from "../../db/prisma.js"; + +// ─── Policy type & defaults ─────────────────────────────────────────────────── + +export type RefundPolicy = { + /** Fixed transaction fee kept back on every refund, in cents. Default: 50 ($0.50). */ + fixedFeeCents: number; + /** International card fee kept back, in basis points. Default: 150 (1.5%). */ + internationalFeeBps: number; + /** Polar's platform fee kept back, in basis points. Default: 500 (5%). */ + polarFeeBps: number; + /** Edorax's own fee kept back, in basis points. Default: 0. */ + edoraxFeeBps: number; +}; + +export const DEFAULT_REFUND_POLICY: RefundPolicy = { + fixedFeeCents: 50, + internationalFeeBps: 150, + polarFeeBps: 500, + edoraxFeeBps: 0, +}; + +// Storage key used in the key-value settings table. +const POLICY_SETTING_KEY = "refund_policy"; + +// ─── Policy persistence ─────────────────────────────────────────────────────── + +/** Loads the saved refund policy, falling back to DEFAULT_REFUND_POLICY if none is saved yet. */ +export async function getRefundPolicy(): Promise { + const row = await prisma.appSetting.findUnique({ where: { key: POLICY_SETTING_KEY } }); + if (!row) return { ...DEFAULT_REFUND_POLICY }; + try { + const parsed: unknown = JSON.parse(row.value as string); + return validateRefundPolicy(parsed) ? (parsed as RefundPolicy) : { ...DEFAULT_REFUND_POLICY }; + } catch { + return { ...DEFAULT_REFUND_POLICY }; + } +} + +/** Persists a new refund policy. Throws when the values fail validation. */ +export async function saveRefundPolicy(policy: RefundPolicy): Promise { + if (!validateRefundPolicy(policy)) throw new Error("Invalid refund policy values."); + await prisma.appSetting.upsert({ + where: { key: POLICY_SETTING_KEY }, + update: { value: JSON.stringify(policy) }, + create: { key: POLICY_SETTING_KEY, value: JSON.stringify(policy) }, + }); +} + +/** + * Returns true when every field is a non-negative integer and the total percentage fee is under 100%. + * Used by the save endpoint and by getRefundPolicy to guard against corrupt stored values. + */ +export function validateRefundPolicy(policy: unknown): policy is RefundPolicy { + if (!policy || typeof policy !== "object") return false; + const p = policy as Record; + const fields: (keyof RefundPolicy)[] = ["fixedFeeCents", "internationalFeeBps", "polarFeeBps", "edoraxFeeBps"]; + for (const f of fields) { + if (!Number.isInteger(p[f]) || (p[f] as number) < 0) return false; + } + const totalBps = + (p.internationalFeeBps as number) + (p.polarFeeBps as number) + (p.edoraxFeeBps as number); + return totalBps < 10_000; // must stay under 100% +} + +// ─── Breakdown type & calculation ──────────────────────────────────────────── export type RefundBreakdown = { paidCents: number; fixedFeeCents: number; internationalFeeCents: number; platformFeeCents: number; - /** What the learner gets back. 0 when the fees would take all of it. */ + edoraxFeeCents: number; + /** What the learner gets back for a Standard refund. 0 when fees exceed the payment. */ refundCents: number; }; const share = (cents: number, bps: number) => Math.round((cents * bps) / 10_000); -/** The refund for a payment: paid − $0.50 − 1.5% − 5% of paid, each percentage rounded to the nearest cent. */ -export function refundBreakdown(paidCents: number): RefundBreakdown { +/** Breaks down the Standard refund amount for a given payment using a live policy (or default policy if omitted). */ +export function refundBreakdown(paidCents: number, policy: RefundPolicy = DEFAULT_REFUND_POLICY): RefundBreakdown { const paid = Math.max(0, Math.round(paidCents)); - const internationalFeeCents = share(paid, REFUND_INTERNATIONAL_FEE_BPS); - const platformFeeCents = share(paid, REFUND_PLATFORM_FEE_BPS); - const refundCents = Math.max(0, paid - REFUND_FIXED_FEE_CENTS - internationalFeeCents - platformFeeCents); - return { paidCents: paid, fixedFeeCents: REFUND_FIXED_FEE_CENTS, internationalFeeCents, platformFeeCents, refundCents }; + const internationalFeeCents = share(paid, policy.internationalFeeBps); + const platformFeeCents = share(paid, policy.polarFeeBps); + const edoraxFeeCents = share(paid, policy.edoraxFeeBps); + const refundCents = Math.max( + 0, + paid - policy.fixedFeeCents - internationalFeeCents - platformFeeCents - edoraxFeeCents, + ); + return { + paidCents: paid, + fixedFeeCents: policy.fixedFeeCents, + internationalFeeCents, + platformFeeCents, + edoraxFeeCents, + refundCents, + }; +} + +// ─── Three-mode refund resolution ──────────────────────────────────────────── + +export type RefundMode = "FULL" | "STANDARD" | "CUSTOM"; + +export type AllRefundOptions = { + /** Everything not yet refunded — Edorax absorbs fees. */ + fullCents: number; + /** Paid minus policy fees — the default selection. */ + standardCents: number; + /** Fee breakdown used to derive standardCents (for the UI). */ + breakdown: RefundBreakdown; + /** Ceiling for a custom amount (equals fullCents). */ + maxCustomCents: number; +}; + +/** Returns all three option amounts for the refund dialog, without issuing anything. */ +export function allRefundOptions( + paidCents: number, + alreadyRefundedCents: number, + policy: RefundPolicy, +): AllRefundOptions { + const max = Math.max(0, paidCents - alreadyRefundedCents); + const breakdown = refundBreakdown(paidCents, policy); + return { + fullCents: max, + standardCents: Math.min(breakdown.refundCents, max), + breakdown, + maxCustomCents: max, + }; } /** - * Whether a refund on an order ends the learner's access. A full refund does, and so does one at - * or above the policy amount, which is how every refund under this policy arrives: the fees kept - * back make it "partially refunded" to Polar. A smaller refund is goodwill and access stays. + * Resolves the actual refund amount for a given mode. + * - FULL: everything remaining (Edorax absorbs fees). + * - STANDARD: paid minus policy fees, capped at remaining. + * - CUSTOM: the value the admin typed, validated against 1..max. + * Throws "INVALID_AMOUNT" when the resolved amount is out of [1, max]. */ -export function refundEndsAccess(input: { status: string; refundedCents: number; paidCents: number }) { +export function resolveRefundCents( + mode: RefundMode, + paidCents: number, + alreadyRefundedCents: number, + policy: RefundPolicy, + customCents?: number, +): number { + const max = Math.max(0, paidCents - alreadyRefundedCents); + let amount: number; + if (mode === "FULL") { + amount = max; + } else if (mode === "STANDARD") { + amount = Math.min(refundBreakdown(paidCents, policy).refundCents, max); + } else { + if (customCents === undefined) throw new Error("CUSTOM mode requires customCents."); + amount = customCents; + } + if (!Number.isInteger(amount) || amount < 1 || amount > max) { + throw new Error("INVALID_AMOUNT"); + } + return amount; +} + +// ─── Webhook helper ─────────────────────────────────────────────────────────── + +/** + * Whether a Polar webhook refund ends the learner's access. + * A full ("refunded") status always does. A partial refund does when it reaches or exceeds the + * Standard policy amount. A smaller one is goodwill and access stays. + */ +export function refundEndsAccess(input: { + status: string; + refundedCents: number; + paidCents: number; + policy: RefundPolicy; +}) { if (input.status === "refunded") return true; - const policy = refundBreakdown(input.paidCents).refundCents; - return input.refundedCents > 0 && input.refundedCents >= policy; + const standard = refundBreakdown(input.paidCents, input.policy).refundCents; + return input.refundedCents > 0 && input.refundedCents >= standard; } diff --git a/server/src/shared/api/admin.ts b/server/src/shared/api/admin.ts index 642c381d5..ba4958c1a 100644 --- a/server/src/shared/api/admin.ts +++ b/server/src/shared/api/admin.ts @@ -240,13 +240,45 @@ export type AdminUserDetail = { coursesOwned: Array<{ id: string; title: string; slug: string; status: CourseStatus }>; }; -/** A refund less Polar’s fees on the payment: $0.50 transaction fee, 1.5% international fee, 5% Polar fee. */ +export type FeatureFlagInfo = { + key: string; + name: string; + description: string; + enabled: boolean; + category: "gamification" | "infra"; +}; + +export type AppSettingsView = { + refundPolicy: RefundPolicyView; + featureFlags: FeatureFlagInfo[]; + polar: { + configured: boolean; + environment: string; + }; +}; + +export type RefundPolicy = { + fixedFeeCents: number; + internationalFeeBps: number; + polarFeeBps: number; + edoraxFeeBps: number; +}; + +export type RefundPolicyView = { + policy: RefundPolicy; + example: { + paidCents: number; + standardRefundCents: number; + fullRefundCents: number; + }; +}; export type AdminRefundBreakdown = { currency: string; paidCents: number; fixedFeeCents: number; internationalFeeCents: number; platformFeeCents: number; + edoraxFeeCents: number; refundCents: number; }; diff --git a/server/src/validations/admin.ts b/server/src/validations/admin.ts index bf032dd03..eddb19b8c 100644 --- a/server/src/validations/admin.ts +++ b/server/src/validations/admin.ts @@ -263,3 +263,19 @@ export const desktopUpdatesBody = z.object({ }), }); export type DesktopUpdatesBody = z.infer; + +// ─── Refund policy ──────────────────────────────────────────────────────────── + +const bpsField = (name: string) => + z + .number({ message: `${name} must be a number` }) + .int({ message: `${name} must be an integer` }) + .min(0, { message: `${name} must be 0 or greater` }); + +export const refundPolicyBody = z.object({ + fixedFeeCents: z.number({ message: "fixedFeeCents must be a number" }).int().min(0), + internationalFeeBps: bpsField("internationalFeeBps"), + polarFeeBps: bpsField("polarFeeBps"), + edoraxFeeBps: bpsField("edoraxFeeBps"), +}); +export type RefundPolicyBody = z.infer; diff --git a/server/src/validations/enrollments.ts b/server/src/validations/enrollments.ts index 7271183a1..4ffde4df8 100644 --- a/server/src/validations/enrollments.ts +++ b/server/src/validations/enrollments.ts @@ -3,10 +3,32 @@ import { id, params } from "./common.js"; export const selfEnrollBody = z.object({ courseId: id, couponCode: z.string().trim().min(3).max(32).optional() }); export const enrollmentParams = params("enrollmentId"); -export const refundBody = z.object({ - reason: z.enum(["customer_request", "duplicate", "fraudulent", "service_disruption", "satisfaction_guarantee", "other"]).optional(), - comment: z.string().trim().max(500).optional(), -}); +export const refundBody = z + .object({ + /** Which of the three refund options the admin chose. Defaults to STANDARD. */ + mode: z.enum(["FULL", "STANDARD", "CUSTOM"]).default("STANDARD"), + /** Required when mode === "CUSTOM". Positive integer, max = order amount in cents. */ + customCents: z.number().int().min(1).optional(), + reason: z + .enum(["customer_request", "duplicate", "fraudulent", "service_disruption", "satisfaction_guarantee", "other"]) + .optional(), + comment: z.string().trim().max(500).optional(), + /** End the learner's access immediately. Defaults to true. */ + revokeAccess: z.boolean().default(true), + }) + .refine((b) => b.mode !== "CUSTOM" || b.customCents !== undefined, { + message: "customCents is required for CUSTOM refunds.", + path: ["customCents"], + }) + .refine((b) => b.mode !== "FULL" || b.reason !== undefined, { + message: "A reason is required for FULL refunds.", + path: ["reason"], + }) + .refine((b) => b.mode !== "CUSTOM" || b.reason !== undefined, { + message: "A reason is required for CUSTOM refunds.", + path: ["reason"], + }); +export type RefundBody = z.infer; /** Admin edit of an enrollment: course access and payment status only. Only the fields sent change. */ export const adminEnrollmentUpdateBody = z diff --git a/server/tests/unit/services/admin/users.test.ts b/server/tests/unit/services/admin/users.test.ts index 19c12542d..8567c8772 100644 --- a/server/tests/unit/services/admin/users.test.ts +++ b/server/tests/unit/services/admin/users.test.ts @@ -357,7 +357,15 @@ describe("confirmed-enrollment filtering in user list and detail", () => { const detail = await getUserDetail("user-1"); const refund = Object.fromEntries(detail.enrollments.map((row) => [row.id, row.refund])); - expect(refund.polar).toEqual({ currency: "USD", paidCents: 1000, fixedFeeCents: 50, internationalFeeCents: 15, platformFeeCents: 50, refundCents: 885 }); + expect(refund.polar).toEqual({ + currency: "USD", + paidCents: 1000, + fixedFeeCents: 50, + internationalFeeCents: 15, + platformFeeCents: 50, + edoraxFeeCents: 0, + refundCents: 885, + }); expect(refund.manual).toBeNull(); expect(refund.free).toBeNull(); expect(refund.tiny).toBeNull(); diff --git a/server/tests/unit/services/payments/refund-course-payment.test.ts b/server/tests/unit/services/payments/refund-course-payment.test.ts index d4d9f33a0..7df840287 100644 --- a/server/tests/unit/services/payments/refund-course-payment.test.ts +++ b/server/tests/unit/services/payments/refund-course-payment.test.ts @@ -7,6 +7,7 @@ const db = vi.hoisted(() => ({ })); const refundsCreate = vi.hoisted(() => vi.fn()); const recordAdminAction = vi.hoisted(() => vi.fn()); +const getRefundPolicyMock = vi.hoisted(() => vi.fn()); vi.mock("../../../../src/db/prisma.js", () => ({ prisma: db })); vi.mock("../../../../src/utils/logger.js", () => ({ logger: { warn: vi.fn(), info: vi.fn(), error: vi.fn() } })); @@ -18,55 +19,139 @@ vi.mock("../../../../src/services/admin/audit.js", () => ({ recordAdminAction, ADMIN_AUDIT_ACTIONS: { PAYMENT_REFUND: "payment.refund" }, })); +vi.mock("../../../../src/services/payments/refund-policy.js", async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, getRefundPolicy: getRefundPolicyMock }; +}); import { previewCourseRefund, refundCoursePayment } from "../../../../src/services/payments/refund-course-payment.js"; +import { DEFAULT_REFUND_POLICY } from "../../../../src/services/payments/refund-policy.js"; const admin = { id: "admin_1", email: "admin@example.com" }; const enrollment = (payment: Record = {}) => ({ id: "enr_1", lifecycle: "ACTIVE", - payment: { status: "SUCCEEDED", provider: "polar", providerRef: "ord_1", amountCents: 1000, instructorPayoutStatus: "PENDING", instructorShareCents: 700, ...payment }, + payment: { + status: "SUCCEEDED", + provider: "polar", + providerRef: "ord_1", + amountCents: 1000, + instructorPayoutStatus: "PENDING", + instructorShareCents: 700, + ...payment, + }, }); describe("refundCoursePayment", () => { beforeEach(() => { vi.clearAllMocks(); - db.$transaction.mockImplementation(async (fn) => fn(db)); + db.$transaction.mockImplementation(async (fn: (tx: typeof db) => Promise) => fn(db)); db.payment.updateMany.mockResolvedValue({ count: 1 }); refundsCreate.mockResolvedValue({ id: "ref_1" }); + getRefundPolicyMock.mockResolvedValue(DEFAULT_REFUND_POLICY); }); - it("refunds the payment less $0.50, 1.5% and 5% through Polar, ends access and records who did it", async () => { + // ─── STANDARD (default) ─────────────────────────────────────────────────── + + it("STANDARD: refunds paid minus fees ($0.50 + 1.5% + 5%), ends access and records who did it", async () => { db.enrollment.findUnique.mockResolvedValue(enrollment()); - const result = await refundCoursePayment("enr_1", admin, { reason: "customer_request" }); + const result = await refundCoursePayment("enr_1", admin, { mode: "STANDARD", reason: "customer_request" }); + // 1000 - 50 - 15 - 50 = 885 expect(refundsCreate).toHaveBeenCalledWith( - expect.objectContaining({ order_id: "ord_1", amount: 885, reason: "customer_request", metadata: { enrollmentId: "enr_1", refundedBy: "admin_1" } }), + expect.objectContaining({ order_id: "ord_1", amount: 885, metadata: expect.objectContaining({ enrollmentId: "enr_1", refundMode: "STANDARD" }) }), ); - expect(result).toMatchObject({ refundId: "ref_1", paidCents: 1000, fixedFeeCents: 50, internationalFeeCents: 15, platformFeeCents: 50, refundCents: 885 }); + expect(result).toMatchObject({ refundId: "ref_1", mode: "STANDARD", refundCents: 885 }); expect(db.payment.updateMany).toHaveBeenCalledWith(expect.objectContaining({ data: expect.objectContaining({ status: "REFUNDED" }) })); expect(db.enrollment.update).toHaveBeenCalledWith({ where: { id: "enr_1" }, data: { lifecycle: "CANCELLED", status: "DROPPED" } }); expect(recordAdminAction).toHaveBeenCalledWith(db, expect.objectContaining({ actor: admin, action: "payment.refund", targetId: "enr_1" })); }); - it("previews the same amounts without refunding", async () => { + // ─── FULL ───────────────────────────────────────────────────────────────── + + it("FULL: returns everything and ends access", async () => { + db.enrollment.findUnique.mockResolvedValue(enrollment()); + + const result = await refundCoursePayment("enr_1", admin, { mode: "FULL", reason: "customer_request" }); + + expect(refundsCreate).toHaveBeenCalledWith(expect.objectContaining({ amount: 1000 })); + expect(result).toMatchObject({ mode: "FULL", refundCents: 1000 }); + expect(db.payment.updateMany).toHaveBeenCalled(); + }); + + it("FULL: requires a reason", async () => { + db.enrollment.findUnique.mockResolvedValue(enrollment()); + await expect(refundCoursePayment("enr_1", admin, { mode: "FULL" })).rejects.toThrow(/reason/i); + expect(refundsCreate).not.toHaveBeenCalled(); + }); + + // ─── CUSTOM ─────────────────────────────────────────────────────────────── + + it("CUSTOM: refunds the exact amount typed, capped at order total", async () => { + db.enrollment.findUnique.mockResolvedValue(enrollment()); + + const result = await refundCoursePayment("enr_1", admin, { + mode: "CUSTOM", + customCents: 600, + reason: "satisfaction_guarantee", + }); + + expect(refundsCreate).toHaveBeenCalledWith(expect.objectContaining({ amount: 600 })); + expect(result).toMatchObject({ mode: "CUSTOM", refundCents: 600 }); + }); + + it("CUSTOM at the maximum (order amount) succeeds", async () => { + db.enrollment.findUnique.mockResolvedValue(enrollment()); + const result = await refundCoursePayment("enr_1", admin, { + mode: "CUSTOM", + customCents: 1000, + reason: "customer_request", + }); + expect(result.refundCents).toBe(1000); + }); + + it("CUSTOM above the order total is rejected", async () => { + db.enrollment.findUnique.mockResolvedValue(enrollment()); + await expect( + refundCoursePayment("enr_1", admin, { mode: "CUSTOM", customCents: 1001, reason: "other" }), + ).rejects.toThrow(/invalid/i); + expect(refundsCreate).not.toHaveBeenCalled(); + }); + + it("CUSTOM: requires a reason", async () => { + db.enrollment.findUnique.mockResolvedValue(enrollment()); + await expect(refundCoursePayment("enr_1", admin, { mode: "CUSTOM", customCents: 500 })).rejects.toThrow(/reason/i); + expect(refundsCreate).not.toHaveBeenCalled(); + }); + + // ─── Preview ────────────────────────────────────────────────────────────── + + it("previews all three amounts without refunding", async () => { db.enrollment.findUnique.mockResolvedValue(enrollment()); - await expect(previewCourseRefund("enr_1")).resolves.toEqual({ paidCents: 1000, fixedFeeCents: 50, internationalFeeCents: 15, platformFeeCents: 50, refundCents: 885 }); + const preview = await previewCourseRefund("enr_1"); + + expect(preview).toMatchObject({ + fullCents: 1000, + standardCents: 885, + maxCustomCents: 1000, + }); expect(refundsCreate).not.toHaveBeenCalled(); }); - it("refuses when the fees would take the whole payment", async () => { + // ─── Validations ────────────────────────────────────────────────────────── + + it("refuses when fees would take the whole payment", async () => { db.enrollment.findUnique.mockResolvedValue(enrollment({ amountCents: 50 })); - await expect(refundCoursePayment("enr_1", admin)).rejects.toThrow(/nothing to refund/); + await expect(refundCoursePayment("enr_1", admin, { mode: "STANDARD" })).rejects.toThrow(/nothing to refund/); expect(refundsCreate).not.toHaveBeenCalled(); }); - it("refuses a payment that is already refunded, or not made through Polar", async () => { + it("refuses a payment that is already refunded or not made through Polar", async () => { db.enrollment.findUnique.mockResolvedValueOnce(enrollment({ status: "REFUNDED" })); - await expect(refundCoursePayment("enr_1", admin)).rejects.toThrow(/already been refunded/); + await expect(refundCoursePayment("enr_1", admin, { mode: "STANDARD" })).rejects.toThrow(/already been refunded/); db.enrollment.findUnique.mockResolvedValueOnce(enrollment({ provider: "manual" })); - await expect(refundCoursePayment("enr_1", admin)).rejects.toThrow(/not paid through Polar/); + await expect(refundCoursePayment("enr_1", admin, { mode: "STANDARD" })).rejects.toThrow(/not paid through Polar/); expect(refundsCreate).not.toHaveBeenCalled(); }); @@ -74,7 +159,19 @@ describe("refundCoursePayment", () => { db.enrollment.findUnique.mockResolvedValue(enrollment()); refundsCreate.mockRejectedValue(new Error("Polar said no")); - await expect(refundCoursePayment("enr_1", admin)).rejects.toThrow(/Polar said no/); + await expect(refundCoursePayment("enr_1", admin, { mode: "STANDARD" })).rejects.toThrow(/Polar said no/); + expect(db.payment.updateMany).not.toHaveBeenCalled(); + expect(db.enrollment.update).not.toHaveBeenCalled(); + }); + + // ─── revokeAccess = false ───────────────────────────────────────────────── + + it("when revokeAccess is false, Polar is called but enrollment is not cancelled", async () => { + db.enrollment.findUnique.mockResolvedValue(enrollment()); + + await refundCoursePayment("enr_1", admin, { mode: "STANDARD", revokeAccess: false }); + + expect(refundsCreate).toHaveBeenCalled(); expect(db.payment.updateMany).not.toHaveBeenCalled(); expect(db.enrollment.update).not.toHaveBeenCalled(); }); diff --git a/server/tests/unit/services/payments/refund-polar-order.test.ts b/server/tests/unit/services/payments/refund-polar-order.test.ts index b80fb6df4..865df81c7 100644 --- a/server/tests/unit/services/payments/refund-polar-order.test.ts +++ b/server/tests/unit/services/payments/refund-polar-order.test.ts @@ -6,30 +6,54 @@ const db = vi.hoisted(() => ({ $transaction: vi.fn(), })); const logger = vi.hoisted(() => ({ warn: vi.fn(), info: vi.fn(), error: vi.fn() })); +const getRefundPolicyMock = vi.hoisted(() => vi.fn()); vi.mock("../../../../src/db/prisma.js", () => ({ prisma: db })); vi.mock("../../../../src/utils/logger.js", () => ({ logger })); +vi.mock("../../../../src/services/payments/refund-policy.js", async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, getRefundPolicy: getRefundPolicyMock }; +}); import { revokePolarOrderRefund } from "../../../../src/services/payments/refund-polar-order.js"; +import { DEFAULT_REFUND_POLICY } from "../../../../src/services/payments/refund-policy.js"; + +const P = DEFAULT_REFUND_POLICY; const paidEnrollment = (payment: Record = {}) => ({ id: "enr_1", lifecycle: "ACTIVE", - payment: { status: "SUCCEEDED", provider: "polar", providerRef: "ord_1", amountCents: 1000, instructorPayoutStatus: "PENDING", instructorShareCents: 700, ...payment }, + payment: { + status: "SUCCEEDED", + provider: "polar", + providerRef: "ord_1", + amountCents: 1000, + instructorPayoutStatus: "PENDING", + instructorShareCents: 700, + ...payment, + }, }); -// $10.00 paid, refunded by the policy: 1000 - 50 - 15 - 50 = 885 cents, which Polar calls partially refunded. -const policyRefund = { orderId: "ord_1", checkoutId: "chk_1", metadata: { enrollmentId: "enr_1" }, status: "partially_refunded", refundedAmount: 885, totalAmount: 1000 }; +// $10.00 paid; Standard refund = 1000 - 50 - 15 - 50 = 885 cents → Polar calls it "partially_refunded". +const policyRefund = { + orderId: "ord_1", + checkoutId: "chk_1", + metadata: { enrollmentId: "enr_1" }, + status: "partially_refunded", + refundedAmount: 885, + totalAmount: 1000, +}; describe("revokePolarOrderRefund", () => { beforeEach(() => { vi.clearAllMocks(); - db.$transaction.mockImplementation(async (fn) => fn(db)); + db.$transaction.mockImplementation(async (fn: (tx: typeof db) => Promise) => fn(db)); db.enrollment.findFirst.mockResolvedValue(null); db.payment.updateMany.mockResolvedValue({ count: 1 }); + getRefundPolicyMock.mockResolvedValue(P); }); - it("removes access for a refund at the policy amount and cancels an unpaid instructor payout", async () => { + it("removes access for a refund at the Standard policy amount and cancels an unpaid instructor payout", async () => { db.enrollment.findUnique.mockResolvedValue(paidEnrollment()); await expect(revokePolarOrderRefund(policyRefund)).resolves.toEqual({ revoked: true, enrollmentId: "enr_1" }); @@ -40,19 +64,22 @@ describe("revokePolarOrderRefund", () => { expect(db.enrollment.update).toHaveBeenCalledWith({ where: { id: "enr_1" }, data: { lifecycle: "CANCELLED", status: "DROPPED" } }); }); - it("removes access for a full refund too", async () => { + it("removes access for a full (status=refunded) refund too", async () => { db.enrollment.findUnique.mockResolvedValue(paidEnrollment()); const result = await revokePolarOrderRefund({ ...policyRefund, status: "refunded", refundedAmount: 1000 }); expect(result).toEqual({ revoked: true, enrollmentId: "enr_1" }); }); it("finds the enrollment by order id when the metadata has none", async () => { - db.enrollment.findFirst.mockImplementation(async ({ where }) => (where.payment.providerRef === "ord_1" ? paidEnrollment() : null)); + db.enrollment.findFirst.mockImplementation( + async ({ where }: { where: { payment: { providerRef: string } } }) => + where.payment.providerRef === "ord_1" ? paidEnrollment() : null, + ); const result = await revokePolarOrderRefund({ ...policyRefund, metadata: null }); expect(result).toEqual({ revoked: true, enrollmentId: "enr_1" }); }); - it("keeps access for a goodwill refund below the policy amount", async () => { + it("keeps access for a goodwill refund below the Standard amount", async () => { db.enrollment.findUnique.mockResolvedValue(paidEnrollment()); const result = await revokePolarOrderRefund({ ...policyRefund, refundedAmount: 300 }); @@ -60,6 +87,16 @@ describe("revokePolarOrderRefund", () => { expect(db.payment.updateMany).not.toHaveBeenCalled(); }); + it("uses the live policy to decide the threshold (changed edoraxFeeBps lowers the threshold)", async () => { + db.enrollment.findUnique.mockResolvedValue(paidEnrollment()); + // With edoraxFeeBps=200, Standard for $10 = 865 + getRefundPolicyMock.mockResolvedValue({ ...P, edoraxFeeBps: 200 }); + + // 884 would be goodwill under the old policy (threshold 885), but above the new one (865) + const result = await revokePolarOrderRefund({ ...policyRefund, refundedAmount: 870 }); + expect(result).toEqual({ revoked: true, enrollmentId: "enr_1" }); + }); + it("changes nothing when the admin refund already ended access", async () => { db.enrollment.findUnique.mockResolvedValue({ ...paidEnrollment({ status: "REFUNDED" }), lifecycle: "CANCELLED" }); @@ -68,7 +105,7 @@ describe("revokePolarOrderRefund", () => { expect(db.$transaction).not.toHaveBeenCalled(); }); - it("changes nothing when another delivery won the race", async () => { + it("changes nothing when another delivery won the race (idempotency)", async () => { db.enrollment.findUnique.mockResolvedValue(paidEnrollment()); db.payment.updateMany.mockResolvedValue({ count: 0 }); @@ -87,8 +124,14 @@ describe("revokePolarOrderRefund", () => { db.enrollment.findUnique.mockResolvedValue(paidEnrollment({ instructorPayoutStatus: "PAID" })); await revokePolarOrderRefund(policyRefund); - expect(db.payment.updateMany).toHaveBeenCalledWith({ where: { enrollmentId: "enr_1", status: "SUCCEEDED" }, data: { status: "REFUNDED" } }); - expect(logger.warn).toHaveBeenCalledWith(expect.objectContaining({ enrollmentId: "enr_1" }), expect.stringMatching(/manual adjustment/)); + expect(db.payment.updateMany).toHaveBeenCalledWith({ + where: { enrollmentId: "enr_1", status: "SUCCEEDED" }, + data: { status: "REFUNDED" }, + }); + expect(logger.warn).toHaveBeenCalledWith( + expect.objectContaining({ enrollmentId: "enr_1" }), + expect.stringMatching(/manual adjustment/), + ); }); it("reports an order it cannot match without failing", async () => { diff --git a/server/tests/unit/services/payments/refund-policy.test.ts b/server/tests/unit/services/payments/refund-policy.test.ts index ff251b3fb..1883e036a 100644 --- a/server/tests/unit/services/payments/refund-policy.test.ts +++ b/server/tests/unit/services/payments/refund-policy.test.ts @@ -1,31 +1,177 @@ import { describe, expect, it } from "vitest"; -import { refundBreakdown, refundEndsAccess } from "../../../../src/services/payments/refund-policy.js"; +import { + DEFAULT_REFUND_POLICY, + allRefundOptions, + refundBreakdown, + refundEndsAccess, + resolveRefundCents, + validateRefundPolicy, + type RefundPolicy, +} from "../../../../src/services/payments/refund-policy.js"; + +// ─── Helpers ────────────────────────────────────────────────────────────────── + +const P = DEFAULT_REFUND_POLICY; // fixedFeeCents:50, international:150bps, polar:500bps, edorax:0bps +const INTL: RefundPolicy = { ...P, internationalFeeBps: 150 }; +const DOMESTIC: RefundPolicy = { ...P, internationalFeeBps: 0 }; + +// ─── refundBreakdown ────────────────────────────────────────────────────────── describe("refundBreakdown", () => { - it("keeps back $0.50, 1.5% and the 5% platform fee of what was paid", () => { - expect(refundBreakdown(1000)).toEqual({ paidCents: 1000, fixedFeeCents: 50, internationalFeeCents: 15, platformFeeCents: 50, refundCents: 885 }); - expect(refundBreakdown(4999).refundCents).toBe(4999 - 50 - 75 - 250); + it("keeps back $0.50, 1.5% international and 5% polar from a $10.00 payment", () => { + // 1000 - 50 - 15 - 50 - 0 = 885 + expect(refundBreakdown(1000, P)).toEqual({ + paidCents: 1000, + fixedFeeCents: 50, + internationalFeeCents: 15, + platformFeeCents: 50, + edoraxFeeCents: 0, + refundCents: 885, + }); + }); + + it("omits the international fee when internationalFeeBps is 0 (domestic)", () => { + // 1000 - 50 - 0 - 50 - 0 = 900 + expect(refundBreakdown(1000, DOMESTIC)).toMatchObject({ internationalFeeCents: 0, refundCents: 900 }); + }); + + it("includes Edorax fee when edoraxFeeBps is non-zero", () => { + const p: RefundPolicy = { ...P, edoraxFeeBps: 200 }; // extra 2% + // 1000 - 50 - 15 - 50 - 20 = 865 + expect(refundBreakdown(1000, p)).toMatchObject({ edoraxFeeCents: 20, refundCents: 865 }); }); it("rounds the international fee to the nearest cent", () => { - expect(refundBreakdown(100).internationalFeeCents).toBe(2); // 1.5 cents - expect(refundBreakdown(1033).internationalFeeCents).toBe(15); // 15.495 cents + expect(refundBreakdown(100, P).internationalFeeCents).toBe(2); // 1.5 → rounds to 2 + expect(refundBreakdown(1033, P).internationalFeeCents).toBe(15); // 15.495 → rounds to 15 + }); + + it("never goes below zero when fees are as much as or more than the payment", () => { + expect(refundBreakdown(50, P).refundCents).toBe(0); + expect(refundBreakdown(0, P).refundCents).toBe(0); + }); + + it("changes outcome when any of the four fee fields change", () => { + const base = refundBreakdown(2000, P).refundCents; + expect(refundBreakdown(2000, { ...P, fixedFeeCents: 100 }).refundCents).toBe(base - 50); + expect(refundBreakdown(2000, { ...P, internationalFeeBps: 300 }).refundCents).toBeLessThan(base); + expect(refundBreakdown(2000, { ...P, polarFeeBps: 1000 }).refundCents).toBeLessThan(base); + expect(refundBreakdown(2000, { ...P, edoraxFeeBps: 100 }).refundCents).toBeLessThan(base); + }); +}); + +// ─── validateRefundPolicy ───────────────────────────────────────────────────── + +describe("validateRefundPolicy", () => { + it("accepts the default policy", () => { + expect(validateRefundPolicy(DEFAULT_REFUND_POLICY)).toBe(true); + }); + + it("rejects negative values", () => { + expect(validateRefundPolicy({ ...P, fixedFeeCents: -1 })).toBe(false); + expect(validateRefundPolicy({ ...P, edoraxFeeBps: -50 })).toBe(false); + }); + + it("rejects non-integer values", () => { + expect(validateRefundPolicy({ ...P, fixedFeeCents: 0.5 })).toBe(false); + expect(validateRefundPolicy({ ...P, polarFeeBps: 1.5 })).toBe(false); + }); + + it("rejects when total percentage >= 100%", () => { + // 10000 bps = 100%; not valid + expect(validateRefundPolicy({ ...P, internationalFeeBps: 5000, polarFeeBps: 5000, edoraxFeeBps: 0 })).toBe(false); + }); + + it("rejects non-objects", () => { + expect(validateRefundPolicy(null)).toBe(false); + expect(validateRefundPolicy("string")).toBe(false); + expect(validateRefundPolicy(42)).toBe(false); + }); +}); + +// ─── allRefundOptions ───────────────────────────────────────────────────────── + +describe("allRefundOptions", () => { + it("returns all three amounts and maxCustomCents", () => { + const opts = allRefundOptions(1000, 0, P); + expect(opts.fullCents).toBe(1000); + expect(opts.standardCents).toBe(885); // 1000-50-15-50 + expect(opts.maxCustomCents).toBe(1000); + expect(opts.breakdown.refundCents).toBe(885); + }); + + it("caps fullCents by prior refunds", () => { + const opts = allRefundOptions(1000, 300, P); + expect(opts.fullCents).toBe(700); + expect(opts.maxCustomCents).toBe(700); + }); + + it("caps standardCents at the remaining balance after prior refunds", () => { + // Standard for $10 = 885; if 300 already refunded, remaining = 700, standard is capped at 700 + const opts = allRefundOptions(1000, 300, P); + expect(opts.standardCents).toBe(700); + }); +}); + +// ─── resolveRefundCents ─────────────────────────────────────────────────────── + +describe("resolveRefundCents", () => { + it("FULL returns everything remaining", () => { + expect(resolveRefundCents("FULL", 1000, 0, P)).toBe(1000); + }); + + it("FULL after a prior partial refund returns only what remains", () => { + expect(resolveRefundCents("FULL", 1000, 115, P)).toBe(885); + }); + + it("STANDARD returns paid minus policy fees", () => { + expect(resolveRefundCents("STANDARD", 1000, 0, P)).toBe(885); }); - it("never goes below zero when the fees are as much as the payment", () => { - expect(refundBreakdown(50).refundCents).toBe(0); - expect(refundBreakdown(0).refundCents).toBe(0); + it("CUSTOM returns exactly the custom amount when valid", () => { + expect(resolveRefundCents("CUSTOM", 1000, 0, P, 500)).toBe(500); + }); + + it("CUSTOM at the maximum (order amount) succeeds", () => { + expect(resolveRefundCents("CUSTOM", 1000, 0, P, 1000)).toBe(1000); + }); + + it("CUSTOM above the maximum throws INVALID_AMOUNT", () => { + expect(() => resolveRefundCents("CUSTOM", 1000, 0, P, 1001)).toThrow("INVALID_AMOUNT"); + }); + + it("CUSTOM of 0 throws INVALID_AMOUNT", () => { + expect(() => resolveRefundCents("CUSTOM", 1000, 0, P, 0)).toThrow("INVALID_AMOUNT"); + }); + + it("CUSTOM without customCents throws", () => { + expect(() => resolveRefundCents("CUSTOM", 1000, 0, P, undefined)).toThrow(); }); }); +// ─── refundEndsAccess ───────────────────────────────────────────────────────── + describe("refundEndsAccess", () => { - it("ends access for a full refund or one at the policy amount", () => { - expect(refundEndsAccess({ status: "refunded", refundedCents: 1000, paidCents: 1000 })).toBe(true); - expect(refundEndsAccess({ status: "partially_refunded", refundedCents: 885, paidCents: 1000 })).toBe(true); + it('ends access for status "refunded" regardless of amount', () => { + expect(refundEndsAccess({ status: "refunded", refundedCents: 1000, paidCents: 1000, policy: P })).toBe(true); + expect(refundEndsAccess({ status: "refunded", refundedCents: 1, paidCents: 1000, policy: P })).toBe(true); + }); + + it("ends access for a partial refund at or above the standard amount", () => { + expect(refundEndsAccess({ status: "partially_refunded", refundedCents: 885, paidCents: 1000, policy: P })).toBe(true); + expect(refundEndsAccess({ status: "partially_refunded", refundedCents: 900, paidCents: 1000, policy: P })).toBe(true); + }); + + it("keeps access for a goodwill refund below the standard amount", () => { + expect(refundEndsAccess({ status: "partially_refunded", refundedCents: 884, paidCents: 1000, policy: P })).toBe(false); + expect(refundEndsAccess({ status: "partially_refunded", refundedCents: 0, paidCents: 1000, policy: P })).toBe(false); }); - it("keeps access for a smaller goodwill refund", () => { - expect(refundEndsAccess({ status: "partially_refunded", refundedCents: 884, paidCents: 1000 })).toBe(false); - expect(refundEndsAccess({ status: "partially_refunded", refundedCents: 0, paidCents: 30 })).toBe(false); + it("uses the live policy, so changing fees changes the threshold", () => { + // With edoraxFeeBps=200 (extra 2%), standard for $10 = 865 + const strictPolicy: RefundPolicy = { ...P, edoraxFeeBps: 200 }; + expect(refundEndsAccess({ status: "partially_refunded", refundedCents: 865, paidCents: 1000, policy: strictPolicy })).toBe(true); + // 885 (old standard) would still be above the new 865 threshold + expect(refundEndsAccess({ status: "partially_refunded", refundedCents: 864, paidCents: 1000, policy: strictPolicy })).toBe(false); }); }); From a8c167571edcd584c2320169cfef3a14f8540f18 Mon Sep 17 00:00:00 2001 From: ASIF RAZA Date: Tue, 17 Nov 2026 23:11:56 +0500 Subject: [PATCH 3/8] Merge remote-tracking branch 'origin/main' into polar-refunds --- .github/workflows/desktop-ci.yml | 2 +- .github/workflows/desktop-release.yml | 47 +- desktop/.gitignore | 3 + desktop/forge.config.mts | 39 +- desktop/package.json | 7 +- desktop/packaging/rpm.spec.ejs | 64 ++ desktop/pnpm-lock.yaml | 32 +- desktop/pnpm-workspace.yaml | 1 + desktop/scripts/stage-ide.mjs | 39 + desktop/src/domain/leaderboard.ts | 35 +- desktop/src/domain/shell-labs.ts | 4 + desktop/src/ide/runtime.ts | 9 +- desktop/src/main.ts | 15 + desktop/src/preload.ts | 2 + .../src/ui/leaderboard/LeaderboardPage.tsx | 3 +- .../src/ui/leaderboard/LeaderboardParts.tsx | 121 +++- desktop/src/ui/shell-labs/ShellLabs.tsx | 20 +- desktop/src/ui/shell-labs/progress.ts | 35 +- desktop/tests/lab-progress.test.ts | 73 ++ docs/12-course-variants-and-publishing.mdx | 15 + docs/14-gamification.mdx | 27 +- docs/gamification-todo.md | 53 +- .../(admin)/admin/desktop-updates/page.tsx | 40 +- .../app/(learn)/(catalog)/labs/shell/page.tsx | 45 +- .../app/(learn)/(main)/highlights/page.tsx | 22 + .../[courseSlug]/[chapterSlug]/page.tsx | 1 + .../admin/desktop-updates-panel.tsx | 683 ++++++------------ .../components/learn/chapter-highlights.tsx | 639 ++++++++++++++++ .../components/learn/chapter-reader-shell.tsx | 10 + .../learn/dashboard/league-goal-card.tsx | 79 ++ .../learn/dashboard/mentee-dashboard.tsx | 2 + .../components/learn/highlights-library.tsx | 271 +++++++ .../leaderboard/leaderboard-league-card.tsx | 182 ++++- .../learn/leaderboard/leaderboard-page.tsx | 4 +- .../learn/leaderboard/league-badge.tsx | 50 ++ .../leaderboard/use-leaderboard-confetti.ts | 3 +- .../learn/mentee-workspace-shell.tsx | 3 +- frontend/src/lib/highlight-locate.ts | 97 +++ frontend/src/lib/learn-areas.ts | 4 +- frontend/src/server/actions/highlights.ts | 68 ++ frontend/src/shared/api/gamification.ts | 29 +- frontend/src/shared/api/learner.ts | 3 +- frontend/src/shared/api/reader.ts | 11 + .../src/shared/gamification/achievements.ts | 20 +- frontend/src/shared/gamification/leagues.ts | 53 +- .../admin/desktop-updates-page.test.ts | 36 +- .../tests/unit/learn/highlight-locate.test.ts | 50 ++ server/.env.example | 2 + .../migration.sql | 38 + .../migration.sql | 11 + .../migration.sql | 6 + .../migration.sql | 12 + server/prisma/schema.prisma | 52 ++ server/scripts/course-source.ts | 20 +- server/src/config/env.ts | 8 + server/src/controllers/chapters.ts | 41 ++ server/src/controllers/learner.ts | 5 + server/src/controllers/shell-labs.ts | 12 + server/src/routes/v1/chapters.ts | 11 + server/src/routes/v1/learner.ts | 7 +- server/src/routes/v1/shell-labs.ts | 2 + server/src/services/chapters/highlights.ts | 188 +++++ server/src/services/chapters/reader.ts | 12 +- server/src/services/courses/releases.ts | 16 +- server/src/services/gamification/flags.ts | 2 + .../gamification/leaderboard-categories.ts | 59 +- server/src/services/gamification/league.ts | 61 +- .../src/services/learner/dashboard-model.ts | 6 +- .../services/learner/load-mentee-dashboard.ts | 38 +- server/src/services/shell-labs.service.ts | 35 + server/src/services/teach/course-import.ts | 3 +- .../services/teach/course-update-matching.ts | 7 + server/src/services/teach/course-update.ts | 1 + .../services/teach/publish-course-release.ts | 23 +- server/src/shared/api/gamification.ts | 29 +- server/src/shared/api/learner.ts | 3 +- server/src/shared/api/reader.ts | 11 + .../src/shared/gamification/achievements.ts | 20 +- server/src/shared/gamification/leagues.ts | 53 +- server/src/validations/chapters.ts | 17 + server/tests/api/chapter-highlights.test.ts | 178 +++++ .../api/course-remove-by-address.test.ts | 131 ++++ server/tests/api/gamification.test.ts | 4 +- server/tests/api/leaderboard-hub.test.ts | 106 ++- server/tests/api/shell-lab-progress.test.ts | 74 ++ .../scripts/course-manifest-family.test.ts | 9 + .../unit/services/gamification/pure.test.ts | 36 + .../shared/gamification/achievements.test.ts | 44 ++ 88 files changed, 3776 insertions(+), 668 deletions(-) create mode 100644 desktop/packaging/rpm.spec.ejs create mode 100644 desktop/scripts/stage-ide.mjs create mode 100644 desktop/tests/lab-progress.test.ts create mode 100644 frontend/src/app/(learn)/(main)/highlights/page.tsx create mode 100644 frontend/src/components/learn/chapter-highlights.tsx create mode 100644 frontend/src/components/learn/dashboard/league-goal-card.tsx create mode 100644 frontend/src/components/learn/highlights-library.tsx create mode 100644 frontend/src/components/learn/leaderboard/league-badge.tsx create mode 100644 frontend/src/lib/highlight-locate.ts create mode 100644 frontend/src/server/actions/highlights.ts create mode 100644 frontend/tests/unit/learn/highlight-locate.test.ts create mode 100644 server/prisma/migrations/20261105121548_add_chapter_highlights/migration.sql create mode 100644 server/prisma/migrations/20261114140000_shell_lab_progress/migration.sql create mode 100644 server/prisma/migrations/20261116090000_expand_league_tiers/migration.sql create mode 100644 server/prisma/migrations/20261118100000_chapter_highlight_unique/migration.sql create mode 100644 server/src/services/chapters/highlights.ts create mode 100644 server/tests/api/chapter-highlights.test.ts create mode 100644 server/tests/api/course-remove-by-address.test.ts create mode 100644 server/tests/api/shell-lab-progress.test.ts create mode 100644 server/tests/unit/shared/gamification/achievements.test.ts diff --git a/.github/workflows/desktop-ci.yml b/.github/workflows/desktop-ci.yml index 130270bd2..a21b3348c 100644 --- a/.github/workflows/desktop-ci.yml +++ b/.github/workflows/desktop-ci.yml @@ -5,7 +5,7 @@ name: Desktop checks # server/src/shared/** code the desktop app imports from the server # this workflow and the release workflow # A change to only the server, the web app or the docs does not start this workflow. -# The release builds (Windows, macOS, Linux) are a separate workflow that runs on a tag or by hand. +# The release builds (Windows, macOS, Linux) are a separate workflow that runs only by hand. on: pull_request: diff --git a/.github/workflows/desktop-release.yml b/.github/workflows/desktop-release.yml index 7f56a0172..14ca44232 100644 --- a/.github/workflows/desktop-release.yml +++ b/.github/workflows/desktop-release.yml @@ -1,9 +1,16 @@ name: Desktop release -# Builds the Edorax desktop app for Windows, macOS and Linux and attaches the installers to a GitHub release. +# Builds the Edorax desktop app for Windows, macOS and Linux. # -# Make a release: git tag desktop-v0.1.0 && git push origin desktop-v0.1.0 -# Try the builds: run this workflow by hand (Actions tab). The installers are kept as workflow artifacts. +# Make a release: bump "version" in desktop/package.json, commit, then +# git tag desktop-v && git push origin desktop-v +# The tag must match the version in desktop/package.json. +# +# Or by hand: Actions tab -> "Desktop release" -> "Run workflow", then pick the branch. +# publish = false (default) build only; the installers are kept as workflow artifacts. +# publish = true also tag the commit as desktop-v +# (or reuse that tag if it was pushed for this commit) +# and attach the installers to a GitHub pre-release. # # The app carries no labs. It downloads them from the server after sign-in, so this workflow needs no secrets. # The installers are not code signed yet: Windows SmartScreen and macOS Gatekeeper will warn on first open. @@ -12,6 +19,11 @@ on: push: tags: ["desktop-v*"] workflow_dispatch: + inputs: + publish: + description: "Publish a GitHub pre-release (tag desktop-v) after building" + type: boolean + default: false permissions: contents: write @@ -43,6 +55,10 @@ jobs: node-version: 22 cache: pnpm cache-dependency-path: desktop/pnpm-lock.yaml + # The .deb and .rpm makers need these tools on the Linux runner. + - if: runner.os == 'Linux' + run: sudo apt-get update -qq && sudo apt-get install -y -qq fakeroot rpm + working-directory: . - run: pnpm install --frozen-lockfile # The desktop build imports shared code from server/src/shared, which needs the server's packages. - run: pnpm --dir ../server install --frozen-lockfile @@ -57,9 +73,26 @@ jobs: release: name: Publish release needs: make - if: startsWith(github.ref, 'refs/tags/desktop-v') + if: inputs.publish || startsWith(github.ref, 'refs/tags/desktop-v') runs-on: ubuntu-latest steps: + - uses: actions/checkout@v4 + - name: Work out the tag from desktop/package.json + id: tag + run: | + version=$(node -p "require('./desktop/package.json').version") + tag="desktop-v${version}" + if [ "${GITHUB_REF_TYPE}" = "tag" ] && [ "${GITHUB_REF_NAME}" != "${tag}" ]; then + echo "::error::Pushed tag ${GITHUB_REF_NAME} does not match desktop/package.json (${tag}). Bump the version or fix the tag." + exit 1 + fi + # A tag pushed by hand for this same commit is fine; a tag on another commit means the version was not bumped. + existing=$(git ls-remote --tags origin "refs/tags/${tag}^{}" "refs/tags/${tag}" | awk '{print $1}' | head -n1) + if [ -n "$existing" ] && [ "$existing" != "$GITHUB_SHA" ]; then + echo "::error::Tag ${tag} already exists on another commit. Bump the version in desktop/package.json first." + exit 1 + fi + echo "tag=${tag}" >> "$GITHUB_OUTPUT" - uses: actions/download-artifact@v4 with: path: dist @@ -68,7 +101,9 @@ jobs: run: find dist -type f | sort - uses: softprops/action-gh-release@v2 with: - name: Edorax desktop ${{ github.ref_name }} + tag_name: ${{ steps.tag.outputs.tag }} + target_commitish: ${{ github.sha }} + name: Edorax desktop ${{ steps.tag.outputs.tag }} # A first release stays a pre-release until it has been tried on all three systems. prerelease: true generate_release_notes: true @@ -78,3 +113,5 @@ jobs: dist/**/*.nupkg dist/**/RELEASES dist/**/*.zip + dist/**/*.deb + dist/**/*.rpm diff --git a/desktop/.gitignore b/desktop/.gitignore index 89626b921..fb5cedfff 100644 --- a/desktop/.gitignore +++ b/desktop/.gitignore @@ -149,3 +149,6 @@ playwright-report/ # Shell labs are copied from Edorax Core by `pnpm sync:labs`; Core owns them. /labs/ + +# Slim copy of the built IDE that Forge ships (scripts/stage-ide.mjs). +/.ide-bundle/ diff --git a/desktop/forge.config.mts b/desktop/forge.config.mts index 992e485f1..982c9b382 100644 --- a/desktop/forge.config.mts +++ b/desktop/forge.config.mts @@ -1,7 +1,10 @@ import { preparePty } from './scripts/prepare-pty.mjs'; +import { stageIde } from './scripts/stage-ide.mjs'; import type { ForgeConfig } from '@electron-forge/shared-types'; import { MakerSquirrel } from '@electron-forge/maker-squirrel'; import { MakerZIP } from '@electron-forge/maker-zip'; +import { MakerDeb } from '@electron-forge/maker-deb'; +import { MakerRpm } from '@electron-forge/maker-rpm'; import { VitePlugin } from '@electron-forge/plugin-vite'; import { FusesPlugin } from '@electron-forge/plugin-fuses'; import { FuseV1Options, FuseVersion } from '@electron/fuses'; @@ -11,6 +14,10 @@ const config: ForgeConfig = { generateAssets: async () => { await preparePty(); }, + // Ship only the built IDE (lib, plugins, package.json), not ide/node_modules and its sources. + prePackage: async () => { + await stageIde(); + }, }, packagerConfig: { asar: { unpack: '**/node_modules/node-pty/**' }, @@ -22,11 +29,13 @@ const config: ForgeConfig = { !file.startsWith('/node_modules/node-pty') && !file.startsWith('/node_modules/node-addon-api'), name: 'Edorax', + executableName: 'Edorax', icon: './assets/edorax', extraResource: [ './assets/edorax.png', './assets/edorax-dock.png', - './ide', + // Staged by scripts/stage-ide.mjs; still lands at resources/ide. + './.ide-bundle/ide', ], }, // TEMPORARY: node-pty's Electron rebuild needs a working Visual Studio install, which this machine @@ -35,9 +44,33 @@ const config: ForgeConfig = { rebuildConfig: { onlyModules: [] }, makers: [ new MakerSquirrel({}), - // Zip for every system. Linux uses the zip for now: the .deb and .rpm makers crash in this - // dependency layout (an old glob picks up the wrong minimatch), so they are left out until that is fixed. + // Zip for every system. new MakerZIP({}, ['darwin', 'win32', 'linux']), + // Debian and Ubuntu: `sudo apt install ./edorax__amd64.deb`. The package sets up the + // sandbox helper, the menu entry and the `edorax` command by itself. These makers take their + // settings directly (no `options` wrapper), and `electron-forge make --targets ...` ignores them. + new MakerDeb({ + name: 'edorax', + productName: 'Edorax', + genericName: 'Learning app', + bin: 'Edorax', + maintainer: 'Edorax ', + homepage: 'https://www.edorax.com', + categories: ['Education', 'Development'], + icon: './assets/edorax.png', + }), + // Fedora and RHEL: `sudo dnf install ./edorax-.x86_64.rpm`. + new MakerRpm({ + name: 'edorax', + productName: 'Edorax', + genericName: 'Learning app', + bin: 'Edorax', + homepage: 'https://www.edorax.com', + categories: ['Education', 'Development'], + icon: './assets/edorax.png', + // rpm 4.20+ (current ubuntu-latest) breaks the stock template's relative `cp -r usr/*`. + specTemplate: './packaging/rpm.spec.ejs', + }), ], plugins: [ new VitePlugin({ diff --git a/desktop/package.json b/desktop/package.json index bdc51feed..ae12062a5 100644 --- a/desktop/package.json +++ b/desktop/package.json @@ -1,7 +1,7 @@ { "name": "desktop", "productName": "Edorax", - "version": "0.1.0", + "version": "0.1.2", "private": true, "description": "Edorax desktop learning workspace", "keywords": [], @@ -21,7 +21,7 @@ "sync:labs": "node scripts/sync-labs.mjs", "lint:fix": "oxlint --fix && oxfmt --write", "typecheck": "tsc --noEmit", - "test": "tsx --test tests/api.test.ts tests/labs.test.ts tests/local-runtime.test.ts tests/ide.test.ts tests/shell-labs.test.ts tests/shell-labs-catalog.test.ts tests/guided-labs.test.ts tests/docker-setup.test.ts tests/app-version.test.ts tests/update-service.test.ts", + "test": "tsx --test tests/api.test.ts tests/labs.test.ts tests/local-runtime.test.ts tests/ide.test.ts tests/shell-labs.test.ts tests/shell-labs-catalog.test.ts tests/guided-labs.test.ts tests/docker-setup.test.ts tests/app-version.test.ts tests/update-service.test.ts tests/lab-progress.test.ts", "test:ui": "playwright test", "dev:ui": "vite --config vite.renderer.config.mts --host 127.0.0.1 --port 5179 --strictPort", "test:labs": "tsx --test tests/labs.integration.test.ts tests/shell-labs.integration.test.ts", @@ -78,6 +78,7 @@ }, "overrides": { "dompurify": "3.4.17", - "minimatch": "^11.0.5" + "minimatch": "^11.0.5", + "glob@7>minimatch": "^3.1.2" } } diff --git a/desktop/packaging/rpm.spec.ejs b/desktop/packaging/rpm.spec.ejs new file mode 100644 index 000000000..9e3203c6b --- /dev/null +++ b/desktop/packaging/rpm.spec.ejs @@ -0,0 +1,64 @@ +<% /* Copy of electron-installer-redhat 4.0.0 resources/spec.ejs. Only change: %install copies from %{_topdir}/BUILD/usr + instead of a relative usr/, because rpm 4.20+ runs %install from BUILD/--build. */ %> +%define _binary_payload w<%= compressionLevel %>.xzdio + +%if "%{_host_cpu}" != "%{_target_cpu}" +%global __strip /bin/true +%endif + +Name: <%= name %> +Version: <%= version %> +Release: <%= revision %>%{?dist} +<% if (description) { print(`Summary: ${description}\n`) } +%> +<% if (license) { print(`License: ${license}\n`) } +if (homepage) { print(`URL: ${homepage}\n`) } +if (license || homepage) { print('\n') } + +%>Requires: <%= requires.join(', ') %> +AutoReqProv: no + +<% if (productDescription) { +%>%description +<% print(productDescription) +print('\n\n\n') } + + +%>%install +mkdir -p %{buildroot}/usr/ +cp <%= process.platform === 'darwin' ? '-R' : '-r' %> %{_topdir}/BUILD/usr/* %{buildroot}/usr/ + + +%files +/usr/bin/<%= name %> +/usr/lib/<%= name %>/ +/usr/share/applications/<%= name %>.desktop +/usr/share/doc/<%= name %>/ +<% if (_.isObject(icon)) { + _.forEach(icon, function (path, resolution) { + %>/usr/share/icons/hicolor/<%= resolution %>/apps/<%= name %><%= resolution === 'symbolic' ? '-symbolic' : '' %>.<%= ['scalable', 'symbolic'].includes(resolution) ? 'svg' : 'png' %> +<% }) } else { + %>/usr/share/pixmaps/<%= name %>.png +<% } %> + +<% if (pre) { + %>%pre +<% print(pre) +if (preun || post || postun) print('\n\n\n') } + + +%><% if (preun) { + %>%preun +<% print(preun) +if (post || postun) print('\n\n\n') } + + +%><% if (post) { + %>%post +<% print(post) +if (postun) print('\n\n\n') } + + +%><% if (postun) { + %>%postun +<% print(postun) } %> diff --git a/desktop/pnpm-lock.yaml b/desktop/pnpm-lock.yaml index 73bf1de74..f6100a2cc 100644 --- a/desktop/pnpm-lock.yaml +++ b/desktop/pnpm-lock.yaml @@ -7,6 +7,7 @@ settings: overrides: dompurify: 3.4.17 minimatch: ^11.0.5 + glob@7>minimatch: ^3.1.2 importers: @@ -1205,6 +1206,9 @@ packages: bail@2.0.2: resolution: {integrity: sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw==} + balanced-match@1.0.2: + resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==} + balanced-match@4.0.4: resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==} engines: {node: 18 || 20 || >=22} @@ -1218,6 +1222,9 @@ packages: bl@4.1.0: resolution: {integrity: sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==} + brace-expansion@1.1.22: + resolution: {integrity: sha512-CKLDTuSsN0+r1ThM0WkzzBI7dnPI6xEGfa/JnVYIK9JNBA1N1NyPwXVHor//NKD/y3sDxp764sZdLhFK7pH8XQ==} + brace-expansion@5.0.12: resolution: {integrity: sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==} engines: {node: 20 || >=22} @@ -1319,6 +1326,9 @@ packages: resolution: {integrity: sha512-KRs7WVDKg86PWiuAqhDrAQnTXZKraVcCc6vFdL14qrZ/DcWwuRo7VoiYXalXO7S5GKpqYiVEwCbgFDfxNHKJBQ==} engines: {node: ^12.20.0 || >=14} + concat-map@0.0.1: + resolution: {integrity: sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==} + convert-to-spaces@2.0.1: resolution: {integrity: sha512-rcQ1bsQO9799wq24uE5AM2tAILy4gXGIK/njFWcVQkGNZ96edlpY+A7bjwvzjYvLDyzmG1MmMLZhpcsb+klNMQ==} engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} @@ -2062,6 +2072,9 @@ packages: resolution: {integrity: sha512-snPlVppFcYWfLLFQGhDxUyBcHNtMlWmn3jtj7pEaO+DP8pqL0IvAzXhMYmn1z9ASNtgmwLBdFxSf4tMUB0OTKA==} engines: {node: 20 || >=22} + minimatch@3.1.5: + resolution: {integrity: sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==} + minimist@1.2.8: resolution: {integrity: sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==} @@ -3623,6 +3636,9 @@ snapshots: bail@2.0.2: {} + balanced-match@1.0.2: + optional: true + balanced-match@4.0.4: {} base64-js@1.5.1: {} @@ -3637,6 +3653,12 @@ snapshots: inherits: 2.0.4 readable-stream: 3.6.2 + brace-expansion@1.1.22: + dependencies: + balanced-match: 1.0.2 + concat-map: 0.0.1 + optional: true + brace-expansion@5.0.12: dependencies: balanced-match: 4.0.4 @@ -3722,6 +3744,9 @@ snapshots: commander@9.5.0: {} + concat-map@0.0.1: + optional: true + convert-to-spaces@2.0.1: {} cpu-features@0.0.10: @@ -4054,7 +4079,7 @@ snapshots: fs.realpath: 1.0.0 inflight: 1.0.6 inherits: 2.0.4 - minimatch: 11.0.5 + minimatch: 3.1.5 once: 1.4.0 path-is-absolute: 1.0.1 optional: true @@ -4761,6 +4786,11 @@ snapshots: '@isaacs/nonrecursive-glob-match': 1.1.0 brace-expansion: 5.0.12 + minimatch@3.1.5: + dependencies: + brace-expansion: 1.1.22 + optional: true + minimist@1.2.8: optional: true diff --git a/desktop/pnpm-workspace.yaml b/desktop/pnpm-workspace.yaml index 447fce2dc..af77e1fc7 100644 --- a/desktop/pnpm-workspace.yaml +++ b/desktop/pnpm-workspace.yaml @@ -10,3 +10,4 @@ allowBuilds: overrides: dompurify: 3.4.17 minimatch: ^11.0.5 + "glob@7>minimatch": ^3.1.2 diff --git a/desktop/scripts/stage-ide.mjs b/desktop/scripts/stage-ide.mjs new file mode 100644 index 000000000..378378279 --- /dev/null +++ b/desktop/scripts/stage-ide.mjs @@ -0,0 +1,39 @@ +// Copies only what the Theia IDE needs at runtime into .ide-bundle/ide, which Forge ships as a +// resource. The production build bundles the backend (lib/backend/main.js, with its native +// binaries in lib/backend/native) and the frontend (lib/frontend), so ide/node_modules, src-gen, +// the build scripts and the lockfiles are not needed in the installed app. +import { cp, rm, stat } from 'node:fs/promises'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const desktop = fileURLToPath(new URL('..', import.meta.url)); +const source = path.join(desktop, 'ide'); +const target = path.join(desktop, '.ide-bundle', 'ide'); + +const keep = ['lib', 'plugins', 'package.json']; +// Source maps are only useful when debugging the IDE itself. +const skip = (file) => file.endsWith('.map'); + +export async function stageIde() { + await stat(path.join(source, 'lib', 'backend', 'main.js')).catch(() => { + throw new Error('The IDE is not built. Run `pnpm ide:setup` (or `pnpm ide:build`) first.'); + }); + await rm(target, { recursive: true, force: true }); + for (const entry of keep) { + const from = path.join(source, entry); + // plugins/ only exists after `pnpm --dir ide run download:plugins`; the app creates it if missing. + if (!(await stat(from).catch(() => null))) { + console.warn(`stage-ide: skipping missing ide/${entry}`); + continue; + } + await cp(from, path.join(target, entry), { + recursive: true, + filter: (file) => !skip(file), + }); + } +} + +if (process.argv[1] && fileURLToPath(import.meta.url) === path.resolve(process.argv[1])) { + await stageIde(); + console.log(`Staged IDE runtime at ${target}`); +} diff --git a/desktop/src/domain/leaderboard.ts b/desktop/src/domain/leaderboard.ts index d5b5caf90..290dfda18 100644 --- a/desktop/src/domain/leaderboard.ts +++ b/desktop/src/domain/leaderboard.ts @@ -48,13 +48,46 @@ export function isLeaderboardSelection(value: unknown): value is LeaderboardSele return categoryOk && scopeOk && courseOk; } -export const LEAGUE_TIER_ORDER: LeagueTier[] = ['BRONZE', 'SILVER', 'GOLD', 'PLATINUM', 'DIAMOND']; +export const LEAGUE_TIER_ORDER: LeagueTier[] = ['BRONZE', 'SILVER', 'GOLD', 'PLATINUM', 'COBALT', 'JADE', 'QUARTZ', 'AURORA', 'ZENITH', 'DIAMOND']; + +export const LEAGUE_WEEKLY_GOALS: Record = { + BRONZE: 100, + SILVER: 200, + GOLD: 400, + PLATINUM: 700, + COBALT: 1_000, + JADE: 1_400, + QUARTZ: 1_900, + AURORA: 2_500, + ZENITH: 3_200, + DIAMOND: 4_000, +}; + +export const LEAGUE_TIER_MARKS: Record = { + BRONZE: 'Br', + SILVER: 'Si', + GOLD: 'Go', + PLATINUM: 'Pt', + COBALT: 'Co', + JADE: 'Ja', + QUARTZ: 'Qz', + AURORA: 'Au', + ZENITH: 'Ze', + DIAMOND: 'Di', +}; + +export const LEAGUE_PROMOTION_PERCENT = 0.1; export const LEAGUE_TIER_LABELS: Record = { BRONZE: 'Bronze', SILVER: 'Silver', GOLD: 'Gold', PLATINUM: 'Platinum', + COBALT: 'Cobalt', + JADE: 'Jade', + QUARTZ: 'Quartz', + AURORA: 'Aurora', + ZENITH: 'Zenith', DIAMOND: 'Diamond', }; diff --git a/desktop/src/domain/shell-labs.ts b/desktop/src/domain/shell-labs.ts index 029ed689d..cb9e9c395 100644 --- a/desktop/src/domain/shell-labs.ts +++ b/desktop/src/domain/shell-labs.ts @@ -314,6 +314,10 @@ export interface ShellLabsAPI { list(): Promise; /** Asks the server for newer labs and saves them on this computer. Never rejects: a failure comes back as a plain message. */ refresh(): Promise; + /** Passed steps per lab, kept on the learner's account. Null when signed out or offline. Never rejects. */ + progress(): Promise | null>; + /** Saves the passed steps of one lab on the account. False when it could not. Never rejects. */ + saveProgress(slug: string, steps: string[]): Promise; view(slug: string): Promise; status(slug: string): Promise; start(slug: string): Promise; diff --git a/desktop/src/ide/runtime.ts b/desktop/src/ide/runtime.ts index 7167a1499..b11b6722a 100644 --- a/desktop/src/ide/runtime.ts +++ b/desktop/src/ide/runtime.ts @@ -40,7 +40,14 @@ export class TheiaRuntime { : process.platform === 'win32' ? 'node.exe' : 'node'; - const main = path.join(this.directory, 'src-gen/backend/main.js'); + // The production build bundles the backend into lib/backend/main.js, which runs without + // node_modules. src-gen/backend/main.js is the unbundled entry and needs ide/node_modules. + const bundledMain = path.join(this.directory, 'lib/backend/main.js'); + const sourceMain = path.join(this.directory, 'src-gen/backend/main.js'); + const main = await access(bundledMain).then( + () => bundledMain, + () => sourceMain, + ); try { await access(main); } catch { diff --git a/desktop/src/main.ts b/desktop/src/main.ts index 33de53072..e99bd3422 100644 --- a/desktop/src/main.ts +++ b/desktop/src/main.ts @@ -764,6 +764,21 @@ else { requireRenderer(event); return refreshLabsFromServer(); }); + // Progress lives on the learner's account. Both calls swallow failures: progress is also kept on + // this computer, so the labs work offline and the next sync catches the account up. + ipcMain.handle('shell-labs:progress', async (event) => { + requireRenderer(event); + if (!previewClient.sessionSnapshot()) return null; + const result = await previewClient.request('/api/v1/shell-labs/progress', 'GET'); + const data = result.ok ? (result.data as { progress?: unknown } | null)?.progress : null; + return data && typeof data === 'object' && !Array.isArray(data) ? data : null; + }); + ipcMain.handle('shell-labs:save-progress', async (event, slug, steps) => { + requireRenderer(event); + if (typeof slug !== 'string' || !Array.isArray(steps) || !previewClient.sessionSnapshot()) return false; + const result = await previewClient.request(`/api/v1/shell-labs/progress/${encodeURIComponent(slug)}`, 'PUT', { steps }); + return result.ok; + }); ipcMain.handle('shell-labs:view', (event, slug) => { requireRenderer(event); const lab = getShellLab(slug); diff --git a/desktop/src/preload.ts b/desktop/src/preload.ts index 91c74091c..f66770130 100644 --- a/desktop/src/preload.ts +++ b/desktop/src/preload.ts @@ -68,6 +68,8 @@ const api: DesktopAPI = { }, list: () => ipcRenderer.invoke('shell-labs:list'), refresh: () => ipcRenderer.invoke('shell-labs:refresh'), + progress: () => ipcRenderer.invoke('shell-labs:progress'), + saveProgress: (slug, steps) => ipcRenderer.invoke('shell-labs:save-progress', slug, steps), view: (slug) => ipcRenderer.invoke('shell-labs:view', slug), status: (slug) => ipcRenderer.invoke('shell-labs:status', slug), start: (slug) => ipcRenderer.invoke('shell-labs:start', slug), diff --git a/desktop/src/ui/leaderboard/LeaderboardPage.tsx b/desktop/src/ui/leaderboard/LeaderboardPage.tsx index bd460efc0..43de5838d 100644 --- a/desktop/src/ui/leaderboard/LeaderboardPage.tsx +++ b/desktop/src/ui/leaderboard/LeaderboardPage.tsx @@ -93,7 +93,8 @@ export function LeaderboardPage({ initialSelection }: { initialSelection?: Leade if (!view || view.status !== 'ready') return; const key = `${view.category}|${view.scope}|${view.courseId ?? 'global'}`; const onPodium = view.you.rank >= 1 && view.you.rank <= 3 && view.you.score > 0; - const promoted = view.league?.lastWeek?.outcome === 'PROMOTED'; + const outcome = view.league?.lastWeek?.outcome; + const promoted = outcome === 'PROMOTED' || outcome === 'PROMOTED_TARGET' || outcome === 'PROMOTED_BOTH'; if ((!onPodium && !promoted) || celebrated.current === key) return; celebrated.current = key; const timer = window.setTimeout(() => { diff --git a/desktop/src/ui/leaderboard/LeaderboardParts.tsx b/desktop/src/ui/leaderboard/LeaderboardParts.tsx index 4d73b3c36..5ae8926fc 100644 --- a/desktop/src/ui/leaderboard/LeaderboardParts.tsx +++ b/desktop/src/ui/leaderboard/LeaderboardParts.tsx @@ -1,9 +1,12 @@ import type { ReactNode } from 'react'; import { LEAGUE_TIER_LABELS, + LEAGUE_TIER_ORDER, + LEAGUE_WEEKLY_GOALS, formatNumber, formatScore, initials, + LEAGUE_PROMOTION_PERCENT, nextLeagueTier, prevLeagueTier, resetLabel, @@ -28,6 +31,39 @@ export function Pill({ tone, children }: { tone: keyof typeof PILL; children: Re return {children}; } +const BADGE_COLORS: Record = { + BRONZE: '#c87945', + SILVER: '#b7c4d2', + GOLD: '#f0b936', + PLATINUM: '#91a8b8', + COBALT: '#3276c8', + JADE: '#35a77d', + QUARTZ: '#a78bda', + AURORA: '#5fb7bd', + ZENITH: '#665ed0', + DIAMOND: '#55aee8', +}; + +export function LeagueBadge({ tier }: { tier: LeagueTier }) { + const colors = BADGE_COLORS[tier]; + return ( + + {LEAGUE_TIER_LABELS[tier]} League + + {tier === 'BRONZE' ? : null} + {tier === 'SILVER' ? : null} + {tier === 'GOLD' ? : null} + {tier === 'PLATINUM' ? : null} + {tier === 'COBALT' ? : null} + {tier === 'JADE' ? : null} + {tier === 'QUARTZ' ? : null} + {tier === 'AURORA' ? : null} + {tier === 'ZENITH' ? : null} + {tier === 'DIAMOND' ? : null} + + ); +} + export function Rank({ rank, highlight }: { rank: number; highlight?: boolean }) { const tone = MEDAL[rank] ?? (highlight ? 'bg-primary text-primary-foreground' : 'bg-muted text-muted-foreground'); return ( @@ -121,14 +157,19 @@ function LeagueOutcome({ league }: { league: LeagueInfo }) { const last = league.lastWeek; if (!last) return null; const box = 'rounded-xl border px-4 py-2.5 text-sm font-medium'; - if (last.outcome === 'PROMOTED') { + if (last.outcome === 'PROMOTED' || last.outcome === 'PROMOTED_TARGET' || last.outcome === 'PROMOTED_BOTH') { const to = nextLeagueTier(last.fromTier); + const path = last.outcome === 'PROMOTED_TARGET' ? 'by reaching your weekly goal' : last.outcome === 'PROMOTED_BOTH' ? 'by rank and your weekly goal' : 'by rank'; return (

- Promoted to {to ? LEAGUE_TIER_LABELS[to] : 'a higher league'} last week. + Promoted to {to ? LEAGUE_TIER_LABELS[to] : 'a higher league'} last week {path}.

); } + if (last.outcome === 'RECOVERY_HELD' || last.outcome === 'SHIELD_HELD') { + const protection = last.outcome === 'RECOVERY_HELD' ? 'recovery quest' : 'League Shield'; + return

Your {protection} protected your league place last week.

; + } if (last.outcome === 'DEMOTED') { const to = prevLeagueTier(last.fromTier); return ( @@ -165,6 +206,51 @@ export function LeagueCard({ const isDemoting = demoteCount > 0 && league.rank >= league.demotionZone && Boolean(prev); const best = bestScore ?? 0; const label = 'This week compared with your best week'; + const currentIndex = LEAGUE_TIER_ORDER.indexOf(league.tier); + + const journey = ( +
+
+
+

League journey

+

Your weekly path

+
+ {currentIndex + 1} of {LEAGUE_TIER_ORDER.length} +
+
    + {LEAGUE_TIER_ORDER.map((tier, index) => { + const current = tier === league.tier; + const nextTier = tier === next; + const past = currentIndex > index; + return ( +
  1. +
    + 0 && past ? 'bg-primary' : 'bg-border'}`} /> + + + + +
    + {LEAGUE_TIER_LABELS[tier]} + {current ? 'You are here' : nextTier ? 'Next' : past ? 'Complete' : 'Upcoming'} +
  2. + ); + })} +
+
+
+

Current league

+

{LEAGUE_TIER_LABELS[league.tier]} · {formatNumber(league.goal)} XP goal

+

Reach the goal or finish in the top {Math.round(LEAGUE_PROMOTION_PERCENT * 100)}%.

+
+
+

Next league

+

{next ? `${LEAGUE_TIER_LABELS[next]} · ${formatNumber(LEAGUE_WEEKLY_GOALS[next])} XP goal` : 'Diamond · final league'}

+

{next ? `You are one tier away from ${LEAGUE_TIER_LABELS[next]}.` : 'You have reached the top of the league journey.'}

+
+
+
+ ); return (
@@ -191,6 +277,8 @@ export function LeagueCard({
+ {journey} +
@@ -199,8 +287,10 @@ export function LeagueCard({
{next && promoteCount > 0 ? (

- Top {promoteCount} promote to {LEAGUE_TIER_LABELS[next]} + Top {Math.round(LEAGUE_PROMOTION_PERCENT * 100)}% ({promoteCount} {promoteCount === 1 ? 'spot' : 'spots'}) or the weekly goal promotes to {LEAGUE_TIER_LABELS[next]}

+ ) : next && league.goal > 0 ? ( +

Reach the weekly goal to promote

) : prev && demoteCount > 0 ? (

Bottom {demoteCount} demote to {LEAGUE_TIER_LABELS[prev]} @@ -212,6 +302,31 @@ export function LeagueCard({ )}

+ {league.goal > 0 ? ( +
+
+ + {league.goalMet ? 'Weekly goal met' : 'Achievement promotion'} + + {formatNumber(score)} / {formatNumber(league.goal)} XP +
+ +

Reach your goal or finish in the top {Math.round(LEAGUE_PROMOTION_PERCENT * 100)}%. Both paths unlock the next league.

+
+ ) : null} + + {league.recovery ? ( +
+
+ Recovery quest + + {league.recovery.completed ? 'Complete' : 'In progress'} + +
+

Complete {league.recovery.chapterTarget} chapter and earn {formatNumber(league.recovery.xpTarget)} XP to protect against one demotion.

+
+ ) : null} + {best > 0 ? (
diff --git a/desktop/src/ui/shell-labs/ShellLabs.tsx b/desktop/src/ui/shell-labs/ShellLabs.tsx index fcb2e2ef5..8e7c669b3 100644 --- a/desktop/src/ui/shell-labs/ShellLabs.tsx +++ b/desktop/src/ui/shell-labs/ShellLabs.tsx @@ -1,8 +1,8 @@ import { useEffect, useState } from 'react'; -import { ArrowLeft, Clock, Terminal } from 'lucide-react'; +import { ArrowLeft, CheckCircle2, Clock, Terminal } from 'lucide-react'; import { SHELL_TOPICS, type ShellLabSummary, type ShellTopic } from '../../domain/shell-labs'; import { ShellLabPage } from './ShellLabPage'; -import { errorText, passedSteps } from './progress'; +import { errorText, passedSteps, syncPassedSteps } from './progress'; /** * Labs that need a real kernel of their own (systemd as PID 1, mount and loop devices). They arrive @@ -31,6 +31,12 @@ export function ShellLabs({ onBack, topic: only }: { onBack: () => void; topic?: .catch((reason: unknown) => setError(errorText(reason))); }, []); + // Progress also lives on the account: bring in steps done on another computer or before a reinstall. + const [, setSynced] = useState(0); + useEffect(() => { + void syncPassedSteps().then((changed) => changed && setSynced((n) => n + 1)); + }, []); + if (open) return setOpen(null)} />; return ( @@ -90,9 +96,13 @@ export function ShellLabs({ onBack, topic: only }: { onBack: () => void; topic?: {lab.minutes} min - - {done ? `${Math.min(done, lab.steps)} of ${lab.steps} steps done` : `${lab.steps} steps`} - + {done >= lab.steps ? ( + + Completed + + ) : ( + {done ? `${done} of ${lab.steps} steps done` : `${lab.steps} steps`} + )} diff --git a/desktop/src/ui/shell-labs/progress.ts b/desktop/src/ui/shell-labs/progress.ts index 4a8481ed0..630c86044 100644 --- a/desktop/src/ui/shell-labs/progress.ts +++ b/desktop/src/ui/shell-labs/progress.ts @@ -17,7 +17,7 @@ export function passedSteps(slug: string): string[] { return Array.isArray(steps) ? steps.filter((step) => typeof step === 'string') : []; } -export function savePassedSteps(slug: string, steps: string[]) { +function writeLocal(slug: string, steps: string[]) { try { const all = read(); if (steps.length) all[slug] = steps; @@ -28,6 +28,39 @@ export function savePassedSteps(slug: string, steps: string[]) { } } +/** Saves on this computer and, in the background, on the learner's account. */ +export function savePassedSteps(slug: string, steps: string[]) { + writeLocal(slug, steps); + void window.buildment?.shellLabs?.saveProgress?.(slug, steps).catch(() => {}); +} + +/** + * Joins this computer's progress with the account's, so a reinstall or a second computer still shows + * what was done. A step done on either side stays done. Steps found only on this computer are sent + * to the account. Returns true when something changed here. Never rejects. + */ +export async function syncPassedSteps(): Promise { + try { + const remote = await window.buildment?.shellLabs?.progress?.(); + if (!remote) return false; + let changed = false; + const local = read(); + for (const slug of new Set([...Object.keys(local), ...Object.keys(remote)])) { + const mine = Array.isArray(local[slug]) ? local[slug] : []; + const theirs = Array.isArray(remote[slug]) ? remote[slug].filter((step) => typeof step === 'string') : []; + const joined = [...new Set([...theirs, ...mine])]; + if (joined.length > mine.length) { + writeLocal(slug, joined); + changed = true; + } + if (joined.length > theirs.length) void window.buildment.shellLabs.saveProgress(slug, joined).catch(() => {}); + } + return changed; + } catch { + return false; + } +} + /** IPC errors arrive as "Error invoking remote method 'x': Error: message". Keep the message. */ export function errorText(error: unknown) { const text = error instanceof Error ? error.message : String(error); diff --git a/desktop/tests/lab-progress.test.ts b/desktop/tests/lab-progress.test.ts new file mode 100644 index 000000000..4f52e09bc --- /dev/null +++ b/desktop/tests/lab-progress.test.ts @@ -0,0 +1,73 @@ +import assert from 'node:assert/strict'; +import { beforeEach, describe, it } from 'node:test'; +import { passedSteps, savePassedSteps, syncPassedSteps } from '../src/ui/shell-labs/progress'; + +// The progress helpers run in the page; give them a tiny localStorage and a fake app bridge. +const store = new Map(); +const g = globalThis as Record; +g.localStorage = { + getItem: (key: string) => store.get(key) ?? null, + setItem: (key: string, value: string) => void store.set(key, value), +}; + +let remote: Record | null = null; +let sent: { slug: string; steps: string[] }[] = []; +g.window = { + buildment: { + shellLabs: { + progress: async () => remote, + saveProgress: async (slug: string, steps: string[]) => { + sent.push({ slug, steps }); + return true; + }, + }, + }, +}; + +beforeEach(() => { + store.clear(); + remote = {}; + sent = []; +}); + +describe('lab progress sync', () => { + it('shows steps that exist only on the account', async () => { + remote = { 'linux-102': ['a', 'b'], 'docker-first-container': ['x'] }; + assert.equal(await syncPassedSteps(), true); + assert.deepEqual(passedSteps('linux-102'), ['a', 'b']); + assert.deepEqual(passedSteps('docker-first-container'), ['x']); + assert.deepEqual(sent, []); + }); + + it('sends steps that exist only on this computer to the account', async () => { + store.set('edorax:shell-labs:v1', JSON.stringify({ 'linux-101': ['a', 'b'] })); + assert.equal(await syncPassedSteps(), false); + assert.deepEqual(sent, [{ slug: 'linux-101', steps: ['a', 'b'] }]); + }); + + it('keeps a step done on either side', async () => { + store.set('edorax:shell-labs:v1', JSON.stringify({ 'linux-101': ['a'] })); + remote = { 'linux-101': ['b'] }; + assert.equal(await syncPassedSteps(), true); + assert.deepEqual(passedSteps('linux-101').sort(), ['a', 'b']); + assert.deepEqual(sent[0].steps.sort(), ['a', 'b']); + }); + + it('changes nothing when signed out or offline', async () => { + store.set('edorax:shell-labs:v1', JSON.stringify({ 'linux-101': ['a'] })); + remote = null; + assert.equal(await syncPassedSteps(), false); + assert.deepEqual(passedSteps('linux-101'), ['a']); + assert.deepEqual(sent, []); + }); + + it('saving a lab also saves it on the account, and a reset sends an empty list', () => { + savePassedSteps('linux-101', ['a']); + savePassedSteps('linux-101', []); + assert.deepEqual(sent, [ + { slug: 'linux-101', steps: ['a'] }, + { slug: 'linux-101', steps: [] }, + ]); + assert.deepEqual(passedSteps('linux-101'), []); + }); +}); diff --git a/docs/12-course-variants-and-publishing.mdx b/docs/12-course-variants-and-publishing.mdx index e343cff97..8705a8a65 100644 --- a/docs/12-course-variants-and-publishing.mdx +++ b/docs/12-course-variants-and-publishing.mdx @@ -89,6 +89,21 @@ module sequence, including every variant-only module. `omitLessonKeys` removes inherited lessons from retained shared modules. New graded work gets separate progress. Keep keys stable and review the effect on every variant before approval. +A course without lesson keys removes a lesson by its public address, the last part of +its reader link: + +```yaml +remove: + lessons: + - slug: 39-5-the-old-summary + redirectTo: 39-5-part-1-the-bucket +``` + +`redirectTo` is optional. With it, an old link to the removed lesson opens the named +lesson instead of a "not found" page. The target must be in the course after the publish. +Leave the entry in `course.yaml`: a lesson that an earlier release already removed is +skipped, and the redirect is kept. Leaving a lesson file out of the package never removes it. + The older `multi-vendor-marketplace` source folder now has a manifest with stable keys for all 385 lessons. Its `repositoryTargetSlug` points to the existing `freshmarket-multi-vendor-marketplace-v3` database course. The publisher requires diff --git a/docs/14-gamification.mdx b/docs/14-gamification.mdx index 6899dac39..14f6ae776 100644 --- a/docs/14-gamification.mdx +++ b/docs/14-gamification.mdx @@ -144,18 +144,27 @@ The `/leaderboard` page serves several boards from one read, | Streak | `streak` | `global` | current active-day streak, counted in each learner's own timezone | - **Leagues.** The global weekly board is a league. Every opted-in learner sits in a tier - (`User.leagueTier`, Bronze → Diamond; new learners start at Bronze). At the Monday 00:00 UTC - reset (`POST /api/v1/jobs/leaderboard-reset`, cron-secret protected), the closed week's global XP - ranks each tier: the top 10% promote, the bottom 20% demote, everyone else holds. Diamond has - nothing to promote to, Bronze nothing to demote from, and leagues under 10 learners have no - demotion zone. The reset is idempotent (advisory lock, one `LeaguePlacement` row per learner per - week) and excludes learners who already opted out or hid game elements. + (`User.leagueTier`, Bronze → Diamond through Cobalt, Jade, Quartz, Aurora and Zenith; new learners + start at Bronze). At the Monday 00:00 UTC + reset (`POST /api/v1/jobs/leaderboard-reset`, cron-secret protected), a learner can promote in + either of two ways: finish in the top 10% of a tier with at least five eligible learners, or reach + the tier's published weekly XP goal. The fixed goals are Bronze 100, Silver 200, Gold 400, + Platinum 700, Cobalt 1,000, Jade 1,400, Quartz 1,900, Aurora 2,500, Zenith 3,200 and Diamond + 4,000 XP. Both paths unlock one tier only. Diamond has nothing to + promote to, Bronze nothing to demote from, and leagues under 10 learners have no demotion zone. + The reset is idempotent (advisory lock, one `LeaguePlacement` row per learner per week) and + excludes learners who already opted out or hid game elements. +- **Recovery.** A learner in the demotion zone can complete the recovery quest by completing one + chapter and earning 50 XP in the closed week. Recovery protection holds the learner's tier before + a League Shield is consumed. Neither protection grants promotion, and only one protection applies + to a settlement. - **Recognition boards.** All-time, speed and streak carry no promotion stakes — they exist so different strengths shine. Podium, neighbourhood and personal-best bars work as on the course board. -- **What a learner sees.** Per board: a league card (tier, rank, promotion and demotion zones, last - week's outcome), an animated top-three podium, the learners nearest their rank, and last week's - winners. Reaching a podium or getting promoted fires confetti and the celebration sound. +- **What a learner sees.** Per board: a league card (tier, rank, top-10-percent zone, published goal, + recovery progress, last week's outcome), an animated top-three podium, the learners nearest their + rank, and last week's winners. Reaching a podium or getting promoted fires confetti and the + celebration sound. - The per-course board keeps its own endpoint, contract and settlement logic; the hub delegates to it for `weekly_xp` + `course`, so the dashboard card and the old contract are untouched. diff --git a/docs/gamification-todo.md b/docs/gamification-todo.md index d5e267354..d0a57d879 100644 --- a/docs/gamification-todo.md +++ b/docs/gamification-todo.md @@ -4,19 +4,18 @@ Source: `Buildment_Gamification_Design_Concepts.pdf` concept book + researched m (Duolingo leagues/personal-records, PUBG seasonal tiers, Pluralsight mastery-gating) + Devmaxx competitor signal. -## Status vs upstream (2026-10-31) +## Status vs upstream (2026-11-15) - **Phase 1 (league) largely landed upstream** in PR #161 `feat(leaderboard): multi-category hub with - weekly leagues`: cross-course weekly league, Bronze→Diamond tiers, top 10% promote / bottom 20% - demote at Monday 00:00 UTC, per-course board kept, hub UI + categories, privacy, "beat your best". + weekly leagues`: cross-course weekly league, ten tiers from Bronze to Diamond, top-10-percent or fixed-goal promotion / + bottom 20% demotion at Monday 00:00 UTC, per-course board kept, hub UI + categories, privacy, + "beat your best". Files: `services/gamification/league.ts`, `leaderboard-categories.ts`, `shared/gamification/leagues.ts`, migration `leaderboard_leagues`. -- **Two divergences from this plan's choices were shipped:** +- **One divergence from this plan's choices remains:** - Grouping is **tier-based (percentile)**, not the planned ~30-person random same-pace cohorts (they explicitly chose tiers over cohorts). - - **Achievement promotion was not built** — only competitive percentile (top 10% / bottom 20%); - no escalating XP-target promotion path. -- **Still open:** Phase 2 career ladder, Phase 3 Build Credits/marketplace, Phase 4 daily/monthly/ - recovery/mascot-loading + a dedicated **My Records** surface, Phase 5 share/experiments. +- **Still open:** Phase 4 daily/monthly/recap/notifications and the loading companion, plus Phase 5 + experiments. ## Core decisions (locked) - **Two layers**: a short-horizon **league** + a permanent **career ladder**, plus a **rewards** loop. @@ -50,22 +49,23 @@ competitor signal. - **My Records**: read-only, in scope. ## Phase 0 — Foundation -- [ ] Confirm the two-layer model as source of truth (decisions above are the locked scope) -- [ ] Feature-flag inventory: `GAMIFICATION_LEAGUE_TIERS`, `GAMIFICATION_CAREER_LEVELS`, - `GAMIFICATION_CREDITS`, `GAMIFICATION_RECOVERY` (each `null` when off) +- [x] Confirm the two-layer model as source of truth (decisions above are the locked scope) +- [x] Feature-flag inventory: `GAMIFICATION_LEAGUE_TIERS`, `GAMIFICATION_CAREER_LEVELS`, + `GAMIFICATION_CREDITS`, `GAMIFICATION_RECOVERY` (each `false` when off) ## Phase 1 — League (cross-course, Duolingo-style) — ✅ MAJORITY LANDED UPSTREAM (PR #161) - [x] **Landed:** cross-course weekly league (global XP across all courses), weekly reset Monday 00:00 - UTC, tiers (Bronze→Diamond), top 10% / bottom 20% promotion & demotion, per-course board + UTC, ten tiers from Bronze through Diamond, top-10-percent or fixed-goal / bottom 20% promotion & demotion, per-course board retained, hub UI + categories (`weekly_xp/global`, `all_time_xp/global`, `speed/global`, `streak/global`), privacy + "beat your best" bar. - [ ] **Gap vs plan:** grouping is **tier-based**, not the planned ~30-person random same-pace cohorts (decide whether to adopt the shipped tiers or add real cohorts). -- [ ] **Gap vs plan:** **achievement promotion** (published escalating weekly-XP target) not built — - only competitive percentile. +- [x] **Achievement promotion:** fixed weekly XP goals are an alternate path to promotion. Current + goals are 100, 200, 400, 700, 1,000, 1,400, 1,900, 2,500, 3,200 and 4,000 XP in tier order. - [ ] Decouple from career: league demotion touches the league tier only; a permanent career ladder (Phase 2) does not exist yet, so nothing to decouple from today. -- [ ] Dashboard/league UI + tests: hub UI and `leaderboard-hub.test.ts` landed; confirm the rest. +- [x] Dashboard/league UI + tests: hub UI now shows the top-10-percent zone, target progress, recovery progress and + settlement reasons; shared, pure and API coverage added. ## Phase 2 — Career ladder (permanent) - [ ] **Define "mastery" in code** (verified signals advancing each tier) — do first; avoids inflation @@ -84,10 +84,10 @@ competitor signal. ## Phase 4 — Supporting loops & polish - [ ] Daily quests → chests → XP-boost (mini dose loop) - [ ] Monthly badge (quest-points + themed badge) -- [ ] **Recovery**: League Shield / recovery quest — **included** (ships with the league work) -- [ ] **My Records (personal bests)**: longest streak + best weekly XP/chapters are computed in the hub - (PR #161); still missing a dedicated profile "My Records" surface + most-XP-in-a-day / best league - finish lines; "New record!" celebration; read-only recognition +- [x] **Recovery:** League Shield plus a recovery quest requiring one completed chapter and 50 XP; + recovery protection is used before a shield at settlement. +- [x] **My Records (personal bests)**: longest streak, best weekly/day XP, best league finish and + related records are available on the Career Identity profile; read-only recognition remains. - [ ] Mascot loading/companion (Dot with a mood during skeleton loads) - [ ] Weekly recap / Monday ritual surface - [ ] Notifications: "last chance to promote", streak/recovery nudges @@ -138,21 +138,20 @@ Reviewed all 20 pages of `Buildment_Gamification_Design_Concepts_images/`. Statu | 17 | XP microinteraction | 🟡 Partial | XP awarding exists; subtle "+20 XP, 1.5s, return focus" UI not verified | | 19 | Mobile fast screens | 🟡 Partial | Responsive exists; not the dedicated League/Rewards mobile layouts | | 4/5 | Dashboard A/B (calm / arcade) | 🟡 Partial | Functional dashboard, not the exact layouts | -| 7 | **Achievement promotion (published weekly XP goal)** | ❌ Missing | Only percentile promotion (known Phase 1 gap) | +| 7 | **Achievement promotion (published weekly XP goal)** | ✅ Done | Fixed tier goals: 100 / 200 / 400 / 700 / 1,000 XP; one-tier maximum | | 10 | **Monday ritual / weekly recap** | ❌ Missing | No promotion celebration + next-goal screen | -| 18 | **Weekly missions (quest board)** | ❌ Missing | No effort-based mission → credit loop | -| 9 | Recovery quest / pause week | ❌ Missing | Shield only | +| 18 | **Weekly missions (quest board)** | ✅ Done | Weekly quest board and idempotent credit claims shipped in PR #172 | +| 9 | Recovery quest / pause week | 🟡 Partial | Recovery quest is implemented; pause week remains out of scope | | 20 | Experiments / measurement | ❌ Missing | Not built | ### Prioritized next work -- **P0:** (1) achievement promotion — published weekly XP target as an alternate promotion path; (2) - Monday ritual / weekly recap (promotion result + credits + next goal); (3) weekly missions (quest → - credits). +- **P0:** (1) Monday ritual / weekly recap (promotion result + credits + next goal); (2) daily quests, + chests and monthly badge; (3) notifications for promotion and recovery. - **P1:** category weekly track (pick one, route XP, no double-count); league journey view with XP thresholds + separate identity; leaderboard "fair / promotion secured" state. - **P2:** 3 branded share cards; mascot family reactions + motion/reduced-motion; XP microinteraction; - recovery quest / pause week; dedicated mobile League/Rewards; experiments vs non-gamified control. + pause week; dedicated mobile League/Rewards; experiments vs non-gamified control. ### Already solid Leagues + tiers, career ladder, Build Credits economy, marketplace (incl. League Shield), the Career -Identity shared profile, Records, Achievements, and the activity heatmap. \ No newline at end of file +Identity shared profile, Records, Achievements, and the activity heatmap. diff --git a/frontend/src/app/(admin)/admin/desktop-updates/page.tsx b/frontend/src/app/(admin)/admin/desktop-updates/page.tsx index a9ce56d4a..e807682b1 100644 --- a/frontend/src/app/(admin)/admin/desktop-updates/page.tsx +++ b/frontend/src/app/(admin)/admin/desktop-updates/page.tsx @@ -1,8 +1,7 @@ import { serverApiFetch } from "@/lib/api-server"; -import { AdminPageHeader, AdminPanel } from "@/components/admin/admin-ui"; +import { AdminPageHeader } from "@/components/admin/admin-ui"; import { DesktopUpdatesPanel } from "@/components/admin/desktop-updates-panel"; import { forceDesktopUpdateToLatest, saveDesktopUpdateRules } from "@/server/actions/admin/desktop-updates"; -import { formatUpdatedAt, platformLabel } from "@/lib/desktop-updates"; import type { DesktopUpdatesView } from "@/shared/api/desktop-updates"; // The admin layout already requires the ADMIN role for everything under /admin. @@ -14,43 +13,8 @@ export default async function AdminDesktopUpdatesPage() { - -
- {policies.map((policy) => ( - -

{platformLabel(policy.platform)}

-
-
-
Minimum version
-
{policy.minimumVersion}
-
-
-
Latest version
-
{policy.latestVersion}
-
-
-
Blocked versions
-
- {policy.blockedVersions.length > 0 ? policy.blockedVersions.join(", ") : "None"} -
-
-
-

- {policy.isDefault || !policy.updatedAt ? ( - "Not set: using defaults" - ) : ( - <> - Changed by {policy.updatedBy ? policy.updatedBy.name || policy.updatedBy.email : "unknown"} on{" "} - - - )} -

-
- ))} -
-
); diff --git a/frontend/src/app/(learn)/(catalog)/labs/shell/page.tsx b/frontend/src/app/(learn)/(catalog)/labs/shell/page.tsx index c7e5a4561..e794d26bd 100644 --- a/frontend/src/app/(learn)/(catalog)/labs/shell/page.tsx +++ b/frontend/src/app/(learn)/(catalog)/labs/shell/page.tsx @@ -1,11 +1,12 @@ import type { Metadata } from "next"; -import { Container, FolderOpen, LogIn, MonitorDown, Terminal } from "lucide-react"; +import Link from "next/link"; +import { ArrowRight, Container, FolderOpen, LogIn, MonitorDown, Terminal } from "lucide-react"; import { SITE_SHARE_IMAGE } from "@/lib/site"; -import { AreaHero, AreaPage, AreaSection, CardGrid, ComingSoonPanel, InfoCard } from "@/components/areas/area-page"; +import { AreaHero, AreaPage, AreaSection, CardGrid, InfoCard } from "@/components/areas/area-page"; export const metadata: Metadata = { title: "Shell labs and the desktop app", - description: "Real shell work on real machines, in the Edorax desktop app. What it does today and what is coming.", + description: "46 hands-on shell labs on real Linux machines, containers and networks, in the free Edorax desktop app. Download it here.", alternates: { canonical: "/labs/shell" }, openGraph: { title: "Shell labs on Edorax", url: "/labs/shell", images: [SITE_SHARE_IMAGE] }, }; @@ -16,9 +17,9 @@ export default function ShellLabsPage() { @@ -32,11 +33,12 @@ export default function ShellLabsPage() {
} title="What it does today">
    +
  • Run the 46 shell labs: each gives you a task, hints and a Check button that looks at the machine.
  • Browse the course catalogue and course previews.
  • Read lessons in a native reader, with the same diagrams, labs and quizzes as the web.
  • Open a course IDE beside a lesson: edit files, run a terminal, and check exercises.
  • @@ -55,22 +57,37 @@ export default function ShellLabsPage() { before it removes them. You need Docker Desktop running for this mode.

    - } title="What is coming for shell labs"> + } title="Still to come">
      -
    • Lab machines that a course defines: Linux hosts, containers and small networks.
    • -
    • Tests that check the machine after each step.
    • -
    • Progress that syncs to your account, the same as chapters.
    • +
    • Labs that need their own kernel, such as systemd and disk storage.
    • +
    • Installers that are signed, so Windows and macOS stop showing a warning.
    • +
    • An app that updates itself. For now you download a new version.

- The app is tested on Apple silicon Macs first. Windows and Intel Macs follow. Downloads will be linked here when it is ready. + Shell labs need Docker Desktop running on your computer. Your lab progress is saved on your account.

- - Visual labs are open today in the browser, with no install. - + +
+
+

Windows, macOS (Apple silicon) and Linux. Version 0.1.0, early release.

+

+ The installers are not signed yet, so Windows or macOS may show a warning the first time. Choose to run it anyway. Intel Macs are + not built yet. +

+
+ + Download the app + + +
+
); } diff --git a/frontend/src/app/(learn)/(main)/highlights/page.tsx b/frontend/src/app/(learn)/(main)/highlights/page.tsx new file mode 100644 index 000000000..4301bc1f9 --- /dev/null +++ b/frontend/src/app/(learn)/(main)/highlights/page.tsx @@ -0,0 +1,22 @@ +import { serverApiFetch } from "@/lib/api-server"; +import { HighlightsLibrary } from "@/components/learn/highlights-library"; +import type { UserHighlightView } from "@/server/actions/highlights"; + +export const dynamic = "force-dynamic"; + +export default async function HighlightsPage() { + let highlights: UserHighlightView[]; + try { + highlights = await serverApiFetch("/api/v1/learner/highlights"); + } catch { + return ( +
+

My Highlights

+

+ Your highlights could not be loaded. This is not the same as having none. Reload the page to try again. +

+
+ ); + } + return ; +} diff --git a/frontend/src/app/(learn)/courses/[courseSlug]/[chapterSlug]/page.tsx b/frontend/src/app/(learn)/courses/[courseSlug]/[chapterSlug]/page.tsx index b3cda8b9d..29a200a3c 100644 --- a/frontend/src/app/(learn)/courses/[courseSlug]/[chapterSlug]/page.tsx +++ b/frontend/src/app/(learn)/courses/[courseSlug]/[chapterSlug]/page.tsx @@ -119,6 +119,7 @@ export default async function ChapterReaderPage({ recap={content.recap} streakMilestone={content.streakMilestone} headingNotes={content.headingNotes} + highlights={content.highlights} predictGate={content.predictGate} predictRevealed={content.predictRevealed} promptCourseRating={Boolean(content.promptCourseRating)} diff --git a/frontend/src/components/admin/desktop-updates-panel.tsx b/frontend/src/components/admin/desktop-updates-panel.tsx index 419a8db18..67a1d04ee 100644 --- a/frontend/src/components/admin/desktop-updates-panel.tsx +++ b/frontend/src/components/admin/desktop-updates-panel.tsx @@ -1,508 +1,295 @@ "use client"; -import { useEffect, useId, useRef, useState, useTransition, type KeyboardEvent } from "react"; +import { useState, useTransition } from "react"; import { useRouter } from "next/navigation"; -import { AlertTriangle, X } from "lucide-react"; import { Button } from "@/components/ui/button"; import { toast } from "@/components/ui/app-toast"; import { AdminPanel } from "@/components/admin/admin-ui"; import { cn } from "@/lib/utils"; import { - BLOCKED_VERSIONS_MAX, DESKTOP_PLATFORMS, MESSAGE_MAX_LENGTH, - addBlockedVersion, buildUpdateRequest, + compareVersions, describeForcePlan, - joinPlatformLabels, + formatUpdatedAt, + isValidVersion, planForceToLatest, platformLabel, - removeBlockedVersion, - type RulesFormValues, } from "@/lib/desktop-updates"; import type { DesktopPlatform, DesktopUpdatePolicy, DesktopUpdateRequest } from "@/shared/api/desktop-updates"; type ActionResult = { ok: boolean; message: string }; +type Actions = { + saveRules: (input: DesktopUpdateRequest) => Promise; + forceToLatest: (input: { confirmed: Partial> }) => Promise; +}; const fieldClass = "flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm shadow-xs outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:opacity-60"; const labelClass = "flex flex-col gap-1 text-xs font-medium text-muted-foreground"; -const hintClass = "text-[11px] font-normal text-muted-foreground"; - -const EMPTY_VALUES: RulesFormValues = { - minimumVersion: "", - latestVersion: "", - downloadUrl: "", - message: "", - blockedVersions: [], -}; - -function prefill(policy: DesktopUpdatePolicy | null): RulesFormValues { - if (!policy) return EMPTY_VALUES; - return { - minimumVersion: policy.minimumVersion, - latestVersion: policy.latestVersion, - downloadUrl: policy.downloadUrl, - message: policy.message, - blockedVersions: [...policy.blockedVersions], - }; -} -export function DesktopUpdatesPanel({ - policies, - saveRules, - forceToLatest, -}: { - policies: DesktopUpdatePolicy[]; - saveRules: (input: DesktopUpdateRequest) => Promise; - forceToLatest: (input: { confirmed: Partial> }) => Promise; -}) { +/** Runs a server action, shows the answer, and reloads the page data when it worked. */ +function useRunner() { const router = useRouter(); - const [selected, setSelected] = useState([]); - const [result, setResult] = useState(null); - const [resets, setResets] = useState(0); const [pending, startTransition] = useTransition(); - - const allSelected = selected.length === DESKTOP_PLATFORMS.length; - const single = selected.length === 1 ? (policies.find((policy) => policy.platform === selected[0]) ?? null) : null; - - const toggle = (platform: DesktopPlatform, checked: boolean) => - setSelected(DESKTOP_PLATFORMS.filter((item) => (item === platform ? checked : selected.includes(item)))); - - const report = (next: ActionResult) => { - setResult(next); - toast(next.message, next.ok ? "success" : "error"); - if (next.ok) { - setResets((count) => count + 1); - router.refresh(); - } - }; - - const run = (work: () => Promise) => + const [result, setResult] = useState(null); + const run = (work: () => Promise, after?: () => void) => startTransition(async () => { + let next: ActionResult; try { - report(await work()); + next = await work(); } catch { - report({ ok: false, message: "Something went wrong. Please try again." }); + next = { ok: false, message: "Something went wrong. Please try again." }; + } + setResult(next); + toast(next.message, next.ok ? "success" : "error"); + if (next.ok) { + after?.(); + router.refresh(); } }); + return { pending, result, setResult, run }; +} +function Result({ result }: { result: ActionResult | null }) { + if (!result) return null; return ( - -
-

Change the update rules

-

- Choose the platforms first. Then change only the fields you need. -

-
- -
- Apply to -
- {DESKTOP_PLATFORMS.map((platform) => ( - - ))} - -
- {selected.length === 0 ? ( -

Choose at least one platform.

- ) : null} -
- - 0 ? "many" : "none"}:${resets}`} - selected={selected} - single={single} - pending={pending} - onSave={(request) => run(() => saveRules(request))} - onError={(message) => { - setResult({ ok: false, message }); - }} - /> - - run(() => forceToLatest({ confirmed }))} - /> - -
- {result ? ( -

- {result.message} -

- ) : null} -
-
+

+ {result.message} +

); } -function RulesForm({ - selected, - single, - pending, - onSave, - onError, +/** A button that asks once more before it does something that locks users out. */ +function ConfirmButton({ + label, + question, + disabled, + onConfirm, }: { - selected: DesktopPlatform[]; - single: DesktopUpdatePolicy | null; - pending: boolean; - onSave: (request: DesktopUpdateRequest) => void; - onError: (message: string) => void; + label: string; + question: string; + disabled?: boolean; + onConfirm: () => void; }) { - const [values, setValues] = useState(() => prefill(single)); - const [clearMessage, setClearMessage] = useState(false); - const [clearBlocked, setClearBlocked] = useState(false); - const [blockedInput, setBlockedInput] = useState(""); - const [blockedError, setBlockedError] = useState(""); - const [errors, setErrors] = useState([]); - const blockedErrorId = useId(); - const errorsId = useId(); - - const set = (key: K, value: RulesFormValues[K]) => { - setValues((current) => ({ ...current, [key]: value })); - setErrors([]); - }; - - const addBlocked = () => { - const outcome = addBlockedVersion(values.blockedVersions, blockedInput); - if (!outcome.ok) { - setBlockedError(outcome.error); - return; - } - setBlockedError(""); - setBlockedInput(""); - setClearBlocked(false); - set("blockedVersions", outcome.list); - }; - - const onBlockedKey = (event: KeyboardEvent) => { - if (event.key === "Enter") { - event.preventDefault(); - addBlocked(); - } - }; - - const disabled = pending || selected.length === 0; - + const [asking, setAsking] = useState(false); + if (!asking) { + return ( + + ); + } return ( -
{ - event.preventDefault(); - const built = buildUpdateRequest({ - platforms: selected, - values, - clear: { message: clearMessage, blockedVersions: clearBlocked }, - current: single, - }); - if (!built.ok) { - setErrors(built.errors); - onError(built.errors.join(" ")); - return; - } - setErrors([]); - onSave(built.request); - }} - > -

- {single - ? `The fields show the saved values for ${platformLabel(single.platform)}. Change what you need.` - : selected.length > 1 - ? "Empty fields stay as they are. Whatever you fill in is saved for every platform you chose." - : "Choose a platform to see its saved values."} -

+ + {question} + + + + ); +} -
- - -
+export function DesktopUpdatesPanel({ policies, saveRules, forceToLatest }: { policies: DesktopUpdatePolicy[] } & Actions) { + const all = useRunner(); + const plan = planForceToLatest(DESKTOP_PLATFORMS, policies); -