Example: an LMS back office
examples/lms is a small learning-management back office built on RustCMS: courses with a capacity and an instructor, their lessons, learners and enrollments run by staff and instructors, and the school's news written by editors. Read it when you want a complete application to copy from: it follows the application layout and shows where each kind of code goes.
The LMS example: the courses table as staff see it (every course).
What it shows:
| Topic | Where |
|---|---|
| Resources with forms, tables, filters, relations | src/admin/resources/ |
| Business rules in a service, called from hooks, an action and seeders | src/services/enrollment_service.rs |
| Parent locks: every enrollment write locks its course first | ResourceMeta::lock_parent in enrollment_resource.rs |
| Row scoping: instructors see their courses only | scope() + src/models/course.rs, learner.rs |
| Field rules and a policy | course_resource.rs, src/policies/ |
| An action with a form | Enroll a learner… on a course; Move up / Move down on a lesson |
| A dashboard | src/providers/admin_panel_provider.rs |
| A custom page, a slot, a custom cell, a theme | src/admin/pages/, src/admin/slots/, resources/ |
| A job that sends mail, queued with the write | src/jobs/send_welcome.rs |
| A settings group | src/settings/lms_settings.rs |
| Media, rich text, belongs-to-many | src/admin/resources/news_resource.rs |
| Translations (Vietnamese) | lang/vi.toml |
| Feature tests on SQLite, PostgreSQL and MySQL | tests/feature/ |
Quick start
From a checkout of the repository:
cd examples/lms
cp .env.example .env && cargo run -- key:generate # first time only
cargo run -- migrate
cargo run -- db:seed
cargo run -- serve # also runs the queue workersOpen http://localhost:8000/admin (the listen address in config/app.toml) and sign in with one of the seeded accounts. Every account's password is password123.
| Account | Role | Sees and does |
|---|---|---|
admin@example.test | super admin (admin guard) | everything in the panel, including System → Users and Roles (invites instructors); not a super admin of the API guard, so it cannot replace other users' passwords or emails |
staff@example.test | staff | every course (lms.all_courses), assigns instructors, enrolls learners, imports learners, exports enrollments, edits the School settings |
teacher@example.test | instructor | the courses they teach (Introduction to Rust, Web services with Axum), their lessons, learners and enrollments; records progress |
tutor@example.test | instructor | a second instructor (Databases with SeaORM): sign in as both to see the scoping |
editor@example.test | editor | the news, categories, tags and their images; nothing of the courses |
viewer@example.test | viewer | reads everything of the school, exports enrollments, sees the dashboard; changes nothing |
The accounts and their roles come from the seeders:
/// Password of the seeded accounts (example only).
pub const PASSWORD: &str = "password123";
/// `(name, email, role)`; `None` is the super admin.
pub const ACCOUNTS: [(&str, &str, Option<&str>); 6] = [
("Ada Admin", "admin@example.test", None),
("Sam Staff", "staff@example.test", Some("staff")),
("Tess Teacher", "teacher@example.test", Some("instructor")),
("Tom Tutor", "tutor@example.test", Some("instructor")),
("Eve Editor", "editor@example.test", Some("editor")),
("Vic Viewer", "viewer@example.test", Some("viewer")),
];pub struct RoleSeeder;
#[async_trait]
impl Seeder for RoleSeeder {
fn name(&self) -> &'static str {
"role"
}
async fn run(&self, state: &AppState) -> anyhow::Result<()> {
let auth = state.service::<AuthState>().expect("AuthProvider");
let rbac = RbacService::new(state.db(), &auth.resolver);
rbac.sync_permissions(&auth.permissions.all()).await?;
let roles = [("staff", STAFF), ("instructor", INSTRUCTOR), ("editor", EDITOR), ("viewer", VIEWER)];
for (name, permissions) in roles {
if find(state, name).await?.is_none() {
let permissions: Vec<String> = permissions.iter().map(|p| (*p).to_owned()).collect();
rbac.create_role(Actor::System, ADMIN_GUARD, name, &permissions).await?;
}
}
Ok(())
}
}db:seed can run again: each seeder finds rows by a natural key (an email, a slug) before creating them, so a second run completes what an earlier one left. The user seeder refuses to run in production, even with db:seed --force: it creates accounts with a public password.
Another database
.env.example has commented DATABASE_URLs for PostgreSQL and MySQL 8.4 (the MySQL database needs CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_bin).
Data
| Table | Columns |
|---|---|
courses | title, slug (unique), summary, capacity, published, instructor_id → users (set to null when the user is deleted), created_at |
lessons | course_id → courses (deleted with it), title, position, body |
learners | name, email (unique), phone, created_at: people taking courses, without a sign-in |
enrollments | course_id, learner_id (unique together, deleted with either), status active / withdrawn, progress 0–100, enrolled_at |
categories, tags | name (unique) |
news | title, slug (unique), body (rich text), cover (a media item), category_id, author_id, published_at (empty: a draft; in the future: scheduled), created_at |
news_tags | the tags of an article (belongs-to-many) |
Where the code is
| Path | Holds |
|---|---|
src/bootstrap/mod.rs, providers.rs | the application: providers, migrations, API routes |
src/providers/admin_panel_provider.rs | the panel: theme, resources, settings pages (School, Mail), dashboard, page, slot, cell script, translations |
src/providers/auth_service_provider.rs | permissions beyond each resource's CRUD abilities |
src/providers/app_service_provider.rs | seeders, the lms.enrolled job, mail templates |
src/services/enrollment_service.rs | the seat rules (check, enroll_in, enroll), used by the panel, the action and the seeders |
src/models/ | entities; scope helpers course::taught_by, learner::taught_by |
src/policies/ | permission names, instructor(ctx), EnrollmentPolicy |
src/admin/resources/ | the seven resources |
src/admin/pages/ | the Course overview page and the School settings page |
src/admin/slots/course_seats_slot.rs | the Seats card beside a course |
src/settings/lms_settings.rs | the lms settings group |
src/jobs/send_welcome.rs | the lms.enrolled job |
src/routes/api.rs | the JSON API (GET /api/v1/ping, public) |
src/database/ | migrations, seeders, factories |
resources/ | the logo and favicon, page and slot templates, the cell script and style, mail templates |
lang/vi.toml | Vietnamese labels and messages |
tests/feature/ | enrollments, instructors, news (with lessons), customizing, seeding, languages |
Seats and parent locks
A course takes at most capacity active enrollments, and a learner enrolls in a course once (withdrawing and coming back change the same row). The rules are one function in the service. It returns Ok(Err(Refusal)) for a refused enrollment, so callers decide how to report it:
/// Whether an enrollment of `learner_id` in `course_id` with `status` may be
/// written; `current` is the enrollment being changed, if any. The caller
/// holds the course's lock.
pub async fn check(
txn: &DatabaseTransaction,
course_id: i64,
learner_id: i64,
status: &str,
current: Option<i64>,
) -> AppResult<Result<(), Refusal>> {
if status != enrollment::ACTIVE && status != enrollment::WITHDRAWN {
return Ok(Err(Refusal::UnknownStatus));
}
let Some(course) = course::Entity::find_by_id(course_id).one(txn).await? else {
return Ok(Err(Refusal::NoCourse));
};
let mut others = enrollment::Entity::find().filter(enrollment::Column::CourseId.eq(course_id));
if let Some(id) = current {
others = others.filter(enrollment::Column::Id.ne(id));
}
// Already in: said before the seats, which would not help.
if others.clone().filter(enrollment::Column::LearnerId.eq(learner_id)).count(txn).await? > 0 {
return Ok(Err(Refusal::AlreadyEnrolled));
}
if status == enrollment::ACTIVE {
let taken = others.filter(enrollment::Column::Status.eq(enrollment::ACTIVE)).count(txn).await?;
if taken >= u64::try_from(course.capacity).unwrap_or(0) {
return Ok(Err(Refusal::NoSeat));
}
}
Ok(Ok(()))
}/// Why an enrollment cannot be written.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Refusal {
NoCourse,
AlreadyEnrolled,
NoSeat,
UnknownStatus,
}
impl Refusal {
/// The field it concerns and its message (English source, translated by
/// the caller: `ctx.t` in the admin panel).
pub fn reason(self) -> (&'static str, &'static str) {
match self {
Self::NoCourse => ("course_id", "is not a course"),
Self::AlreadyEnrolled => ("learner_id", "is already enrolled in this course"),
Self::NoSeat => ("course_id", "has no seats left"),
Self::UnknownStatus => ("status", "must be active or withdrawn"),
}
}
/// As validation errors, messages passed through `translate`.
pub fn errors(self, translate: impl Fn(&str) -> String) -> ValidationErrors {
let (field, message) = self.reason();
ValidationErrors::field(field, translate(message))
}
}check counts the course's enrollments, so it must run under the course's row lock, or two requests could both take the last seat. Every path takes that lock first.
In the panel, the enrollment resource declares a parent lock. Every enrollment write locks its course before the hooks run (both courses when an enrollment moves), and a unique constraint is mapped to a message:
/// Every write first locks the course (both, when moving): the seat count
/// and the instructor's access hold until it commits.
fn meta() -> ResourceMeta {
ResourceMeta::new("Enrollment")
.icon("activity")
.exportable()
.group("Learning")
.lock_parent("course_id", "courses")
.unique(
"enrollments_course_learner_key",
&["course_id", "learner_id"],
"This learner is already enrolled in this course.",
)
}The hooks then call check in the write's transaction. A new active enrollment also queues the welcome mail in the same transaction, so a refused or failed write queues nothing:
async fn mutate_before_create(ctx: &Ctx, txn: &DatabaseTransaction, data: Data) -> AppResult<Data> {
let (Some(course_id), Some(learner_id)) = (int(&data, "course_id"), int(&data, "learner_id")) else {
// The engine reports the missing fields.
return Ok(data);
};
let status = data.get("status").and_then(|v| v.as_str()).unwrap_or(enrollment::ACTIVE).to_owned();
enrollment_service::check(txn, course_id, learner_id, &status, None)
.await?
.map_err(|refusal| refusal.errors(|m| ctx.t(m)))?;
if status == enrollment::ACTIVE {
// Queued with the enrollment: no enrollment, no job.
ctx.dispatch(txn, &SendWelcome { course_id, learner_id }).await?;
}
Ok(data)
}
async fn mutate_before_update(
ctx: &Ctx,
txn: &DatabaseTransaction,
record: &enrollment::Model,
data: Data,
) -> AppResult<Data> {
if data.contains_key("progress") && !matches!(int(&data, "progress"), Some(0..=100)) {
return Err(ValidationErrors::field("progress", ctx.t("must be between 0 and 100")).into());
}
let course_id = int(&data, "course_id").unwrap_or(record.course_id);
let learner_id = int(&data, "learner_id").unwrap_or(record.learner_id);
let status = data.get("status").and_then(|v| v.as_str()).unwrap_or(&record.status).to_owned();
// Moving, or coming back: checked again (the engine locked both courses).
if course_id != record.course_id || learner_id != record.learner_id || status != record.status {
enrollment_service::check(txn, course_id, learner_id, &status, Some(record.id))
.await?
.map_err(|refusal| refusal.errors(|m| ctx.t(m)))?;
}
Ok(data)
}In an action, the course's Enroll a learner… asks for a learner in a dialog. An action locks the records it runs on, so it calls enroll_in directly. A refusal on the learner shows under the field; others show on the dialog; the whole action rolls back:
/// "Enroll a learner…": a dialog asks which (a learner the user may see);
/// the course is locked by the action, then the seat rules apply.
fn actions() -> Vec<Action<course::Entity>> {
vec![
Action::<course::Entity>::new("enroll", |ctx, txn, courses, data| {
Box::pin(async move {
let learner: i64 = data["learner_id"].as_str().and_then(|k| k.parse().ok()).unwrap_or_default();
for course in courses {
if let Err(refusal) = enrollment_service::enroll_in(txn, course.id, learner).await? {
// On the learner input, or the dialog; the whole action is rolled back.
let (field, message) = refusal.reason();
let mut errors = ValidationErrors::new();
if field == "learner_id" {
errors.add(field, ctx.t(message));
} else {
errors.add_form(ctx.t(message));
}
return Err(errors.into());
}
}
Ok(())
})
})
.label("Enroll a learner…")
.ability("view")
.requires_permission("enrollments.create")
.form(vec![ActionField::belongs_to("learner_id", "learners").label("Learner").required()]),
]
}
The LMS example: Enroll a learner… on a full course answers "has no seats left".
/// Enrolls `learner_id` in `course_id` (active) in `txn`, whose caller holds
/// the course's lock (an action on the course, or [`enroll`]), queuing the
/// welcome with it.
pub async fn enroll_in(
txn: &DatabaseTransaction,
course_id: i64,
learner_id: i64,
) -> AppResult<Result<enrollment::Model, Refusal>> {
if let Err(refusal) = check(txn, course_id, learner_id, enrollment::ACTIVE, None).await? {
return Ok(Err(refusal));
}
let created = enrollment::ActiveModel {
course_id: Set(course_id),
learner_id: Set(learner_id),
status: Set(enrollment::ACTIVE.into()),
progress: Set(0),
enrolled_at: Set(chrono::Utc::now()),
..Default::default()
}
.insert(txn)
.await?;
rustcms::queue::dispatch(txn, &SendWelcome { course_id, learner_id }).await?;
Ok(Ok(created))
}Elsewhere (seeders, jobs, an API), enroll opens its own transaction, locks the course and calls enroll_in. The enrollment seeder uses it, so seeding never overfills a course:
/// Locks the course's row until `txn` ends (SQLite: the write transaction
/// already holds the database lock).
pub async fn lock_course(txn: &DatabaseTransaction, course_id: i64) -> AppResult<Option<course::Model>> {
let select = course::Entity::find_by_id(course_id);
let select = if txn.get_database_backend() == DbBackend::Sqlite { select } else { select.lock_exclusive() };
Ok(select.one(txn).await?)
}/// Enrolls `learner_id` in `course_id` (active) in a transaction of its own,
/// queuing the welcome with it. For code outside the admin panel (seeders,
/// jobs, an API).
pub async fn enroll(
db: &DatabaseConnection,
course_id: i64,
learner_id: i64,
) -> AppResult<Result<enrollment::Model, Refusal>> {
let txn = rustcms::db::begin_write(db).await?;
lock_course(&txn, course_id).await?;
match enroll_in(&txn, course_id, learner_id).await? {
Ok(created) => {
txn.commit().await?;
Ok(Ok(created))
}
Err(refusal) => {
txn.rollback().await?;
Ok(Err(refusal))
}
}
}The result: two requests for the last seat get one 201 and one 422, and a course and its enrollments changed at the same time never deadlock (the course is always locked first, the order its deletion cascades in). The test:
// Two new enrollments.
let course = CourseFactory::new().capacity(1).create(db).await;
let (ann, bob) = (LearnerFactory.create(db).await, LearnerFactory.create(db).await);
let (a, b) = tokio::join!(enroll(&app, &staff, course.id, ann.id), enroll(&app, &other, course.id, bob.id));
assert_eq!(
statuses(&a, &b),
[StatusCode::CREATED, StatusCode::UNPROCESSABLE_ENTITY],
"{} / {}",
a.text(),
b.text()
);
assert_eq!(active(&app, course.id).await, 1);More rules:
- A capacity below the active enrollments is refused (
course_resource.rs, under the same lock: the engine locks a course while it is updated). - The unique constraint
enrollments_course_learner_keystays as the last line of defence and is answered with the message given toResourceMeta::unique. - To move an enrollment, staff change its
course_id: the seat is checked in the new course. To withdraw, setstatustowithdrawn; setting it back toactiveneeds a free seat. statusmust be one of the form'sSelectInput::options(options are validated); the service checks it too (UnknownStatus), for the enroll action and the seeder, which do not go through the form.
See Parent locks and Actions with a form.
Instructors see their courses
Staff hold lms.all_courses; everyone else sees what they teach. One helper says whose courses bound a user:
/// The instructor whose courses bound what `ctx` sees, or `None` for staff.
pub fn instructor(ctx: &Ctx) -> Option<i64> {
if ctx.can(permissions::ALL_COURSES) {
return None;
}
// A principal that is not a user id sees nothing.
Some(ctx.principal.id.parse::<i64>().unwrap_or(-1))
}Courses filter on their own column; lessons, enrollments and learners use an EXISTS subquery from the model (a join could repeat rows):
/// Instructors see the courses they teach.
fn scope(query: Select<course::Entity>, ctx: &Ctx) -> Select<course::Entity> {
match instructor(ctx) {
None => query,
Some(me) => query.filter(course::Column::InstructorId.eq(me)),
}
}/// Scope: the course whose id is `course_id` (a column of the outer query)
/// is taught by `instructor`. `EXISTS` keeps one row per outer row, where a
/// join could repeat them.
pub fn taught_by(instructor: i64, course_id: impl IntoColumnRef) -> SimpleExpr {
Expr::exists(
Query::select()
.expr(Expr::val(1))
.from(Entity)
.and_where(Expr::col((Entity, Column::Id)).equals(course_id))
.and_where(Expr::col((Entity, Column::InstructorId)).eq(instructor))
.to_owned(),
)
}/// Instructors see the lessons of their courses.
fn scope(query: Select<lesson::Entity>, ctx: &Ctx) -> Select<lesson::Entity> {
match instructor(ctx) {
None => query,
Some(me) => query.filter(course::taught_by(me, (lesson::Entity, lesson::Column::CourseId))),
}
}The scope applies on every path: lists, direct ids, options, relations and writes. Another teacher's course, its lessons and enrollments answer 404, are not offered as options, and cannot be picked for a lesson (not even by overriding course_id when creating from a course's page). Learners are shared: an instructor sees every learner enrolled (in any status) in at least one of their courses, even if the learner also takes other teachers' courses; a learner with no enrollment in their courses answers 404. Lessons and enrollments lock their course first, so an instructor removed from a course loses access to it at once.
The LMS example: the same table as teacher@example.test, two courses only.
Field rules and the policy
The extra permissions are declared on the auth provider:
/// Every course, not only the ones taught.
pub const ALL_COURSES: &str = "lms.all_courses";
/// Choosing a course's instructor.
pub const ASSIGN_INSTRUCTOR: &str = "courses.assign_instructor";
/// Recording a learner's progress (the only change to an enrollment it allows).
pub const UPDATE_PROGRESS: &str = "enrollments.update_progress";pub fn provider(api: &ApiRoutes) -> AuthProvider {
AuthProvider::new()
.permission(ADMIN_GUARD, ALL_COURSES, "courses")
.permission(ADMIN_GUARD, ASSIGN_INSTRUCTOR, "courses")
.permission(ADMIN_GUARD, UPDATE_PROGRESS, "enrollments")
// The API's permissions come from its routes.
.api_permissions(api)
}instructor_idis set only withcourses.assign_instructor(field rulescreatable/updatable), and must name a user (checked in the hook):rsfn fields() -> Vec<Field> { vec![ Field::column(course::Column::Title).required().searchable().sortable().max_length(200), Field::column(course::Column::Slug).required().searchable().max_length(120), Field::column(course::Column::Summary).max_length(2000), Field::column(course::Column::Capacity).required().sortable(), Field::column(course::Column::Published).filterable().sortable(), Field::column(course::Column::CreatedAt).guarded().readable(|_| true).sortable(), // Who teaches it decides who sees it: only staff choose. Field::column(course::Column::InstructorId) .label("Instructor") .filterable() .creatable(|ctx| ctx.can(ASSIGN_INSTRUCTOR)) .updatable(|ctx| ctx.can(ASSIGN_INSTRUCTOR)), ] }progressis never set when enrolling (creatable(|_| false)) and changes only withenrollments.update_progress.EnrollmentPolicylets that permissionupdatean enrollment; the field rules keep every other field closed to it:rs/// `enrollments.<ability>`; `enrollments.update_progress` also admits `update` /// (field rules then limit the change to `progress`). Decisions never depend /// on the record: which records a user sees is the resource's scope. pub struct EnrollmentPolicy; impl EnrollmentPolicy { fn grants(ctx: &Ctx, ability: &str) -> bool { ctx.can(&format!("enrollments.{ability}")) || (ability == "update" && ctx.can(UPDATE_PROGRESS)) } } #[async_trait::async_trait] impl Policy for EnrollmentPolicy { async fn allows(&self, ctx: &Ctx, ability: &str, _record: Option<&Data>) -> bool { Self::grants(ctx, ability) } /// Refused before any lookup: without the permission, 403 whether the /// enrollment exists or not. async fn admits(&self, ctx: &Ctx, ability: &str) -> bool { Self::grants(ctx, ability) } /// Lists need no per-record check (no scan of the matching rows). fn view_depends_on_record(&self) -> bool { false } }admitsrefuses abilities before any lookup (403 whether the enrollment exists or not).view_depends_on_record() == falsesays the policy never filters records itself: the scope decides visibility, so lists need no record-by-record scan.
See Authorization.
Lessons in order
Move up / Move down on a lesson swap it with its neighbour among the lessons of its course that the user may see. The lesson resource declares .lock_parent("course_id", "courses"), so the action locks the course and moves of one course never interleave. The lessons are ordered by position (ties in id order), the lesson swaps places with its neighbour (at either end the move does nothing), then positions are written as 1…n; every lesson whose position changes is recorded in the audit log:
/// Moves `lesson` one place among the lessons of its course the user may see
/// (the course is locked by the action: moves of one course never interleave).
/// The lessons are taken by position then id, `lesson` swaps with its
/// neighbour (nothing happens at either end), then positions are written as
/// 1…n; every lesson whose position changes is recorded.
async fn reorder(ctx: &Ctx, txn: &DatabaseTransaction, lesson: &lesson::Model, up: bool) -> AppResult<()> {
let siblings = LessonResource::scope(lesson::Entity::find(), ctx)
.filter(lesson::Column::CourseId.eq(lesson.course_id))
.order_by_asc(lesson::Column::Position)
.order_by_asc(lesson::Column::Id)
.all(txn)
.await?;
let mut order: Vec<&lesson::Model> = siblings.iter().collect();
let Some(index) = order.iter().position(|l| l.id == lesson.id) else { return Ok(()) };
let neighbour = if up { index.checked_sub(1) } else { Some(index + 1).filter(|n| *n < order.len()) };
let Some(neighbour) = neighbour else { return Ok(()) };
order.swap(index, neighbour);
for (n, row) in order.into_iter().enumerate() {
let position = i32::try_from(n + 1).unwrap_or(i32::MAX);
if row.position == position {
continue;
}
let mut model: lesson::ActiveModel = row.clone().into();
model.position = Set(position);
model.update(txn).await?;
let entry = AuditEntry::new("updated", LessonResource::SLUG)
.key(row.id)
.changes(json!({ "position": [row.position, position] }));
rustcms::audit::record(txn, &ctx.audit_context, entry).await?;
}
Ok(())
}
The LMS example: a course's lessons and their Move up / Move down actions.
News
Editors (editor role) write articles with a cover image and a rich-text body, pick a category and link tags on the article's page (news.attach_tags / news.detach_tags). An empty slug is made from the title (slugify, Vietnamese marks removed); a taken slug is refused with 422. Scheduled is an article whose published_at is in the future: nothing publishes it, the date only filters it.
The LMS example: an article with its cover, rich-text body and tags.
See Media, uploads & rich text and Relationships.
Dashboard
Four widgets, each behind its own permission (dashboard.<name>), granted to staff, instructors and viewers. Instructors' counts follow the enrollments' scope:
.dashboard(
Dashboard::new()
.widget(Widget::stat("learners", "learners").label("Learners"))
.widget(
Widget::stat("new_enrollments", "enrollments")
.label("New enrollments")
.compare_last_days(30, "enrolled_at"),
)
.widget(
Widget::chart("enrollments_per_week", "enrollments", "enrolled_at")
.label("Enrollments per week")
.per(Bucket::Week)
.last(12)
.span(2),
)
.widget(
Widget::recent("new_courses", "courses")
.label("New courses")
.columns(&["capacity"])
.sort("-created_at"),
),
)
The LMS example: learners, new enrollments, enrollments per week, new courses.
See Dashboard.
Theme, page, slot and cell
Theme. A blue primary color (lighter in dark mode), rounder corners, a logo and a favicon from resources/admin/:
.theme(
Theme::new()
.primary("#2563eb")
.primary_foreground("#ffffff")
.dark(|dark| dark.primary("#60a5fa").primary_foreground("#0b1220"))
.radius("0.625rem")
.logo(include_bytes!("../../resources/admin/logo.png"), "image/png")
.favicon(include_bytes!("../../resources/admin/favicon.png"), "image/png"),
)Course overview (/admin/p/course-overview, courses.view_any): the first 100 courses the user may list (one page; no paging), each with a meter of seats taken, rendered from resources/views/admin/course_overview.html. It reads courses through ctx.records, so the resource's scope and policy apply and instructors see theirs only:
pub struct CourseOverviewPage;
#[async_trait]
impl PanelPage for CourseOverviewPage {
const SLUG: &'static str = "course-overview";
fn meta() -> PanelPageMeta {
PanelPageMeta::new("Course overview").icon("layers").group("Learning").permission("courses.view_any")
}
fn view() -> PageView {
rustcms::admin::view!("course_overview.html")
}
/// The courses as the user may list them (instructors: theirs), with the
/// seats taken: counted for those courses only.
async fn data(ctx: &Ctx) -> AppResult<Value> {
let query = ListQuery { per_page: Some(100), ..Default::default() };
let courses = ctx.records("courses", &query).await?;
let mut out = Vec::new();
for course in courses.data {
let id = int(&course.data, "id").or_else(|| course.key.parse().ok()).unwrap_or_default();
out.push(json!({
"key": course.key,
"title": course.title,
"capacity": course.data.get("capacity"),
"published": course.data.get("published"),
"active": enrollment_service::active_count(&ctx.db, id).await?,
}));
}
Ok(json!({ "courses": out }))
}
}
The LMS example: the Course overview page, seats taken per course.
Seats beside a course: active and withdrawn enrollments and the average progress:
pub struct CourseSeatsSlot;
#[async_trait]
impl PanelSlot for CourseSeatsSlot {
const NAME: &'static str = "course-seats";
fn placement() -> Placement {
Placement::RecordAside("courses")
}
fn meta() -> SlotMeta {
SlotMeta::new().label("Seats").permission("courses.view")
}
fn view() -> PageView {
rustcms::admin::view!("course_seats.html")
}
/// The course is one the user may view (the panel checked): its counts are theirs to see.
async fn data(ctx: &Ctx, record: &Envelope) -> AppResult<Value> {
let id: i64 = record.key.parse().unwrap_or_default();
let rows = enrollment::Entity::find().filter(enrollment::Column::CourseId.eq(id)).all(&ctx.db).await?;
let active: Vec<&enrollment::Model> = rows.iter().filter(|e| e.status == enrollment::ACTIVE).collect();
let progress = if active.is_empty() {
0
} else {
active.iter().map(|e| i64::from(e.progress)).sum::<i64>() / active.len() as i64
};
Ok(json!({
"active": active.len(),
"withdrawn": rows.len() - active.len(),
"capacity": record.data.get("capacity"),
"progress": progress,
}))
}
}<dl class="rc-stack">
<div><dt class="rc-muted">{{ t("Active") }}</dt><dd>{{ data.active }} / {{ data.capacity }}</dd></div>
<div><dt class="rc-muted">{{ t("Withdrawn") }}</dt><dd>{{ data.withdrawn }}</dd></div>
<div><dt class="rc-muted">{{ t("Average progress") }}</dt><dd><meter class="rc-meter" min="0" max="100" value="{{ data.progress }}"></meter> {{ data.progress }}%</dd></div>
</dl>
The LMS example: a course's page with the Seats card beside it.
Progress cell. The enrollments table draws progress as a bar (a native meter styled by resources/admin/css/lms/progress.css):
fn table() -> Table {
Table::new()
.columns(vec![
TextColumn::make("course_id"),
TextColumn::make("learner_id"),
TextColumn::make("status"),
TextColumn::make("progress").cell("lms/progress"),
DateColumn::make("enrolled_at"),
])
.filters(vec![SelectFilter::make("course_id"), SelectFilter::make("status").options(STATUSES)])
.default_sort("-enrolled_at")
}window.rustcms.registerCell("lms/progress", {
apiVersion: 1,
mount(element, ctx) {
const meter = document.createElement("meter");
meter.className = "lms-progress";
meter.min = 0;
meter.max = 100;
const label = document.createElement("span");
label.className = "lms-progress-label";
element.append(meter, label);
const render = (current) => {
const value = Number(current.data) || 0;
meter.value = value;
label.textContent = `${value}%`;
meter.setAttribute("aria-label", `${current.t("Progress")} ${value}%`);
};
render(ctx);
return {
update: render,
unmount() {
element.replaceChildren();
},
};
},
});
window.rustcms.registerTranslations("vi", { Progress: "Tiến độ" });// The `lms/progress` cell of the enrollments table.
.extension_script("lms-progress", include_str!("../../resources/admin/js/lms/progress.js"))
.extension_style("lms-progress", include_str!("../../resources/admin/css/lms/progress.css"))
The LMS example: enrollments with the lms/progress cell.
See Theming and branding and Customizing the panel.
Mail and the welcome job
A new active enrollment queues lms.enrolled in its own transaction (the hook above, or enroll_in). The job carries ids only and reads the rows again when it runs, sends the welcome mail with the school name, then records a receipt for the course/learner pair, so a later run sends nothing while the receipt is kept (receipts are deleted after queue.failed_retention_days, 30 by default):
/// Ids only: the job reads the rows again when it runs.
#[derive(Debug, Serialize, Deserialize)]
pub struct SendWelcome {
pub course_id: i64,
pub learner_id: i64,
}
#[async_trait]
impl Job for SendWelcome {
const KIND: &'static str = "lms.enrolled";
fn max_attempts() -> u32 {
8
}
async fn handle(self, ctx: JobCtx) -> anyhow::Result<()> {
let db = ctx.state.db();
let (Some(course), Some(learner)) = (
course::Entity::find_by_id(self.course_id).one(db).await?,
learner::Entity::find_by_id(self.learner_id).one(db).await?,
) else {
// Removed since: nobody to welcome.
return Ok(());
};
let receipt = format!("welcome:{}:{}", course.id, learner.id);
if rustcms::models::job_receipt::Entity::find_by_id(receipt.clone()).one(db).await?.is_some() {
return Ok(());
}
let school = rustcms::settings::get::<LmsSettings>(&ctx.state).await?.school_name;
let data = json!({ "name": learner.name, "course": course.title, "school": school });
let locale = ctx.state.config().app.locale.clone();
let sent = async {
let rendered = mail::render(&ctx.state, "welcome", &locale, &data)?;
mail::send(&ctx.state, &Message::rendered([learner.email.clone()], rendered)).await
}
.await;
match sent {
Ok(()) => {}
Err(err) if err.is_permanent() => return Err(Failure::from(err).permanent().into()),
Err(err) => return Err(Failure::from(err).into()),
}
// A short transaction after the mail, never held across the send.
let txn = rustcms::db::begin_write(db).await?;
rustcms::queue::once(&txn, &receipt).await?;
txn.commit().await?;
Ok(())
}
}It is registered with its templates (resources/views/mail/{en,vi}/welcome.*):
// New enrollments queue a welcome mail.
app.job::<crate::jobs::send_welcome::SendWelcome>();
app.mail_template(rustcms::mail_template!("welcome", "en", html));
app.mail_template(rustcms::mail_template!("welcome", "vi", html));
// rustcms:jobsconfig/mail.toml uses driver = "log" with source = "config": locally nothing is sent and the log records each mail (recipients count, message id); add log_body = true (local only) to see the text. A receipt is recorded after the mail, so an interrupted run (after sending, before the receipt) can send it twice.
The administrator invites instructors from System → Users: they choose their password from the invitation mail (staff have no user management). With the log driver, the link is in the log only with log_body = true.
Settings
The lms group (school name, default capacity of seeded courses) is edited at /admin/settings/lms (School) by staff (settings.lms.view / .update). The Mail settings page is also registered (.mail_settings()), for administrators:
/// The school, and defaults for new courses.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LmsSettings {
/// Shown in welcomes.
pub school_name: String,
/// Capacity of the courses the course seeder creates.
pub default_capacity: i32,
}
impl Default for LmsSettings {
fn default() -> Self {
Self { school_name: "rustcms Academy".into(), default_capacity: 30 }
}
}
impl Settings for LmsSettings {
const GROUP: &'static str = "lms";
}async fn validate(ctx: &rustcms::admin::Ctx, settings: &Self) -> Result<(), rustcms::ValidationErrors> {
if !(1..=MAX_CAPACITY).contains(&i64::from(settings.default_capacity)) {
return Err(rustcms::ValidationErrors::field("default_capacity", ctx.t("must be between 1 and 10000")));
}
Ok(())
}See Settings.
Languages
config/app.toml offers English and Vietnamese (locales = ["en", "vi"]). lang/vi.toml translates labels, the service's messages (through ctx.t) and the unique-constraint messages; a test checks that cargo run -- lang:missing vi has nothing to report. See Languages.
API
src/routes/api.rs declares one public route; rustcms make:api <Model> adds controller routes there:
/// Every API route, with the access it requires.
pub fn routes() -> ApiRoutes {
ApiRoutes::new("/api/v1").get("/ping", Access::public(), ping)
// rustcms:api-routes
}See Routing.
Conflicts
A request that met another change to the same data answers 409 write_conflict with nothing saved; send it again. The panel offers to.
Tests
The feature tests use db_test!, so each runs on SQLite, and on PostgreSQL and MySQL when their URLs are set:
cargo test -p lms # SQLite only
RUSTCMS_TEST_PG=postgres://postgres:postgres@localhost:5432/postgres \
RUSTCMS_TEST_MYSQL=mysql://root:secret@localhost:3306/mysql \
cargo test -p lms # all three databasesA test signs in as a seeded account and checks the queued mail:
app.take_mails();
assert_eq!(rustcms::queue::run_until_idle(app.state(), None, 10).await.unwrap(), 1);
assert_eq!(jobs().await, 0, "done");
let mails = app.take_mails();
assert_eq!(mails.len(), 1);See Testing.
What it leaves out
Learner sign-in and quizzes are not part of the example yet.