Skip to main content

rustango_cms/admin/
cms_admin.rs

1//! A generic admin editor for a host app's own models.
2//!
3//! `#[derive(CmsAdmin)]` on a `#[derive(Model)]` type implements
4//! [`CmsAdmin`] from the struct's `#[cms_admin(...)]` and `#[field(...)]`
5//! attributes and registers a [`CmsAdminPage`] for it. The page lives
6//! at `/cms-admin/x/<slug>` inside the admin chrome and gives editors:
7//!
8//! - a list with search, the chosen columns and pagination;
9//! - add and edit forms built from the `#[field]` widgets (every widget
10//!   the page editor has, media and page choosers included);
11//! - delete, with a confirmation.
12//!
13//! Access runs through the role matrix: the model gets a row with view,
14//! add, edit and delete columns (`<resource>.view` … `.delete`), and the
15//! dispatcher checks the matching codename on every request.
16//!
17//! [`CmsAdminOverrides`] holds the hooks a real app needs: fields that
18//! cannot be edited, records that cannot be created or deleted,
19//! validation, side effects after a save or before a delete, options for
20//! a select, and extra widgets for relations the struct has no column
21//! for (a many-to-many list).
22
23use std::collections::HashMap;
24use std::marker::PhantomData;
25
26use async_trait::async_trait;
27use axum::http::StatusCode;
28use axum::response::{IntoResponse, Response};
29use rustango::sql::{ExecError, Pool};
30use serde_json::{json, Value};
31
32use super::admin_page::{AdminForm, AdminPageCtx, AdminPageHandler, MessageLevel, SidebarSection};
33use crate::permissions::Action;
34use crate::widget::{Widget, WidgetKind};
35
36/// Static description of one model's editor, built by the derive.
37#[derive(Debug, Clone, Copy)]
38pub struct CmsAdminMeta {
39    /// URL slug: the page is `/cms-admin/x/<slug>`.
40    pub slug: &'static str,
41    /// Plural label, for the sidebar and the list heading.
42    pub label: &'static str,
43    /// Singular label, for "Add …" and "Edit …".
44    pub singular: &'static str,
45    /// Material Symbols icon name for the sidebar.
46    pub icon: Option<&'static str>,
47    /// Sidebar section.
48    pub section: SidebarSection,
49    /// Order within the section.
50    pub sort_order: i32,
51    /// List columns as `(field, header)`. The first links to the form.
52    pub list: &'static [(&'static str, &'static str)],
53    /// Whether the list shows a search box.
54    pub searchable: bool,
55    /// Rows per list page.
56    pub per_page: i64,
57    /// Codename prefix in the role matrix.
58    pub permission_resource: &'static str,
59}
60
61/// A validation failure for one field, or for the whole form when
62/// `field` is `"_form"`.
63#[derive(Debug, Clone, PartialEq, Eq)]
64pub struct FieldError {
65    pub field: String,
66    pub message: String,
67}
68
69impl FieldError {
70    /// An error attached to `field`.
71    #[must_use]
72    pub fn new(field: impl Into<String>, message: impl Into<String>) -> Self {
73        Self { field: field.into(), message: message.into() }
74    }
75}
76
77/// What `#[derive(CmsAdmin)]` implements. Host code rarely calls these
78/// directly; [`CmsAdminPage`] does.
79#[async_trait]
80pub trait CmsAdmin: CmsAdminOverrides + Sized + Send + Sync + 'static {
81    /// The editor's static description.
82    fn admin_meta() -> &'static CmsAdminMeta;
83    /// A blank record for the add form (`Default::default()`).
84    fn admin_new() -> Self;
85    /// The primary key, once saved.
86    fn admin_id(&self) -> Option<i64>;
87    /// How a record names itself in headings and messages.
88    fn admin_title(&self) -> String;
89    /// The text for list column `field`.
90    fn admin_cell(&self, field: &str) -> String;
91    /// One widget per `#[field]`, filled from `self`.
92    fn admin_widgets(&self) -> Vec<Widget>;
93    /// Copy the posted values into `self`, leaving the fields in `skip`
94    /// alone. Returns a message for each value that does not parse and
95    /// each required field left empty.
96    fn admin_apply(&mut self, form: &AdminForm, skip: &[&str]) -> Vec<FieldError>;
97    /// One page of records matching `search`, and the total match count.
98    async fn admin_list(pool: &Pool, search: &str, limit: i64, offset: i64) -> Result<(Vec<Self>, i64), ExecError>;
99    /// The record with primary key `id`.
100    async fn admin_get(pool: &Pool, id: i64) -> Result<Option<Self>, ExecError>;
101    /// Insert or update.
102    async fn admin_save(&mut self, pool: &Pool) -> Result<(), ExecError>;
103    /// Delete.
104    async fn admin_delete(self, pool: &Pool) -> Result<(), ExecError>;
105}
106
107/// Hooks for a model's editor. Every method has a default, so
108/// `impl CmsAdminOverrides for MyModel {}` is enough to start.
109#[async_trait]
110pub trait CmsAdminOverrides: Send + Sync {
111    /// Fields shown but not editable on `self`. For a new record `self`
112    /// is the blank row.
113    async fn read_only_fields(&self, _pool: &Pool) -> Vec<&'static str> {
114        Vec::new()
115    }
116
117    /// Whether editors may add records. `false` hides "Add" and refuses
118    /// the form.
119    async fn can_create(_pool: &Pool) -> bool
120    where
121        Self: Sized,
122    {
123        true
124    }
125
126    /// Whether editors may delete `self`.
127    async fn can_delete(&self, _pool: &Pool) -> bool {
128        true
129    }
130
131    /// Checks beyond "does each value parse", run before saving.
132    /// Return one [`FieldError`] per problem; any error stops the save
133    /// and re-shows the form.
134    async fn validate(&self, _pool: &Pool) -> Vec<FieldError> {
135        Vec::new()
136    }
137
138    /// Options for a `Select`, `Radio`, `Checkboxes` or `MultiSelect`
139    /// field, as `(value, label)`, replacing any declared in
140    /// `#[field(options(...))]`. Use it for a foreign key:
141    /// list the target table's rows. `None` keeps the declared options.
142    async fn field_options(_pool: &Pool, _field: &str) -> Option<Vec<(String, String)>>
143    where
144        Self: Sized,
145    {
146        None
147    }
148
149    /// Widgets for data that is not a column of this struct, such as a
150    /// many-to-many relation. They render after the `#[field]` widgets;
151    /// [`Self::save_extra`] stores what they post.
152    async fn extra_widgets(&self, _pool: &Pool) -> Vec<Widget> {
153        Vec::new()
154    }
155
156    /// Store the values [`Self::extra_widgets`] posted. Runs after the
157    /// record is saved, so `self` has its primary key.
158    async fn save_extra(&self, _pool: &Pool, _form: &AdminForm) -> Result<(), ExecError> {
159        Ok(())
160    }
161
162    /// Runs after every successful save; `created` is true for an add.
163    async fn after_save(&self, _pool: &Pool, _created: bool) -> Result<(), ExecError> {
164        Ok(())
165    }
166
167    /// Runs before the delete; an error cancels it. Remove dependent
168    /// rows here.
169    async fn before_delete(&self, _pool: &Pool) -> Result<(), ExecError> {
170        Ok(())
171    }
172
173    /// The cells of list column `column` for `rows`, one per row in
174    /// order, overriding the field's own value. Lets a column show
175    /// something computed, such as a count from another table (one query
176    /// for the page, not one per row), or name a column that is not a
177    /// field at all. `None` keeps the default.
178    async fn list_column(_pool: &Pool, _rows: &[Self], _column: &str) -> Option<Vec<String>>
179    where
180        Self: Sized,
181    {
182        None
183    }
184}
185
186/// Parse a `section` attribute value: `content`, `site` and `settings`
187/// are the built-in sections; anything else names a new one.
188#[must_use]
189pub const fn section_from(name: &'static str) -> SidebarSection {
190    match name.as_bytes() {
191        b"content" | b"Content" => SidebarSection::Content,
192        b"site" | b"Site" => SidebarSection::Site,
193        b"settings" | b"Settings" => SidebarSection::Settings,
194        _ => SidebarSection::Custom(name),
195    }
196}
197
198/// The admin page serving model `T`. `#[derive(CmsAdmin)]` registers it;
199/// register it by hand with `register_admin_page!(CmsAdminPage<T>)` only
200/// when implementing [`CmsAdmin`] yourself.
201pub struct CmsAdminPage<T>(PhantomData<fn() -> T>);
202
203impl<T> Default for CmsAdminPage<T> {
204    fn default() -> Self {
205        Self(PhantomData)
206    }
207}
208
209const CRUD: &[Action] = &[Action::View, Action::Add, Action::Edit, Action::Delete];
210
211fn not_found() -> Response {
212    StatusCode::NOT_FOUND.into_response()
213}
214
215fn forbidden() -> Response {
216    StatusCode::FORBIDDEN.into_response()
217}
218
219/// The form's widgets. `posted` is the rejected submission being shown
220/// again: extra widgets read their values from the database, so they
221/// take the posted ones instead, or the editor's changes would be lost.
222async fn widgets_for<T: CmsAdmin>(
223    row: &T,
224    pool: &Pool,
225    read_only: &[&str],
226    all_read_only: bool,
227    posted: Option<&AdminForm>,
228) -> Vec<Widget> {
229    let mut out = Vec::new();
230    for mut w in row.admin_widgets() {
231        if matches!(w.kind, WidgetKind::Select | WidgetKind::Radio | WidgetKind::Checkboxes | WidgetKind::MultiSelect) {
232            if let Some(options) = T::field_options(pool, &w.name).await {
233                w.options = options;
234            }
235        }
236        if all_read_only || read_only.contains(&w.name.as_str()) {
237            w.read_only = true;
238        }
239        out.push(w);
240    }
241    for mut w in row.extra_widgets(pool).await {
242        if let Some(v) = posted.and_then(|f| f.get(&w.name)) {
243            w.value = v.to_owned();
244        }
245        if all_read_only {
246            w.read_only = true;
247        }
248        out.push(w);
249    }
250    out
251}
252
253impl<T: CmsAdmin> CmsAdminPage<T> {
254    fn code(action: Action) -> String {
255        format!("{}.{}", T::admin_meta().permission_resource, action.as_str())
256    }
257
258    async fn list(ctx: &AdminPageCtx<'_>) -> Response {
259        let meta = T::admin_meta();
260        let pool = ctx.tenant.pool();
261        let q = ctx.query_param("q").unwrap_or_default();
262        let query = ctx.query();
263        let per_page = super::pagination::clamp_per_page(
264            query.get("per_page").and_then(|v| v.parse().ok()).or(Some(usize::try_from(meta.per_page).unwrap_or(25))),
265        );
266        let page = query.get("page").and_then(|v| v.parse::<i64>().ok()).unwrap_or(1).max(1);
267        let offset = super::pagination::offset(page, per_page);
268        let (rows, total) = match T::admin_list(pool, &q, per_page as i64, offset).await {
269            Ok(found) => found,
270            Err(e) => return super::AdminError::from(e).into_response(),
271        };
272        let mut columns: Vec<Vec<String>> = Vec::with_capacity(meta.list.len());
273        for (field, _) in meta.list {
274            let cells = match T::list_column(pool, &rows, field).await {
275                Some(cells) if cells.len() == rows.len() => cells,
276                _ => rows.iter().map(|r| r.admin_cell(field)).collect(),
277            };
278            columns.push(cells);
279        }
280        let items: Vec<Value> = rows
281            .iter()
282            .enumerate()
283            .map(|(i, r)| {
284                let cells: Vec<&str> = columns.iter().map(|c| c[i].as_str()).collect();
285                json!({ "id": r.admin_id(), "title": r.admin_title(), "cells": cells })
286            })
287            .collect();
288        let mut tctx = tera::Context::new();
289        tctx.insert("meta", &meta_json(meta));
290        tctx.insert("columns", &meta.list.iter().map(|(_, h)| *h).collect::<Vec<_>>());
291        tctx.insert("items", &items);
292        tctx.insert("q", &q);
293        tctx.insert("total", &total);
294        tctx.insert("query_string", ctx.uri.query().unwrap_or_default());
295        tctx.insert(
296            "pagination",
297            &super::pagination::context(page, per_page, usize::try_from(total).unwrap_or_default()),
298        );
299        tctx.insert("can_add", &(ctx.has_perm(&Self::code(Action::Add)).await && T::can_create(pool).await));
300        ctx.render("rcms_admin/cms_admin_list.html", &mut tctx).await
301    }
302
303    async fn form(ctx: &AdminPageCtx<'_>, row: &T, errors: &[FieldError], posted: Option<&AdminForm>) -> Response {
304        let meta = T::admin_meta();
305        let pool = ctx.tenant.pool();
306        let id = row.admin_id();
307        let may_write = ctx.has_perm(&Self::code(if id.is_some() { Action::Edit } else { Action::Add })).await;
308        let read_only = row.read_only_fields(pool).await;
309        let widgets = widgets_for(row, pool, &read_only, !may_write, posted).await;
310        let can_delete = id.is_some() && ctx.has_perm(&Self::code(Action::Delete)).await && row.can_delete(pool).await;
311        let mut by_field: HashMap<&str, Vec<&str>> = HashMap::new();
312        for e in errors {
313            by_field.entry(e.field.as_str()).or_default().push(e.message.as_str());
314        }
315        let mut tctx = tera::Context::new();
316        tctx.insert("meta", &meta_json(meta));
317        tctx.insert("record_id", &id);
318        tctx.insert("record_title", &row.admin_title());
319        tctx.insert("fields", &widgets);
320        tctx.insert("errors", &by_field);
321        tctx.insert("can_save", &may_write);
322        tctx.insert("can_delete", &can_delete);
323        let mut resp = ctx.render("rcms_admin/cms_admin_form.html", &mut tctx).await;
324        if !errors.is_empty() {
325            *resp.status_mut() = StatusCode::UNPROCESSABLE_ENTITY;
326        }
327        resp
328    }
329
330    async fn load(ctx: &AdminPageCtx<'_>, id: Option<i64>) -> Result<Option<T>, Response> {
331        let Some(id) = id else { return Ok(None) };
332        T::admin_get(ctx.tenant.pool(), id).await.map_err(|e| super::AdminError::from(e).into_response())
333    }
334
335    async fn save(ctx: &AdminPageCtx<'_>, form: &AdminForm) -> Response {
336        let meta = T::admin_meta();
337        let pool = ctx.tenant.pool();
338        let mut row = if ctx.action == Some("new") {
339            if !T::can_create(pool).await {
340                return forbidden();
341            }
342            T::admin_new()
343        } else {
344            match Self::load(ctx, form.int("id")).await {
345                Ok(Some(row)) => row,
346                Ok(None) => return not_found(),
347                Err(resp) => return resp,
348            }
349        };
350        if let Err(errors) = save_record(pool, &mut row, form).await {
351            return Self::form(ctx, &row, &errors, Some(form)).await;
352        }
353        let message = format!("Saved {} “{}”.", meta.singular, row.admin_title());
354        let back = match (form.get("_continue"), row.admin_id()) {
355            (Some(_), Some(id)) => format!("{}/edit?id={id}", ctx.page_url()),
356            _ => ctx.page_url(),
357        };
358        ctx.redirect(&back, MessageLevel::Success, &message)
359    }
360
361    async fn delete(ctx: &AdminPageCtx<'_>, form: &AdminForm) -> Response {
362        let meta = T::admin_meta();
363        let row = match Self::load(ctx, form.int("id")).await {
364            Ok(Some(row)) => row,
365            Ok(None) => return not_found(),
366            Err(resp) => return resp,
367        };
368        let title = row.admin_title();
369        match delete_record(ctx.tenant.pool(), row).await {
370            Ok(true) => ctx.redirect(&ctx.page_url(), MessageLevel::Success, &format!("Deleted {} “{title}”.", meta.singular)),
371            Ok(false) => forbidden(),
372            Err(e) => ctx.redirect(&ctx.page_url(), MessageLevel::Error, &format!("Could not delete “{title}”: {e}")),
373        }
374    }
375}
376
377/// Apply a posted form to `row` and store it, running the hooks in
378/// order: [`CmsAdmin::admin_apply`] (skipping
379/// [`CmsAdminOverrides::read_only_fields`]), [`CmsAdminOverrides::validate`],
380/// the save, [`CmsAdminOverrides::save_extra`], then
381/// [`CmsAdminOverrides::after_save`]. A row without a primary key is
382/// added, and only when [`CmsAdminOverrides::can_create`] allows it.
383///
384/// # Errors
385/// The validation messages, or one `"_form"` error carrying a refused
386/// add or a database failure.
387pub async fn save_record<T: CmsAdmin>(pool: &Pool, row: &mut T, form: &AdminForm) -> Result<(), Vec<FieldError>> {
388    let creating = row.admin_id().is_none();
389    if creating && !T::can_create(pool).await {
390        return Err(vec![FieldError::new("_form", format!("New {} can't be added here.", T::admin_meta().singular))]);
391    }
392    let read_only = row.read_only_fields(pool).await;
393    let mut errors = row.admin_apply(form, &read_only);
394    if errors.is_empty() {
395        errors = row.validate(pool).await;
396    }
397    if !errors.is_empty() {
398        return Err(errors);
399    }
400    let stored = async {
401        row.admin_save(pool).await?;
402        row.save_extra(pool, form).await?;
403        row.after_save(pool, creating).await
404    }
405    .await;
406    stored.map_err(|e| vec![FieldError::new("_form", e.to_string())])
407}
408
409/// Delete `row` after [`CmsAdminOverrides::can_delete`] and
410/// [`CmsAdminOverrides::before_delete`]. `Ok(false)` when `can_delete`
411/// refuses.
412///
413/// # Errors
414/// A failure from `before_delete` or the delete itself.
415pub async fn delete_record<T: CmsAdmin>(pool: &Pool, row: T) -> Result<bool, ExecError> {
416    if !row.can_delete(pool).await {
417        return Ok(false);
418    }
419    row.before_delete(pool).await?;
420    row.admin_delete(pool).await?;
421    Ok(true)
422}
423
424fn meta_json(meta: &CmsAdminMeta) -> Value {
425    json!({
426        "slug": meta.slug,
427        "label": meta.label,
428        "singular": meta.singular,
429        "icon": meta.icon,
430        "searchable": meta.searchable,
431        "url": format!("/cms-admin/x/{}", meta.slug),
432    })
433}
434
435#[async_trait]
436impl<T: CmsAdmin> AdminPageHandler for CmsAdminPage<T> {
437    fn slug(&self) -> &'static str {
438        T::admin_meta().slug
439    }
440
441    fn label(&self) -> &'static str {
442        T::admin_meta().label
443    }
444
445    fn icon(&self) -> Option<&'static str> {
446        T::admin_meta().icon
447    }
448
449    fn section(&self) -> SidebarSection {
450        T::admin_meta().section
451    }
452
453    fn sort_order(&self) -> i32 {
454        T::admin_meta().sort_order
455    }
456
457    fn permission_resource(&self) -> Option<&'static str> {
458        Some(T::admin_meta().permission_resource)
459    }
460
461    fn permission_actions(&self) -> &'static [Action] {
462        CRUD
463    }
464
465    async fn render(&self, ctx: AdminPageCtx<'_>) -> Response {
466        match ctx.action {
467            None => Self::list(&ctx).await,
468            Some("new") => {
469                if !T::can_create(ctx.tenant.pool()).await {
470                    return forbidden();
471                }
472                Self::form(&ctx, &T::admin_new(), &[], None).await
473            }
474            Some("edit") => {
475                let id = ctx.query_param("id").and_then(|v| v.parse().ok());
476                match Self::load(&ctx, id).await {
477                    Ok(Some(row)) => Self::form(&ctx, &row, &[], None).await,
478                    Ok(None) => not_found(),
479                    Err(resp) => resp,
480                }
481            }
482            Some(_) => not_found(),
483        }
484    }
485
486    async fn post(&self, ctx: AdminPageCtx<'_>, form: AdminForm) -> Response {
487        match ctx.action {
488            Some("new" | "edit") => Self::save(&ctx, &form).await,
489            Some("delete") => Self::delete(&ctx, &form).await,
490            _ => not_found(),
491        }
492    }
493}
494
495/// Helpers the derive's generated code calls. Not a stable API.
496#[doc(hidden)]
497pub mod __derive {
498    use super::{AdminForm, FieldError};
499
500    /// The posted text for a `String` field. A required field left
501    /// empty records an error.
502    pub fn string(form: &AdminForm, name: &str, required: bool, errors: &mut Vec<FieldError>) -> Option<String> {
503        let v = form.get(name)?.to_owned();
504        if required && v.trim().is_empty() {
505            errors.push(FieldError::new(name, "This field is required."));
506        }
507        Some(v)
508    }
509
510    /// The posted value for an `Option<String>` field: blank is `None`.
511    pub fn opt_string(form: &AdminForm, name: &str) -> Option<Option<String>> {
512        let v = form.get(name)?;
513        Some(Some(v.to_owned()).filter(|s| !s.trim().is_empty()))
514    }
515
516    /// A checkbox: absent means unchecked.
517    #[must_use]
518    pub fn boolean(form: &AdminForm, name: &str) -> bool {
519        form.checked(name)
520    }
521
522    /// A required value parsed with `FromStr`. `None` leaves the field
523    /// unchanged: the value was not posted, or did not parse (recorded).
524    pub fn parsed<T: std::str::FromStr>(form: &AdminForm, name: &str, errors: &mut Vec<FieldError>) -> Option<T> {
525        let raw = form.get(name)?.trim();
526        if raw.is_empty() {
527            errors.push(FieldError::new(name, "This field is required."));
528            return None;
529        }
530        raw.parse().map_or_else(
531            |_| {
532                errors.push(FieldError::new(name, "Enter a valid value."));
533                None
534            },
535            Some,
536        )
537    }
538
539    /// An optional value parsed with `FromStr`: blank is `None`.
540    pub fn opt_parsed<T: std::str::FromStr>(form: &AdminForm, name: &str, required: bool, errors: &mut Vec<FieldError>) -> Option<Option<T>> {
541        let raw = form.get(name)?.trim();
542        if raw.is_empty() {
543            if required {
544                errors.push(FieldError::new(name, "This field is required."));
545                return None;
546            }
547            return Some(None);
548        }
549        match raw.parse() {
550            Ok(v) => Some(Some(v)),
551            Err(_) => {
552                errors.push(FieldError::new(name, "Enter a valid value."));
553                None
554            }
555        }
556    }
557
558    /// An `Option<T>` as widget text.
559    #[must_use]
560    pub fn show_opt<T: std::fmt::Display>(v: Option<&T>) -> String {
561        v.map(ToString::to_string).unwrap_or_default()
562    }
563}
564
565#[cfg(test)]
566mod tests {
567    use super::__derive::*;
568    use super::*;
569
570    fn form(body: &str) -> AdminForm {
571        AdminForm::parse(body.as_bytes())
572    }
573
574    #[test]
575    fn sections_parse_to_built_ins_or_a_new_heading() {
576        assert_eq!(section_from("content"), SidebarSection::Content);
577        assert_eq!(section_from("Site"), SidebarSection::Site);
578        assert_eq!(section_from("Giving Days"), SidebarSection::Custom("Giving Days"));
579    }
580
581    #[test]
582    fn values_parse_or_record_an_error() {
583        let f = form("n=42&bad=x&blank=&s=hi&o=");
584        let mut errors = Vec::new();
585        assert_eq!(parsed::<i32>(&f, "n", &mut errors), Some(42));
586        assert_eq!(parsed::<i32>(&f, "bad", &mut errors), None);
587        assert_eq!(parsed::<i32>(&f, "absent", &mut errors), None);
588        assert_eq!(opt_parsed::<i64>(&f, "blank", false, &mut errors), Some(None));
589        assert_eq!(string(&f, "s", true, &mut errors), Some("hi".into()));
590        assert_eq!(opt_string(&f, "o"), Some(None));
591        assert_eq!(errors, vec![FieldError::new("bad", "Enter a valid value.")]);
592        let mut errors = Vec::new();
593        assert_eq!(string(&f, "blank", true, &mut errors), Some(String::new()));
594        assert_eq!(opt_parsed::<i64>(&f, "blank", true, &mut errors), None);
595        assert_eq!(errors.len(), 2, "both required blanks are reported");
596    }
597
598    #[test]
599    fn checkbox_absent_is_false() {
600        assert!(boolean(&form("a=on"), "a"));
601        assert!(!boolean(&form("b=on"), "a"));
602    }
603
604    #[test]
605    fn form_keeps_repeated_values() {
606        let f = form("ids=1&ids=2&ids=x&name=+a+");
607        assert_eq!(f.ints("ids"), vec![1, 2]);
608        assert_eq!(f.all("ids").len(), 3);
609        assert_eq!(f.text("name"), "a");
610        assert_eq!(f.get("ids"), Some("x"), "get returns the last value");
611    }
612}