use kit::{inertia_response, Request, Response, InertiaProps, redirect};
use kit::database::{Model, ModelMut};
use crate::models::todos::{Entity as Todos, ActiveModel, Model as Todo};
use sea_orm::ActiveValue::Set;
use serde::{Deserialize, Serialize};
// Props for the index page
#[derive(InertiaProps)]
pub struct TodoIndexProps {
pub todos: Vec<Todo>,
pub filter: String,
}
// Props for the create/edit page
#[derive(InertiaProps)]
pub struct TodoFormProps {
pub todo: Option<Todo>,
}
#[derive(Deserialize)]
pub struct TodoRequest {
pub title: String,
}
// GET /todos
pub async fn index(req: Request) -> Response {
let filter = req.query("filter").unwrap_or("all".to_string());
let todos = match filter.as_str() {
"completed" => {
use sea_orm::{EntityTrait, QueryFilter, ColumnTrait};
use crate::models::todos::Column;
Todos::find()
.filter(Column::Completed.eq(true))
.all(kit::database::DB::connection())
.await
.unwrap_or_default()
}
"pending" => {
use sea_orm::{EntityTrait, QueryFilter, ColumnTrait};
use crate::models::todos::Column;
Todos::find()
.filter(Column::Completed.eq(false))
.all(kit::database::DB::connection())
.await
.unwrap_or_default()
}
_ => Todos::all().await.unwrap_or_default(),
};
inertia_response!("Todos/Index", TodoIndexProps { todos, filter })
}
// GET /todos/create
pub async fn create(_req: Request) -> Response {
inertia_response!("Todos/Create", TodoFormProps { todo: None })
}
// POST /todos
pub async fn store(req: Request) -> Response {
let body: TodoRequest = req.json().await.unwrap();
let new_todo = ActiveModel {
title: Set(body.title),
completed: Set(false),
created_at: Set(chrono::Utc::now().naive_utc()),
..Default::default()
};
let _ = Todos::insert_one(new_todo).await;
redirect("/todos")
}
// GET /todos/:id/edit
pub async fn edit(req: Request) -> Response {
let id: i32 = req.param("id").unwrap().parse().unwrap();
match Todos::find_by_pk(id).await {
Ok(Some(todo)) => {
inertia_response!("Todos/Edit", TodoFormProps { todo: Some(todo) })
}
_ => redirect("/todos"),
}
}
// PUT /todos/:id
pub async fn update(req: Request) -> Response {
let id: i32 = req.param("id").unwrap().parse().unwrap();
let body: TodoRequest = req.json().await.unwrap();
if let Ok(Some(existing)) = Todos::find_by_pk(id).await {
let mut active: ActiveModel = existing.into();
active.title = Set(body.title);
let _ = Todos::update_one(active).await;
}
redirect("/todos")
}
// POST /todos/:id/toggle
pub async fn toggle(req: Request) -> Response {
let id: i32 = req.param("id").unwrap().parse().unwrap();
if let Ok(Some(existing)) = Todos::find_by_pk(id).await {
let mut active: ActiveModel = existing.clone().into();
active.completed = Set(!existing.completed);
let _ = Todos::update_one(active).await;
}
redirect("/todos")
}
// DELETE /todos/:id
pub async fn destroy(req: Request) -> Response {
let id: i32 = req.param("id").unwrap().parse().unwrap();
let _ = Todos::delete_by_pk(id).await;
redirect("/todos")
}