loco straucture
This commit is contained in:
200
src/controllers/checkout.rs
Normal file
200
src/controllers/checkout.rs
Normal file
@@ -0,0 +1,200 @@
|
||||
//! Public checkout flow: the checkout form, placing an order, and the order
|
||||
//! confirmation page.
|
||||
|
||||
use axum_extra::extract::cookie::{Cookie, CookieJar, SameSite};
|
||||
use loco_rs::prelude::*;
|
||||
use sea_orm::{ColumnTrait, EntityTrait, QueryFilter, QueryOrder};
|
||||
use serde::Deserialize;
|
||||
use serde_json::json;
|
||||
use time::Duration as TimeDuration;
|
||||
|
||||
use crate::{
|
||||
controllers::cart::{resolve_cart, CART_COOKIE},
|
||||
models::{order_items, orders, shipping_methods},
|
||||
controllers::i18n::current_lang,
|
||||
shared::{money::format_price, settings},
|
||||
views::checkout as view,
|
||||
};
|
||||
|
||||
const PAYMENT_METHODS: [&str; 2] = ["cod", "bank_transfer"];
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct CheckoutForm {
|
||||
email: String,
|
||||
customer_name: String,
|
||||
address: String,
|
||||
city: String,
|
||||
zip: String,
|
||||
country: String,
|
||||
note: Option<String>,
|
||||
payment_method: String,
|
||||
carrier_code: String,
|
||||
pickup_point_id: Option<String>,
|
||||
pickup_point_name: Option<String>,
|
||||
}
|
||||
|
||||
fn trimmed(value: &str) -> Option<String> {
|
||||
let value = value.trim();
|
||||
(!value.is_empty()).then(|| value.to_string())
|
||||
}
|
||||
|
||||
fn cleared_cart_cookie() -> Cookie<'static> {
|
||||
Cookie::build((CART_COOKIE, ""))
|
||||
.path("/")
|
||||
.same_site(SameSite::Lax)
|
||||
.max_age(TimeDuration::seconds(0))
|
||||
.build()
|
||||
}
|
||||
|
||||
async fn enabled_shipping_methods(ctx: &AppContext) -> Result<Vec<shipping_methods::Model>> {
|
||||
Ok(shipping_methods::Entity::find()
|
||||
.filter(shipping_methods::Column::Enabled.eq(true))
|
||||
.order_by_asc(shipping_methods::Column::Position)
|
||||
.all(&ctx.db)
|
||||
.await?)
|
||||
}
|
||||
|
||||
#[debug_handler]
|
||||
async fn checkout_page(
|
||||
jar: CookieJar,
|
||||
ViewEngine(v): ViewEngine<TeraView>,
|
||||
State(ctx): State<AppContext>,
|
||||
) -> Result<Response> {
|
||||
let (lines, _valid, subtotal) = resolve_cart(&ctx, &jar).await?;
|
||||
if lines.is_empty() {
|
||||
return format::redirect("/cart");
|
||||
}
|
||||
let currency = lines
|
||||
.first()
|
||||
.and_then(|line| line["currency"].as_str())
|
||||
.unwrap_or("EUR")
|
||||
.to_string();
|
||||
|
||||
let methods: Vec<serde_json::Value> = enabled_shipping_methods(&ctx)
|
||||
.await?
|
||||
.iter()
|
||||
.map(|m| {
|
||||
json!({
|
||||
"code": m.code,
|
||||
"name": m.name,
|
||||
"price_cents": m.price_cents,
|
||||
"price": format_price(m.price_cents),
|
||||
"requires_pickup_point": m.requires_pickup_point,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
format::view(
|
||||
&v,
|
||||
"shop/checkout.html",
|
||||
json!({
|
||||
"items": lines,
|
||||
"subtotal": format_price(subtotal),
|
||||
"subtotal_cents": subtotal,
|
||||
"currency": currency,
|
||||
"shipping_methods": methods,
|
||||
"packeta_api_key": settings::get(&ctx, "packeta_api_key").unwrap_or(""),
|
||||
"lang": current_lang(&jar),
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
#[debug_handler]
|
||||
async fn place_order(
|
||||
jar: CookieJar,
|
||||
State(ctx): State<AppContext>,
|
||||
Form(form): Form<CheckoutForm>,
|
||||
) -> Result<Response> {
|
||||
let (_lines, valid, _total) = resolve_cart(&ctx, &jar).await?;
|
||||
if valid.is_empty() {
|
||||
return format::redirect("/cart");
|
||||
}
|
||||
let email =
|
||||
trimmed(&form.email).ok_or_else(|| Error::BadRequest("email is required".to_string()))?;
|
||||
|
||||
if !PAYMENT_METHODS.contains(&form.payment_method.as_str()) {
|
||||
return Err(Error::BadRequest("invalid payment method".to_string()));
|
||||
}
|
||||
|
||||
// Resolve the chosen carrier from the enabled methods (price is taken from
|
||||
// the DB, never the form, so the customer can't pick their own fee).
|
||||
let method = shipping_methods::Entity::find()
|
||||
.filter(shipping_methods::Column::Code.eq(&form.carrier_code))
|
||||
.filter(shipping_methods::Column::Enabled.eq(true))
|
||||
.one(&ctx.db)
|
||||
.await?
|
||||
.ok_or_else(|| Error::BadRequest("invalid shipping method".to_string()))?;
|
||||
|
||||
let (pickup_point_id, pickup_point_name) = if method.requires_pickup_point {
|
||||
let id = form
|
||||
.pickup_point_id
|
||||
.as_deref()
|
||||
.and_then(trimmed)
|
||||
.ok_or_else(|| Error::BadRequest("a pickup point is required".to_string()))?;
|
||||
(Some(id), form.pickup_point_name.as_deref().and_then(trimmed))
|
||||
} else {
|
||||
(None, None)
|
||||
};
|
||||
|
||||
let order = orders::place(
|
||||
&ctx,
|
||||
&valid,
|
||||
orders::Checkout {
|
||||
email,
|
||||
customer_name: trimmed(&form.customer_name),
|
||||
address: trimmed(&form.address),
|
||||
city: trimmed(&form.city),
|
||||
zip: trimmed(&form.zip),
|
||||
country: trimmed(&form.country),
|
||||
note: form.note.as_deref().and_then(trimmed),
|
||||
payment_method: form.payment_method,
|
||||
method,
|
||||
pickup_point_id,
|
||||
pickup_point_name,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
|
||||
format::render()
|
||||
.cookies(&[cleared_cart_cookie()])?
|
||||
.redirect(&format!("/orders/{}", order.order_number))
|
||||
}
|
||||
|
||||
#[debug_handler]
|
||||
async fn order_confirmation(
|
||||
jar: CookieJar,
|
||||
ViewEngine(v): ViewEngine<TeraView>,
|
||||
Path(order_number): Path<String>,
|
||||
State(ctx): State<AppContext>,
|
||||
) -> Result<Response> {
|
||||
let order = orders::Entity::find()
|
||||
.filter(orders::Column::OrderNumber.eq(order_number))
|
||||
.one(&ctx.db)
|
||||
.await?
|
||||
.ok_or_else(|| Error::NotFound)?;
|
||||
let items = order_items::Entity::find()
|
||||
.filter(order_items::Column::OrderId.eq(order.id))
|
||||
.all(&ctx.db)
|
||||
.await?;
|
||||
|
||||
format::view(
|
||||
&v,
|
||||
"shop/order_confirmed.html",
|
||||
json!({
|
||||
"order": view::detail(
|
||||
&order,
|
||||
settings::get(&ctx, "bank_iban").unwrap_or(""),
|
||||
settings::get(&ctx, "bank_account_name").unwrap_or(""),
|
||||
),
|
||||
"items": view::items(&items),
|
||||
"lang": current_lang(&jar),
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn routes() -> Routes {
|
||||
Routes::new()
|
||||
.add("/checkout", get(checkout_page))
|
||||
.add("/checkout", post(place_order))
|
||||
.add("/orders/{order_number}", get(order_confirmation))
|
||||
}
|
||||
Reference in New Issue
Block a user