profile of a new registered users

This commit is contained in:
Priec
2026-06-18 21:11:48 +02:00
parent b9c1277876
commit c6624e1b3d
20 changed files with 501 additions and 17 deletions

View File

@@ -17,7 +17,7 @@ use std::{path::Path, sync::Arc};
#[allow(unused_imports)]
use crate::{
controllers::{
admin_categories, admin_dashboard, admin_form, admin_orders,
account, admin_categories, admin_dashboard, admin_form, admin_orders,
admin_products, admin_shipping, auth, auth_pages, cart, checkout, home, i18n, media, oauth2,
shop,
},
@@ -91,6 +91,7 @@ impl Hooks for App {
// cross-cutting
.add_route(auth::routes())
.add_route(auth_pages::routes())
.add_route(account::routes())
.add_route(oauth2::routes())
.add_route(i18n::routes())
.add_route(media::routes())

112
src/controllers/account.rs Normal file
View File

@@ -0,0 +1,112 @@
//! Customer account area. Currently just the shipping/contact profile, whose
//! fields prefill the checkout form. Gated to authenticated non-admin users:
//! anonymous visitors are bounced to `/login`. Admins have their own area and
//! are sent to the dashboard.
use axum_extra::extract::cookie::CookieJar;
use loco_rs::prelude::*;
use serde::Deserialize;
use serde_json::json;
use crate::{
controllers::i18n::current_lang,
models::customer_profiles::{self, ProfileFields},
shared::guard,
};
#[derive(Debug, Deserialize)]
struct ProfileForm {
phone_prefix: Option<String>,
phone: Option<String>,
address: Option<String>,
city: Option<String>,
zip: Option<String>,
country: Option<String>,
}
fn trimmed(value: Option<&str>) -> Option<String> {
value.map(str::trim).filter(|v| !v.is_empty()).map(String::from)
}
impl From<ProfileForm> for ProfileFields {
fn from(form: ProfileForm) -> Self {
Self {
phone_prefix: trimmed(form.phone_prefix.as_deref()),
phone: trimmed(form.phone.as_deref()),
address: trimmed(form.address.as_deref()),
city: trimmed(form.city.as_deref()),
zip: trimmed(form.zip.as_deref()),
country: trimmed(form.country.as_deref()),
}
}
}
/// Render the profile form for `profile` (which may be `None` for a customer
/// who hasn't saved anything yet). `saved` shows the success banner after a
/// POST.
fn profile_view(
v: &TeraView,
jar: &CookieJar,
name: &str,
email: &str,
profile: Option<&customer_profiles::Model>,
saved: bool,
) -> Result<Response> {
format::view(
v,
"account/profile.html",
json!({
"logged_in_admin": false,
"logged_in_customer": true,
"saved": saved,
"name": name,
"email": email,
"phone_prefix": profile.and_then(|p| p.phone_prefix.clone()),
"phone": profile.and_then(|p| p.phone.clone()),
"address": profile.and_then(|p| p.address.clone()),
"city": profile.and_then(|p| p.city.clone()),
"zip": profile.and_then(|p| p.zip.clone()),
"country": profile.and_then(|p| p.country.clone()),
"lang": current_lang(jar),
}),
)
}
#[debug_handler]
async fn profile_page(
jar: CookieJar,
ViewEngine(v): ViewEngine<TeraView>,
State(ctx): State<AppContext>,
) -> Result<Response> {
let Some(user) = guard::current_user(&ctx, &jar).await else {
return format::redirect("/login");
};
if guard::is_admin(&ctx, &user) {
return format::redirect("/admin/dashboard");
}
let profile = customer_profiles::Model::find_for_user(&ctx.db, user.id).await?;
profile_view(&v, &jar, &user.name, &user.email, profile.as_ref(), false)
}
#[debug_handler]
async fn save_profile(
jar: CookieJar,
ViewEngine(v): ViewEngine<TeraView>,
State(ctx): State<AppContext>,
Form(form): Form<ProfileForm>,
) -> Result<Response> {
let Some(user) = guard::current_user(&ctx, &jar).await else {
return format::redirect("/login");
};
if guard::is_admin(&ctx, &user) {
return format::redirect("/admin/dashboard");
}
let profile = customer_profiles::Model::upsert(&ctx.db, user.id, form.into()).await?;
profile_view(&v, &jar, &user.name, &user.email, Some(&profile), true)
}
pub fn routes() -> Routes {
Routes::new()
.add("/account/profile", get(profile_page))
.add("/account/profile", post(save_profile))
}

View File

@@ -1,4 +1,4 @@
use crate::{controllers::i18n::current_lang, shared::money::format_price, models::products};
use crate::{controllers::i18n::current_lang, shared::{guard, money::format_price}, models::products};
use axum::{
http::{HeaderMap, StatusCode},
response::Redirect,
@@ -234,6 +234,7 @@ async fn show(
// Drop any now-invalid lines from the cookie so the badge stays accurate.
let rebuilt = serialize_cart(&valid);
let (logged_in_admin, logged_in_customer) = guard::chrome(&ctx, &jar).await;
let response = format::view(
&v,
"shop/cart.html",
@@ -241,6 +242,8 @@ async fn show(
"items": lines,
"total": format_price(total),
"currency": currency,
"logged_in_admin": logged_in_admin,
"logged_in_customer": logged_in_customer,
"lang": current_lang(&jar),
}),
)?;

View File

@@ -10,9 +10,9 @@ use time::Duration as TimeDuration;
use crate::{
controllers::cart::{resolve_cart, CART_COOKIE},
models::{order_items, orders, shipping_methods},
models::{customer_profiles::{self, ProfileFields}, order_items, orders, shipping_methods},
controllers::i18n::current_lang,
shared::{money::format_price, settings},
shared::{guard, money::format_price, settings},
views::checkout as view,
};
@@ -33,6 +33,8 @@ struct CheckoutForm {
carrier_code: String,
pickup_point_id: Option<String>,
pickup_point_name: Option<String>,
// Present (as "on") only when a logged-in customer ticks "save my address".
save_profile: Option<String>,
}
fn trimmed(value: &str) -> Option<String> {
@@ -86,6 +88,19 @@ async fn checkout_page(
})
.collect();
// Prefill the form for a logged-in customer: contact name/email come from
// the user account, the address/phone from their saved profile (if any).
let user = guard::current_user(&ctx, &jar).await;
let is_admin = user.as_ref().is_some_and(|u| guard::is_admin(&ctx, u));
let is_customer = user.is_some() && !is_admin;
let profile = match (&user, is_customer) {
(Some(u), true) => customer_profiles::Model::find_for_user(&ctx.db, u.id).await?,
_ => None,
};
let p = |get: fn(&customer_profiles::Model) -> Option<String>| {
profile.as_ref().and_then(get)
};
format::view(
&v,
"shop/checkout.html",
@@ -96,6 +111,16 @@ async fn checkout_page(
"currency": currency,
"shipping_methods": methods,
"packeta_api_key": settings::get(&ctx, "packeta_api_key").unwrap_or(""),
"logged_in_admin": is_admin,
"logged_in_customer": is_customer,
"prefill_email": user.as_ref().filter(|_| is_customer).map(|u| u.email.clone()),
"prefill_name": user.as_ref().filter(|_| is_customer).map(|u| u.name.clone()),
"prefill_phone_prefix": p(|x| x.phone_prefix.clone()),
"prefill_phone": p(|x| x.phone.clone()),
"prefill_address": p(|x| x.address.clone()),
"prefill_city": p(|x| x.city.clone()),
"prefill_zip": p(|x| x.zip.clone()),
"prefill_country": p(|x| x.country.clone()),
"lang": current_lang(&jar),
}),
)
@@ -119,7 +144,7 @@ async fn place_order(
trimmed(&form.phone).ok_or_else(|| Error::BadRequest("phone is required".to_string()))?;
let phone = match trimmed(&form.phone_prefix) {
Some(prefix) => format!("{prefix} {number}"),
None => number,
None => number.clone(),
};
// Contact and shipping-address fields are mandatory (also enforced in the
@@ -157,6 +182,28 @@ async fn place_order(
(None, None)
};
// If a logged-in customer opted in, persist this address to their profile
// so the next checkout is prefilled. Phone is stored split (prefix + number)
// to match the profile/checkout fields. Best-effort: a failure here is logged
// but must not block the order.
if form.save_profile.is_some() {
if let Some(user) = guard::current_user(&ctx, &jar).await {
if !guard::is_admin(&ctx, &user) {
let fields = ProfileFields {
phone_prefix: trimmed(&form.phone_prefix),
phone: Some(number.clone()),
address: Some(address.clone()),
city: Some(city.clone()),
zip: Some(zip.clone()),
country: Some(country.clone()),
};
if let Err(err) = customer_profiles::Model::upsert(&ctx.db, user.id, fields).await {
tracing::error!(error = %err, user_id = user.id, "failed to save checkout profile");
}
}
}
}
let order = orders::place(
&ctx,
&valid,
@@ -198,6 +245,7 @@ async fn order_confirmation(
.filter(order_items::Column::OrderId.eq(order.id))
.all(&ctx.db)
.await?;
let (logged_in_admin, logged_in_customer) = guard::chrome(&ctx, &jar).await;
format::view(
&v,
@@ -209,6 +257,8 @@ async fn order_confirmation(
settings::get(&ctx, "bank_account_name").unwrap_or(""),
),
"items": view::items(&items),
"logged_in_admin": logged_in_admin,
"logged_in_customer": logged_in_customer,
"lang": current_lang(&jar),
}),
)

View File

@@ -13,13 +13,15 @@ async fn index(
State(ctx): State<AppContext>,
) -> Result<Response> {
let products = shop::featured_products(&ctx, 8).await?;
let (logged_in_admin, logged_in_customer) = guard::chrome(&ctx, &jar).await;
format::view(
&v,
"home/index.html",
json!({
"products": products,
"logged_in_admin": guard::logged_in(&ctx, &jar).await,
"logged_in_admin": logged_in_admin,
"logged_in_customer": logged_in_customer,
"lang": current_lang(&jar),
}),
)

View File

@@ -1,3 +1,4 @@
pub mod account;
pub mod auth;
pub mod auth_pages;
pub mod oauth2;

View File

@@ -69,12 +69,14 @@ async fn index(
.all(&ctx.db)
.await?;
let (logged_in_admin, logged_in_customer) = guard::chrome(&ctx, &jar).await;
format::view(
&v,
"shop/index.html",
json!({
"products": product_rows(&ctx, list).await?,
"logged_in_admin": guard::logged_in(&ctx, &jar).await,
"logged_in_admin": logged_in_admin,
"logged_in_customer": logged_in_customer,
"lang": current_lang(&jar),
}),
)
@@ -108,6 +110,7 @@ async fn show(
None => None,
};
let (logged_in_admin, logged_in_customer) = guard::chrome(&ctx, &jar).await;
format::view(
&v,
"shop/show.html",
@@ -115,7 +118,8 @@ async fn show(
"product": view::product_card(&product, None, category.as_ref().map(|c| c.name.clone())),
"images": images.iter().map(|i| i.image_id.clone()).collect::<Vec<_>>(),
"category": category,
"logged_in_admin": guard::logged_in(&ctx, &jar).await,
"logged_in_admin": logged_in_admin,
"logged_in_customer": logged_in_customer,
"lang": current_lang(&jar),
}),
)
@@ -151,6 +155,7 @@ async fn category(
.all(&ctx.db)
.await?;
let (logged_in_admin, logged_in_customer) = guard::chrome(&ctx, &jar).await;
format::view(
&v,
"shop/category.html",
@@ -159,7 +164,8 @@ async fn category(
"breadcrumbs": breadcrumbs,
"children": children,
"products": product_rows(&ctx, list).await?,
"logged_in_admin": guard::logged_in(&ctx, &jar).await,
"logged_in_admin": logged_in_admin,
"logged_in_customer": logged_in_customer,
"lang": current_lang(&jar),
}),
)

View File

@@ -0,0 +1,40 @@
//! `SeaORM` Entity for customer shipping/contact profiles. Hand-written to match
//! the `customer_profiles` migration (1:1 with `users` via a unique `user_id`).
use sea_orm::entity::prelude::*;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Serialize, Deserialize)]
#[sea_orm(table_name = "customer_profiles")]
pub struct Model {
pub created_at: DateTimeWithTimeZone,
pub updated_at: DateTimeWithTimeZone,
#[sea_orm(primary_key)]
pub id: i32,
#[sea_orm(unique)]
pub user_id: i32,
pub phone_prefix: Option<String>,
pub phone: Option<String>,
pub address: Option<String>,
pub city: Option<String>,
pub zip: Option<String>,
pub country: Option<String>,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(
belongs_to = "super::users::Entity",
from = "Column::UserId",
to = "super::users::Column::Id",
on_update = "Cascade",
on_delete = "Cascade"
)]
Users,
}
impl Related<super::users::Entity> for Entity {
fn to() -> RelationDef {
Relation::Users.def()
}
}

View File

@@ -4,6 +4,7 @@ pub mod prelude;
pub mod audit_logs;
pub mod categories;
pub mod customer_profiles;
pub mod o_auth2_sessions;
pub mod order_items;
pub mod orders;

View File

@@ -2,6 +2,7 @@
pub use super::audit_logs::Entity as AuditLogs;
pub use super::categories::Entity as Categories;
pub use super::customer_profiles::Entity as CustomerProfiles;
pub use super::o_auth2_sessions::Entity as OAuth2Sessions;
pub use super::order_items::Entity as OrderItems;
pub use super::orders::Entity as Orders;

View File

@@ -0,0 +1,64 @@
//! Per-customer shipping/contact profile: the address + phone fields used to
//! prefill checkout. One row per user (unique `user_id`); `name`/`email` are
//! read from `users`, never duplicated here.
pub use crate::models::_entities::customer_profiles::{ActiveModel, Column, Entity, Model};
use sea_orm::entity::prelude::*;
use sea_orm::{ActiveValue, IntoActiveModel, QueryFilter, TryIntoModel};
pub type CustomerProfiles = Entity;
/// The editable profile fields, shared by the profile page and the checkout
/// "save my address" path.
#[derive(Debug, Default, Clone)]
pub struct ProfileFields {
pub phone_prefix: Option<String>,
pub phone: Option<String>,
pub address: Option<String>,
pub city: Option<String>,
pub zip: Option<String>,
pub country: Option<String>,
}
#[async_trait::async_trait]
impl ActiveModelBehavior for ActiveModel {
async fn before_save<C>(self, _db: &C, _insert: bool) -> std::result::Result<Self, DbErr>
where
C: ConnectionTrait,
{
Ok(self)
}
}
impl Model {
/// The profile for `user_id`, if one exists.
pub async fn find_for_user(db: &DatabaseConnection, user_id: i32) -> Result<Option<Self>, DbErr> {
Entity::find()
.filter(Column::UserId.eq(user_id))
.one(db)
.await
}
/// Insert or update the profile for `user_id` with `fields`, returning the
/// persisted row. The unique `user_id` index keeps this 1:1.
pub async fn upsert(
db: &DatabaseConnection,
user_id: i32,
fields: ProfileFields,
) -> Result<Self, DbErr> {
let mut active = match Self::find_for_user(db, user_id).await? {
Some(existing) => existing.into_active_model(),
None => ActiveModel {
user_id: ActiveValue::set(user_id),
..Default::default()
},
};
active.phone_prefix = ActiveValue::set(fields.phone_prefix);
active.phone = ActiveValue::set(fields.phone);
active.address = ActiveValue::set(fields.address);
active.city = ActiveValue::set(fields.city);
active.zip = ActiveValue::set(fields.zip);
active.country = ActiveValue::set(fields.country);
active.save(db).await?.try_into_model()
}
}

View File

@@ -8,6 +8,7 @@ pub mod _entities;
pub mod audit_logs;
pub mod categories;
pub mod customer_profiles;
pub mod o_auth2_sessions;
pub mod order_items;
pub mod orders;

View File

@@ -45,3 +45,14 @@ pub async fn logged_in(ctx: &AppContext, jar: &CookieJar) -> bool {
None => false,
}
}
/// Nav chrome flags for storefront pages, in one DB lookup: returns
/// `(logged_in_admin, logged_in_customer)`. A customer is any authenticated
/// non-admin user. Both are `false` for anonymous visitors.
pub async fn chrome(ctx: &AppContext, jar: &CookieJar) -> (bool, bool) {
match current_user(ctx, jar).await {
Some(user) if is_admin(ctx, &user) => (true, false),
Some(_) => (false, true),
None => (false, false),
}
}