forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB914d095Ahmet Kaan Gümüş2 months ago454 commits

modules.rs155 lines, 5.3 KiBHistoryRawDownload
1//! Module entitlements as data, on the school side of the line.
2//!
3//! Two reads, no writes — selling a module is the vendor's act and lives on
4//! `/schools/{slug}/modules` in [`crate::web::builder`]. What stands here is
5//! what a client needs to draw the product: the deployment's catalog (which
6//! modules exist, what each one needs, how they are packaged) and the caller's
7//! own switched-on set, so a frontend hides a nest the school never bought
8//! instead of discovering it as a `403`.
9//!
10//! Both routes are ungated on purpose: an entitlement lookup that a disabled
11//! module could switch off would be unusable exactly when it is needed. The
12//! catalog is unauthenticated for the same reason `GET /limits` is — it is a
13//! deploy-time constant, identical for every school.
14
15use axum::Json;
16use serde::Serialize;
17use utoipa::ToSchema;
18use utoipa_axum::router::OpenApiRouter;
19use utoipa_axum::routes;
20
21use crate::error::ErrorResponse;
22use crate::module::{Module, ModuleSet, Package};
23use crate::state::AppState;
24use crate::web::CurrentUser;
25use crate::web::tenant_state::ResolvedTenant;
26
27pub fn routes() -> OpenApiRouter<AppState> {
28 OpenApiRouter::new()
29 .routes(routes!(module_catalog))
30 .routes(routes!(my_modules))
31}
32
33/// One school's entitlements, both halves of the partition. `disabled` is
34/// carried rather than left to the client to subtract: the two lists together
35/// are the whole catalog, so a client can render the switchboard from one
36/// response.
37#[derive(Serialize, ToSchema)]
38pub struct ModulesResponse {
39 /// Switched on, sorted by name.
40 #[schema(example = json!(["courses", "meals", "notes"]))]
41 pub enabled: Vec<String>,
42 /// Every other module in the catalog, sorted by name.
43 #[schema(example = json!(["chatbot", "payments"]))]
44 pub disabled: Vec<String>,
45}
46
47impl ModulesResponse {
48 pub fn new(modules: &ModuleSet) -> Self {
49 let mut disabled: Vec<String> = Module::ALL
50 .into_iter()
51 .filter(|m| !modules.contains(*m))
52 .map(|m| m.as_str().to_string())
53 .collect();
54 disabled.sort();
55 Self {
56 enabled: modules.names(),
57 disabled,
58 }
59 }
60}
61
62/// What the caller's own school has, without the vendor's half of the picture.
63#[derive(Serialize, ToSchema)]
64struct EnabledResponse {
65 /// Switched on, sorted by name.
66 #[schema(example = json!(["courses", "meals", "notes"]))]
67 enabled: Vec<String>,
68}
69
70/// One sellable module: its name, the bundle it is sold in, and what it cannot
71/// work without.
72#[derive(Serialize, ToSchema)]
73struct CatalogModule {
74 #[schema(example = "exams")]
75 module: String,
76 #[schema(example = "academics")]
77 package: String,
78 /// Modules that must be enabled alongside this one. Structural, not
79 /// commercial: each edge is a stored reference into the other module's
80 /// data, so a set that breaks one is refused.
81 #[schema(example = json!(["courses", "subjects"]))]
82 requires: Vec<String>,
83}
84
85/// One commercial bundle and the modules it sells.
86#[derive(Serialize, ToSchema)]
87struct CatalogPackage {
88 #[schema(example = "academics")]
89 package: String,
90 #[schema(example = json!(["classes", "courses", "exams"]))]
91 modules: Vec<String>,
92}
93
94/// The whole catalog, identical for every school in the deployment.
95#[derive(Serialize, ToSchema)]
96struct CatalogResponse {
97 /// Every module, sorted by name.
98 modules: Vec<CatalogModule>,
99 /// Every package, in the order they are sold.
100 packages: Vec<CatalogPackage>,
101}
102
103fn names(modules: &[Module]) -> Vec<String> {
104 let mut names: Vec<String> = modules.iter().map(|m| m.as_str().to_string()).collect();
105 names.sort();
106 names
107}
108
109/// Every module this deployment can sell, what each one requires, and the
110/// packages they are bundled in. Unauthenticated and deploy-constant, like
111/// `GET /limits`: fetch once, cache for the session.
112#[utoipa::path(
113 get,
114 path = "/modules/catalog",
115 tag = "meta",
116 responses((status = 200, description = "The module catalog", body = CatalogResponse)),
117)]
118async fn module_catalog() -> Json<CatalogResponse> {
119 let mut modules: Vec<CatalogModule> = Module::ALL
120 .into_iter()
121 .map(|module| CatalogModule {
122 module: module.as_str().to_string(),
123 package: module.package().as_str().to_string(),
124 requires: names(module.requires()),
125 })
126 .collect();
127 modules.sort_by(|a, b| a.module.cmp(&b.module));
128 let packages = Package::ALL
129 .into_iter()
130 .map(|package| CatalogPackage {
131 package: package.as_str().to_string(),
132 modules: names(&package.modules()),
133 })
134 .collect();
135 Json(CatalogResponse { modules, packages })
136}
137
138/// What the caller's school has switched on. Any logged-in user may read it —
139/// it is what the client needs to draw its own navigation, not a privileged
140/// fact.
141#[utoipa::path(
142 get,
143 path = "/modules",
144 tag = "meta",
145 security(("session_cookie" = [])),
146 responses(
147 (status = 200, description = "The school's enabled modules", body = EnabledResponse),
148 (status = 401, description = "Not authenticated", body = ErrorResponse),
149 ),
150)]
151async fn my_modules(_user: CurrentUser, tenant: ResolvedTenant) -> Json<EnabledResponse> {
152 Json(EnabledResponse {
153 enabled: tenant.modules.names(),
154 })
155}