1use std::fmt;
5use std::sync::Arc;
6
7use renox::axum::Extension;
8use renox::axum::extract::Request;
9use renox::db::{DbValue, Model, Query, ToDbValue};
10use renox::grid::{Action, Grid, GridRequest, Selection};
11use renox::prelude::*;
12use renox::serde_json::{Map, Value};
13use renox::validation::Errors;
14
15use crate::AdminResource;
16use crate::field::plain_name;
17use crate::panel::{
18 Parent, ParentRecord, check, done, form_fields, money_fields, offers, parse_pairs, read_form,
19 record_title, rules_of, to_json,
20};
21use crate::resource::SaveContext;
22use crate::texts::{Texts, lower};
23
24const MAX_OPTIONS: u64 = 1_000;
26
27#[derive(Clone)]
29enum Kind {
30 HasMany { foreign_key: String },
32 Pivot {
34 table: String,
35 parent_key: String,
36 related_key: String,
37 },
38}
39
40struct Spec {
42 key: String,
43 label: String,
44 kind: Kind,
45 title: String,
46}
47
48trait Def: Send + Sync {
50 fn visible(&self, user: &AuthUser) -> bool;
51 fn routes(&self, spec: Arc<Spec>, parent: Arc<dyn Parent>) -> Routes;
52}
53
54struct Typed<C>(Arc<C>);
55
56impl<C: AdminResource> Def for Typed<C> {
57 fn visible(&self, user: &AuthUser) -> bool {
58 offers(&*self.0, "viewAny") && self.0.allows(user, "viewAny", None)
59 }
60
61 fn routes(&self, spec: Arc<Spec>, parent: Arc<dyn Parent>) -> Routes {
62 routes(RelCtx {
63 parent,
64 child: self.0.clone(),
65 spec,
66 })
67 }
68}
69
70#[derive(Clone)]
124pub struct RelationManager {
125 spec: Arc<Spec>,
126 def: Arc<dyn Def>,
127}
128
129impl fmt::Debug for RelationManager {
130 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
131 f.debug_struct("RelationManager")
132 .field("key", &self.spec.key)
133 .field("label", &self.spec.label)
134 .finish_non_exhaustive()
135 }
136}
137
138impl RelationManager {
139 pub fn has_many<C: AdminResource>(key: &str, label: &str, child: C, foreign_key: &str) -> Self {
147 assert!(
148 plain_name(foreign_key),
149 "RelationManager::has_many: `{foreign_key}` may only have letters, digits and `_`"
150 );
151 Self::build(
152 key,
153 label,
154 child,
155 Kind::HasMany {
156 foreign_key: foreign_key.to_owned(),
157 },
158 )
159 }
160
161 pub fn belongs_to_many<C: AdminResource>(
170 key: &str,
171 label: &str,
172 related: C,
173 pivot_table: &str,
174 parent_key: &str,
175 related_key: &str,
176 ) -> Self {
177 for name in [pivot_table, parent_key, related_key] {
178 assert!(
179 plain_name(name),
180 "RelationManager::belongs_to_many: `{name}` may only have letters, digits and `_`"
181 );
182 }
183 Self::build(
184 key,
185 label,
186 related,
187 Kind::Pivot {
188 table: pivot_table.to_owned(),
189 parent_key: parent_key.to_owned(),
190 related_key: related_key.to_owned(),
191 },
192 )
193 }
194
195 fn build<C: AdminResource>(key: &str, label: &str, resource: C, kind: Kind) -> Self {
196 assert!(
197 !key.is_empty()
198 && key.len() <= 64
199 && key
200 .chars()
201 .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-'),
202 "RelationManager: the key `{key}` may only have letters, digits, `_` and `-`"
203 );
204 Self {
205 spec: Arc::new(Spec {
206 key: key.to_owned(),
207 label: label.to_owned(),
208 kind,
209 title: "name".into(),
210 }),
211 def: Arc::new(Typed(Arc::new(resource))),
212 }
213 }
214
215 pub fn title_column(mut self, column: &str) -> Self {
223 assert!(
224 plain_name(column),
225 "RelationManager::title_column: `{column}` may only have letters, digits and `_`"
226 );
227 let spec = Spec {
228 key: self.spec.key.clone(),
229 label: self.spec.label.clone(),
230 kind: self.spec.kind.clone(),
231 title: column.to_owned(),
232 };
233 self.spec = Arc::new(spec);
234 self
235 }
236
237 pub(crate) fn key(&self) -> &str {
238 &self.spec.key
239 }
240
241 pub(crate) fn label(&self) -> &str {
242 &self.spec.label
243 }
244
245 pub(crate) fn visible(&self, user: &AuthUser) -> bool {
246 self.def.visible(user)
247 }
248
249 pub(crate) fn routes(&self, parent: Arc<dyn Parent>) -> Routes {
250 self.def.routes(self.spec.clone(), parent)
251 }
252}
253
254struct RelCtx<C> {
256 parent: Arc<dyn Parent>,
257 child: Arc<C>,
258 spec: Arc<Spec>,
259}
260
261impl<C> Clone for RelCtx<C> {
262 fn clone(&self) -> Self {
263 Self {
264 parent: self.parent.clone(),
265 child: self.child.clone(),
266 spec: self.spec.clone(),
267 }
268 }
269}
270
271fn routes<C: AdminResource>(cx: RelCtx<C>) -> Routes {
272 let name = format!("{}.{}", cx.parent.slug(), cx.spec.key);
273 let at = format!("/{}/{{id}}/relations/{}", cx.parent.slug(), cx.spec.key);
274 let one = format!("{at}/{{rid}}");
275 let mut routes = Routes::new()
276 .get(&at, index::<C>)
277 .name(&format!("{name}.index"));
278 match cx.spec.kind {
279 Kind::HasMany { .. } => {
280 routes = routes
281 .post(&at, store::<C>)
282 .name(&format!("{name}.store"))
283 .get(&format!("{at}/create"), create::<C>)
284 .name(&format!("{name}.create"))
285 .get(&format!("{one}/edit"), edit::<C>)
286 .name(&format!("{name}.edit"))
287 .put(&one, update::<C>)
288 .name(&format!("{name}.update"))
289 .delete(&one, remove::<C>)
290 .name(&format!("{name}.destroy"));
291 }
292 Kind::Pivot { .. } => {
293 routes = routes
294 .post(&at, attach::<C>)
295 .name(&format!("{name}.attach"))
296 .delete(&one, remove::<C>)
297 .name(&format!("{name}.detach"));
298 }
299 }
300 routes
301 .post(&format!("{at}/actions/remove"), bulk_remove::<C>)
302 .name(&format!("{name}.bulk"))
303 .route_layer(Extension(cx))
304 .require_auth()
305}
306
307impl<C: AdminResource> RelCtx<C> {
308 fn url(&self, id: &str) -> String {
310 format!("{}/{id}/relations/{}", self.parent.base(), self.spec.key)
311 }
312
313 fn allows(&self, user: &AuthUser, ability: &str, record: Option<&C::Model>) -> bool {
314 offers(&*self.child, ability) && self.child.allows(user, ability, record)
315 }
316
317 fn authorize(&self, user: &AuthUser, ability: &str, record: Option<&C::Model>) -> Result {
319 if !offers(&*self.child, ability) {
320 return Err(Error::NotFound);
321 }
322 if self.child.allows(user, ability, record) {
323 Ok(())
324 } else {
325 Err(Error::Forbidden)
326 }
327 }
328
329 fn pivot_write(&self, parent: &ParentRecord) -> Result {
331 if parent.can_update {
332 Ok(())
333 } else {
334 Err(Error::Forbidden)
335 }
336 }
337
338 fn is_pivot(&self) -> bool {
339 matches!(self.spec.kind, Kind::Pivot { .. })
340 }
341
342 fn fixed(&self, parent: &ParentRecord) -> Vec<(String, String)> {
344 match &self.spec.kind {
345 Kind::HasMany { foreign_key } => vec![(foreign_key.clone(), parent.id.clone())],
346 Kind::Pivot { .. } => Vec::new(),
347 }
348 }
349
350 fn scoped(&self, parent: &ParentRecord) -> Query<C::Model> {
352 let query = self.child.query();
353 match &self.spec.kind {
354 Kind::HasMany { foreign_key } => query.where_eq(foreign_key, parent.key.clone()),
355 Kind::Pivot {
356 table,
357 parent_key,
358 related_key,
359 } => query.where_raw(
360 &format!(
361 "\"{}\".\"id\" IN (SELECT \"{related_key}\" FROM \"{table}\" WHERE \"{parent_key}\" = ?)",
362 C::Model::TABLE
363 ),
364 [parent.key.clone()],
365 ),
366 }
367 }
368
369 async fn find(&self, db: &Db, parent: &ParentRecord, rid: &str) -> Result<C::Model> {
371 let key: <C::Model as Model>::Key = rid.parse().map_err(|_| Error::NotFound)?;
372 self.scoped(parent)
373 .where_eq("id", key)
374 .first(db)
375 .await?
376 .ok_or(Error::NotFound)
377 }
378
379 fn grid(&self, parent: &ParentRecord, user: &AuthUser, texts: &Texts) -> Grid {
380 let slug = self.child.slug();
381 let url = self.url(&parent.id);
382 let label = lower(&texts.label(slug, self.child.label()));
383 let plural = lower(&texts.label(slug, self.child.plural_label()));
384 let mut grid = Grid::new(&format!("{}-{}", self.parent.slug(), self.spec.key))
385 .title(&texts.label(self.parent.slug(), &self.spec.label))
386 .sort_by("-id")
387 .empty_state(&texts.get("relation_empty", &[("plural", &plural)]), None);
388 for column in self.child.columns() {
389 let heading = texts.label(slug, column.label());
390 grid = grid.column(column.titled(&heading));
391 }
392 if self.is_pivot() {
393 if parent.can_update {
394 grid = grid
395 .bulk_action(
396 Action::new(&texts.get("detach", &[]), &format!("{url}/actions/remove"))
397 .confirm(&texts.get("detach_question", &[("label", &label)]))
398 .danger(),
399 )
400 .row_action(
401 Action::new(&texts.get("detach", &[]), &format!("{url}/{{id}}"))
402 .method("DELETE")
403 .confirm(&texts.get("detach_question", &[("label", &label)]))
404 .danger(),
405 );
406 }
407 return grid;
408 }
409 if self.allows(user, "deleteAny", None) {
410 grid = grid.bulk_action(
411 Action::new(&texts.get("delete", &[]), &format!("{url}/actions/remove"))
412 .confirm(&texts.get("bulk_delete_hard", &[("plural", &plural)]))
413 .danger(),
414 );
415 }
416 if self.allows(user, "update", None) {
417 grid = grid
418 .row_url(&format!("{url}/{{id}}/edit"))
419 .row_action(Action::link(
420 &texts.get("edit", &[]),
421 &format!("{url}/{{id}}/edit"),
422 ));
423 }
424 if self.allows(user, "delete", None) {
425 grid = grid.row_action(
426 Action::new(&texts.get("delete", &[]), &format!("{url}/{{id}}"))
427 .method("DELETE")
428 .confirm(&texts.get("delete_question", &[("label", &label)]))
429 .danger(),
430 );
431 }
432 grid
433 }
434
435 fn page(
438 &self,
439 state: &AppState,
440 user: &AuthUser,
441 parent: &ParentRecord,
442 texts: &Texts,
443 name: &str,
444 mut values: Map<String, Value>,
445 ) -> Result<View> {
446 let slug = self.child.slug();
447 let url = self.url(&parent.id);
448 values.insert(
449 "admin".into(),
450 to_json(
451 &self
452 .parent
453 .panel()
454 .frame(state, user, Some(self.parent.slug()), texts),
455 )?,
456 );
457 values.insert(
458 "resource".into(),
459 json!({
460 "slug": slug,
461 "label": texts.label(slug, self.child.label()),
462 "plural_label": texts.label(slug, self.child.plural_label()),
463 "index_url": url,
464 "create_url": format!("{url}/create"),
465 "has_view": false,
466 }),
467 );
468 Ok(view(name, Value::Object(values)))
469 }
470}
471
472async fn open<C: AdminResource>(
473 cx: &RelCtx<C>,
474 state: &AppState,
475 user: &AuthUser,
476 id: &str,
477 texts: &Texts,
478) -> Result<ParentRecord> {
479 cx.parent.open(state, user, id, texts).await
480}
481
482async fn index<C: AdminResource>(
483 Extension(cx): Extension<RelCtx<C>>,
484 State(state): State<AppState>,
485 user: AuthUser,
486 Path(id): Path<String>,
487 request: GridRequest,
488) -> Result<View> {
489 let texts = Texts::new(&state);
490 let parent = open(&cx, &state, &user, &id, &texts).await?;
491 cx.authorize(&user, "viewAny", None)?;
492 let grid = cx.grid(&parent, &user, &texts);
493 let rows = grid.page(cx.scoped(&parent), &request).await?;
494 let slug = cx.child.slug();
495 let url = cx.url(&parent.id);
496 let label = texts.label(slug, cx.child.label());
497 let tabs = cx.parent.tabs(&user, &texts, &parent.id);
498 let mut values = Map::new();
499 values.insert("rows".into(), to_json(&rows)?);
500 values.insert("tabs".into(), to_json(&tabs)?);
501 values.insert("current_tab".into(), Value::String(url.clone()));
502 let (parent_label, parent_plural) = cx.parent.names(&texts);
503 values.insert(
504 "parent".into(),
505 json!({
506 "title": parent.title,
507 "index_url": cx.parent.base(),
508 "plural_label": parent_plural,
509 "label": parent_label,
510 }),
511 );
512 values.insert(
513 "relation".into(),
514 json!({
515 "label": texts.label(cx.parent.slug(), &cx.spec.label),
516 "url": url,
517 "child_slug": slug,
518 }),
519 );
520 if cx.is_pivot() {
521 if parent.can_update && cx.allows(&user, "viewAny", None) {
522 let options = attach_options(&cx, &state, &parent).await?;
523 values.insert(
524 "attach".into(),
525 json!({
526 "label": texts.get("attach", &[("label", &lower(&label))]),
527 "none": texts.get("attach_none", &[]),
528 "field": label,
529 "options": options,
530 }),
531 );
532 }
533 } else if cx.allows(&user, "create", None) {
534 values.insert(
535 "new".into(),
536 json!({
537 "label": texts.get("new", &[("label", &lower(&label))]),
538 "url": format!("{url}/create"),
539 }),
540 );
541 }
542 cx.page(
543 &state,
544 &user,
545 &parent,
546 &texts,
547 "renox-admin/relation.html",
548 values,
549 )
550}
551
552async fn attach_options<C: AdminResource>(
554 cx: &RelCtx<C>,
555 state: &AppState,
556 parent: &ParentRecord,
557) -> Result<Vec<(String, String)>> {
558 let Kind::Pivot {
559 table,
560 parent_key,
561 related_key,
562 } = &cx.spec.kind
563 else {
564 return Ok(Vec::new());
565 };
566 let rows = cx
567 .child
568 .query()
569 .where_raw(
570 &format!(
571 "\"{}\".\"id\" NOT IN (SELECT \"{related_key}\" FROM \"{table}\" WHERE \"{parent_key}\" = ?)",
572 C::Model::TABLE
573 ),
574 [parent.key.clone()],
575 )
576 .limit(MAX_OPTIONS)
577 .get(&state.db)
578 .await?;
579 let mut options = Vec::with_capacity(rows.len());
580 for row in &rows {
581 let json = to_json(row)?;
582 let title = match json.get(&cx.spec.title) {
583 Some(Value::String(text)) => text.clone(),
584 Some(Value::Null) | None => row.id().to_string(),
585 Some(other) => other.to_string(),
586 };
587 options.push((row.id().to_string(), title));
588 }
589 options.sort_by_key(|option| option.1.to_lowercase());
590 Ok(options)
591}
592
593async fn create<C: AdminResource>(
594 Extension(cx): Extension<RelCtx<C>>,
595 State(state): State<AppState>,
596 user: AuthUser,
597 Path(id): Path<String>,
598) -> Result<View> {
599 let texts = Texts::new(&state);
600 let parent = open(&cx, &state, &user, &id, &texts).await?;
601 cx.authorize(&user, "create", None)?;
602 let hidden = hidden_names(&cx);
603 let fields = form_fields(&*cx.child, &state, None, &texts, &hidden).await?;
604 let label = lower(&texts.label(cx.child.slug(), cx.child.label()));
605 let mut values = Map::new();
606 values.insert(
607 "title".into(),
608 Value::String(texts.get("new", &[("label", &label)])),
609 );
610 values.insert("fields".into(), to_json(&fields)?);
611 values.insert("action".into(), Value::String(cx.url(&parent.id)));
612 values.insert("method".into(), Value::String("POST".into()));
613 values.insert(
614 "submit_label".into(),
615 Value::String(texts.get("create", &[("label", &label)])),
616 );
617 values.insert("record".into(), Value::Null);
618 cx.page(
619 &state,
620 &user,
621 &parent,
622 &texts,
623 "renox-admin/form.html",
624 values,
625 )
626}
627
628fn hidden_names<C>(cx: &RelCtx<C>) -> Vec<&str> {
630 match &cx.spec.kind {
631 Kind::HasMany { foreign_key } => vec![foreign_key.as_str()],
632 Kind::Pivot { .. } => Vec::new(),
633 }
634}
635
636async fn store<C: AdminResource>(
637 Extension(cx): Extension<RelCtx<C>>,
638 State(state): State<AppState>,
639 user: AuthUser,
640 htmx: Htmx,
641 Path(id): Path<String>,
642 req: Request,
643) -> Result<Response> {
644 let texts = Texts::new(&state);
645 let parent = open(&cx, &state, &user, &id, &texts).await?;
646 cx.authorize(&user, "create", None)?;
647 let form: C::Form =
648 match read_form(&state, req, &money_fields(&*cx.child), &cx.fixed(&parent)).await {
649 Ok(form) => form,
650 Err(answer) => return Ok(*answer),
651 };
652 check(&state.db, rules_of(&*cx.child, &form, None)).await?;
653 let mut record = C::Model::default();
654 cx.child.fill(&mut record, form);
655 record.save(&state.db).await?;
656 let saved = SaveContext {
657 state: state.clone(),
658 user: user.clone(),
659 created: true,
660 previous: None,
661 };
662 cx.child.saved(&record, &saved).await?;
663 let label = texts.label(cx.child.slug(), cx.child.label());
664 let toast = Toast::success(texts.get("created", &[("label", &label)]));
665 Ok(done(&htmx, toast, &cx.url(&parent.id)))
666}
667
668async fn edit<C: AdminResource>(
669 Extension(cx): Extension<RelCtx<C>>,
670 State(state): State<AppState>,
671 user: AuthUser,
672 Path((id, rid)): Path<(String, String)>,
673) -> Result<View> {
674 let texts = Texts::new(&state);
675 let parent = open(&cx, &state, &user, &id, &texts).await?;
676 let record = cx.find(&state.db, &parent, &rid).await?;
677 cx.authorize(&user, "update", Some(&record))?;
678 let json = to_json(&record)?;
679 let hidden = hidden_names(&cx);
680 let fields = form_fields(&*cx.child, &state, Some(&json), &texts, &hidden).await?;
681 let url = cx.url(&parent.id);
682 let rid = record.id().to_string();
683 let label = texts.label(cx.child.slug(), cx.child.label());
684 let title = record_title(&*cx.child, &record, &texts);
685 let mut values = Map::new();
686 values.insert(
687 "title".into(),
688 Value::String(texts.get("edit_title", &[("title", &title)])),
689 );
690 values.insert("fields".into(), to_json(&fields)?);
691 values.insert("action".into(), Value::String(format!("{url}/{rid}")));
692 values.insert("method".into(), Value::String("PUT".into()));
693 values.insert(
694 "submit_label".into(),
695 Value::String(texts.get("save_changes", &[])),
696 );
697 values.insert("record".into(), json);
698 if cx.allows(&user, "delete", Some(&record)) {
699 values.insert(
700 "delete".into(),
701 json!({ "url": format!("{url}/{rid}"), "label": label, "soft": false }),
702 );
703 }
704 cx.page(
705 &state,
706 &user,
707 &parent,
708 &texts,
709 "renox-admin/form.html",
710 values,
711 )
712}
713
714async fn update<C: AdminResource>(
715 Extension(cx): Extension<RelCtx<C>>,
716 State(state): State<AppState>,
717 user: AuthUser,
718 htmx: Htmx,
719 Path((id, rid)): Path<(String, String)>,
720 req: Request,
721) -> Result<Response> {
722 let texts = Texts::new(&state);
723 let parent = open(&cx, &state, &user, &id, &texts).await?;
724 let mut record = cx.find(&state.db, &parent, &rid).await?;
725 cx.authorize(&user, "update", Some(&record))?;
726 let form: C::Form =
727 match read_form(&state, req, &money_fields(&*cx.child), &cx.fixed(&parent)).await {
728 Ok(form) => form,
729 Err(answer) => return Ok(*answer),
730 };
731 check(&state.db, rules_of(&*cx.child, &form, Some(&record))).await?;
732 let previous = to_json(&record)?;
733 cx.child.fill(&mut record, form);
734 record.save(&state.db).await?;
735 let saved = SaveContext {
736 state: state.clone(),
737 user: user.clone(),
738 created: false,
739 previous: Some(previous),
740 };
741 cx.child.saved(&record, &saved).await?;
742 let label = texts.label(cx.child.slug(), cx.child.label());
743 let toast = Toast::success(texts.get("saved", &[("label", &label)]));
744 Ok(done(&htmx, toast, &cx.url(&parent.id)))
745}
746
747async fn remove<C: AdminResource>(
749 Extension(cx): Extension<RelCtx<C>>,
750 State(state): State<AppState>,
751 user: AuthUser,
752 htmx: Htmx,
753 Path((id, rid)): Path<(String, String)>,
754) -> Result<Response> {
755 let texts = Texts::new(&state);
756 let parent = open(&cx, &state, &user, &id, &texts).await?;
757 let mut record = cx.find(&state.db, &parent, &rid).await?;
758 let label = texts.label(cx.child.slug(), cx.child.label());
759 let toast = if cx.is_pivot() {
760 cx.pivot_write(&parent)?;
761 detach(&cx, &state, &parent, &[record.id().to_db_value()]).await?;
762 Toast::success(texts.get("detached", &[("label", &label)]))
763 } else {
764 cx.authorize(&user, "delete", Some(&record))?;
765 record.delete(&state.db).await?;
766 Toast::success(texts.get("deleted", &[("label", &label)]))
767 };
768 if htmx.request {
769 Ok(toast.into_response())
770 } else {
771 Ok(done(&htmx, toast, &cx.url(&parent.id)))
772 }
773}
774
775async fn detach<C: AdminResource>(
777 cx: &RelCtx<C>,
778 state: &AppState,
779 parent: &ParentRecord,
780 related: &[DbValue],
781) -> Result {
782 let Kind::Pivot {
783 table,
784 parent_key,
785 related_key,
786 } = &cx.spec.kind
787 else {
788 return Ok(());
789 };
790 let mut tx = state.db.begin().await?;
791 for value in related {
792 renox::db::sql(format!(
793 "DELETE FROM \"{table}\" WHERE \"{parent_key}\" = ? AND \"{related_key}\" = ?"
794 ))
795 .bind(parent.key.clone())
796 .bind(value.clone())
797 .execute(&mut tx)
798 .await?;
799 }
800 tx.commit().await?;
801 Ok(())
802}
803
804async fn attach<C: AdminResource>(
805 Extension(cx): Extension<RelCtx<C>>,
806 State(state): State<AppState>,
807 user: AuthUser,
808 htmx: Htmx,
809 Path(id): Path<String>,
810 body: renox::axum::body::Bytes,
811) -> Result<Response> {
812 let texts = Texts::new(&state);
813 let parent = open(&cx, &state, &user, &id, &texts).await?;
814 cx.pivot_write(&parent)?;
815 cx.authorize(&user, "viewAny", None)?;
816 let Kind::Pivot {
817 table,
818 parent_key,
819 related_key,
820 } = &cx.spec.kind
821 else {
822 return Err(Error::NotFound);
823 };
824 let label = texts.label(cx.child.slug(), cx.child.label());
825 let chosen = parse_pairs(&body)
826 .into_iter()
827 .rev()
828 .find(|(name, _)| name == "attach")
829 .map(|(_, value)| value)
830 .unwrap_or_default();
831 let mut errors = Errors::new();
832 let key = chosen.parse::<<C::Model as Model>::Key>().ok();
834 let row = match key {
835 Some(key) if !chosen.is_empty() => {
836 cx.child
837 .query()
838 .where_eq("id", key)
839 .first(&state.db)
840 .await?
841 }
842 _ => None,
843 };
844 let Some(row) = row else {
845 errors.add("attach", texts.get("choice", &[("field", &label)]));
846 return Err(ValidationError::new(errors).into());
847 };
848 let related = row.id().to_db_value();
849 let already = renox::db::sql(format!(
850 "SELECT COUNT(*) FROM \"{table}\" WHERE \"{parent_key}\" = ? AND \"{related_key}\" = ?"
851 ))
852 .bind(parent.key.clone())
853 .bind(related.clone())
854 .scalar::<i64>(&state.db)
855 .await?;
856 if already == 0 {
857 renox::db::sql(format!(
858 "INSERT INTO \"{table}\" (\"{parent_key}\", \"{related_key}\") VALUES (?, ?)"
859 ))
860 .bind(parent.key.clone())
861 .bind(related)
862 .execute(&state.db)
863 .await?;
864 }
865 let toast = Toast::success(texts.get("attached", &[("label", &label)]));
866 if htmx.request {
867 Ok((toast, HxRefresh).into_response())
868 } else {
869 Ok(done(&htmx, toast, &cx.url(&parent.id)))
870 }
871}
872
873async fn bulk_remove<C: AdminResource>(
875 Extension(cx): Extension<RelCtx<C>>,
876 State(state): State<AppState>,
877 user: AuthUser,
878 Path(id): Path<String>,
879 request: GridRequest,
880 body: renox::axum::body::Bytes,
881) -> Result<Toast> {
882 let texts = Texts::new(&state);
883 let parent = open(&cx, &state, &user, &id, &texts).await?;
884 if cx.is_pivot() {
885 cx.pivot_write(&parent)?;
886 } else {
887 cx.authorize(&user, "deleteAny", None)?;
888 }
889 let mut selection = Selection::default();
890 for (name, value) in parse_pairs(&body) {
891 match name.as_str() {
892 "ids" => {
893 selection.ids = value
894 .split(',')
895 .filter(|id| !id.is_empty())
896 .map(str::to_owned)
897 .collect();
898 }
899 "all" => selection.all = value == "true",
900 _ => {}
901 }
902 }
903 let grid = cx.grid(&parent, &user, &texts);
904 let mut records = grid
905 .selected(cx.scoped(&parent), &request, &selection)?
906 .limit(10_000)
907 .get(&state.db)
908 .await?;
909 if records.is_empty() {
910 return Ok(Toast::info(texts.get("nothing_selected", &[])));
911 }
912 let count = records.len();
913 let slug = cx.child.slug();
914 let what = if count == 1 {
915 format!("1 {}", lower(&texts.label(slug, cx.child.label())))
916 } else {
917 format!(
918 "{count} {}",
919 lower(&texts.label(slug, cx.child.plural_label()))
920 )
921 };
922 if cx.is_pivot() {
923 let related: Vec<DbValue> = records.iter().map(|r| r.id().to_db_value()).collect();
924 detach(&cx, &state, &parent, &related).await?;
925 return Ok(Toast::success(texts.get("n_detached", &[("what", &what)])));
926 }
927 if records
928 .iter()
929 .any(|record| !cx.child.allows(&user, "delete", Some(record)))
930 {
931 return Err(Error::Forbidden);
932 }
933 let mut tx = state.db.begin().await?;
934 for record in &mut records {
935 record.delete(&mut tx).await?;
936 }
937 tx.commit().await?;
938 Ok(Toast::success(texts.get("n_deleted", &[("what", &what)])))
939}