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

@@ -70,6 +70,7 @@ auth-or = or
auth-google = Continue with Google
nav-login = Sign in
nav-register = Register
nav-profile = My profile
register-title = Create account
register-name = Name
register-submit = Create account
@@ -256,8 +257,13 @@ country-de = Germany
country-pl = Poland
country-hu = Hungary
checkout-note = Order note
checkout-save-profile = Save this address to my profile
checkout-place-order = Place order
checkout-summary = Order summary
profile-title = My profile
profile-intro = We'll use these details to prefill checkout.
profile-saved = Profile saved.
profile-save = Save profile
order-confirmed-title = Thank you for your order!
order-confirmed-sub = We have received your order.
order-number = Order number

View File

@@ -70,6 +70,7 @@ auth-or = alebo
auth-google = Pokračovať cez Google
nav-login = Prihlásiť sa
nav-register = Registrácia
nav-profile = Môj profil
register-title = Vytvoriť účet
register-name = Meno
register-submit = Zaregistrovať sa
@@ -256,8 +257,13 @@ country-de = Nemecko
country-pl = Poľsko
country-hu = Maďarsko
checkout-note = Poznámka k objednávke
checkout-save-profile = Uložiť túto adresu do môjho profilu
checkout-place-order = Odoslať objednávku
checkout-summary = Súhrn objednávky
profile-title = Môj profil
profile-intro = Tieto údaje použijeme na predvyplnenie pokladne.
profile-saved = Profil bol uložený.
profile-save = Uložiť profil
order-confirmed-title = Ďakujeme za objednávku!
order-confirmed-sub = Vašu objednávku sme prijali.
order-number = Číslo objednávky

View File

@@ -0,0 +1,114 @@
{% extends "base.html" %}
{% import "macros/ui.html" as ui %}
{% block title %}{{ t(key="profile-title", lang=lang | default(value='sk')) }}{% endblock title %}
{% block content %}
<div class="mx-auto max-w-2xl">
<h1 class="text-3xl font-bold text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="profile-title", lang=lang | default(value='sk')) }}</h1>
<p class="mt-2 text-sm text-on-surface/70 dark:text-on-surface-dark/70">{{ t(key="profile-intro", lang=lang | default(value='sk')) }}</p>
{% if saved %}
<div class="mt-4 rounded-radius border border-success bg-success/10 px-4 py-3 text-sm text-success" role="status">
{{ t(key="profile-saved", lang=lang | default(value='sk')) }}
</div>
{% endif %}
<form method="post" action="/account/profile" hx-boost="false" class="mt-6 space-y-6">
<!-- account (read-only — managed by the login) -->
<fieldset class="space-y-4 rounded-radius border border-outline bg-surface p-6 dark:border-outline-dark dark:bg-surface-dark-alt">
<legend class="px-1 text-sm font-semibold text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="checkout-contact", lang=lang | default(value='sk')) }}</legend>
<div class="space-y-1.5">
<label class="text-sm font-medium text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="checkout-name", lang=lang | default(value='sk')) }}</label>
<p class="text-sm text-on-surface/80 dark:text-on-surface-dark/80">{{ name }}</p>
</div>
<div class="space-y-1.5">
<label class="text-sm font-medium text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="checkout-email", lang=lang | default(value='sk')) }}</label>
<p class="text-sm text-on-surface/80 dark:text-on-surface-dark/80">{{ email }}</p>
</div>
<div class="space-y-1.5">
<label for="phone" class="text-sm font-medium text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="checkout-phone", lang=lang | default(value='sk')) }}</label>
<div class="flex gap-2">
<!-- editable combobox: type freely or pick from the dropdown -->
<div class="relative w-28 shrink-0" @click.outside="prefixOpen = false"
x-data="{ prefixOpen: false, prefix: '{{ phone_prefix | default(value='+421') }}', opts: [
{ v: '+421', l: '🇸🇰 +421' }, { v: '+420', l: '🇨🇿 +420' },
{ v: '+43', l: '🇦🇹 +43' }, { v: '+49', l: '🇩🇪 +49' },
{ v: '+48', l: '🇵🇱 +48' }, { v: '+36', l: '🇭🇺 +36' },
{ v: '+44', l: '🇬🇧 +44' }, { v: '+39', l: '🇮🇹 +39' }, { v: '+33', l: '🇫🇷 +33' }
], get filtered() { return this.opts.filter(o => !this.prefix || o.v.includes(this.prefix)) } }">
<input name="phone_prefix" type="text" x-model="prefix" @focus="prefixOpen = true" @input="prefixOpen = true"
aria-label="{{ t(key='checkout-phone', lang=lang | default(value='sk')) }}" autocomplete="tel-country-code" inputmode="tel"
class="w-full rounded-radius border border-outline bg-surface py-2 pl-3 pr-7 text-sm text-on-surface focus:outline-2 focus:outline-primary dark:border-outline-dark dark:bg-surface-dark dark:text-on-surface-dark">
<button type="button" tabindex="-1" @click="prefixOpen = !prefixOpen"
class="absolute inset-y-0 right-0 flex w-7 items-center justify-center text-on-surface/60 dark:text-on-surface-dark/60">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"
class="size-4 transition-transform" :class="prefixOpen && 'rotate-180'">
<path stroke-linecap="round" stroke-linejoin="round" d="m19.5 8.25-7.5 7.5-7.5-7.5" />
</svg>
</button>
<ul x-show="prefixOpen" x-cloak x-transition
class="absolute z-20 mt-1 max-h-56 w-full overflow-auto rounded-radius border border-outline bg-surface p-1 shadow-lg dark:border-outline-dark dark:bg-surface-dark-alt">
<template x-for="o in filtered" :key="o.v">
<li><button type="button" @click="prefix = o.v; prefixOpen = false" x-text="o.l"
class="block w-full rounded-radius px-3 py-1.5 text-left text-sm text-on-surface transition hover:bg-surface-alt dark:text-on-surface-dark dark:hover:bg-surface-dark"></button></li>
</template>
</ul>
</div>
{{ ui::input(name="phone", id="phone", type="tel", value=phone | default(value=''), autocomplete="tel", placeholder="900 000 000", attrs='inputmode="tel"') }}
</div>
</div>
</fieldset>
<!-- default shipping address -->
<fieldset class="space-y-4 rounded-radius border border-outline bg-surface p-6 dark:border-outline-dark dark:bg-surface-dark-alt">
<legend class="px-1 text-sm font-semibold text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="checkout-shipping", lang=lang | default(value='sk')) }}</legend>
<div class="space-y-1.5">
<label for="address" class="text-sm font-medium text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="checkout-address", lang=lang | default(value='sk')) }}</label>
{{ ui::input(name="address", id="address", value=address | default(value=''), autocomplete="street-address") }}
</div>
<div class="grid gap-4 sm:grid-cols-3">
<div class="space-y-1.5">
<label for="city" class="text-sm font-medium text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="checkout-city", lang=lang | default(value='sk')) }}</label>
{{ ui::input(name="city", id="city", value=city | default(value=''), autocomplete="address-level2") }}
</div>
<div class="space-y-1.5">
<label for="zip" class="text-sm font-medium text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="checkout-zip", lang=lang | default(value='sk')) }}</label>
{{ ui::input(name="zip", id="zip", value=zip | default(value=''), autocomplete="postal-code") }}
</div>
<div class="space-y-1.5">
<label for="country" class="text-sm font-medium text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="checkout-country", lang=lang | default(value='sk')) }}</label>
<div class="relative" @click.outside="countryOpen = false"
x-data="{ countryOpen: false, country: '{{ country | default(value='') }}', opts: [
{ v: '{{ t(key='country-sk', lang=lang | default(value='sk')) }}', l: '🇸🇰 {{ t(key='country-sk', lang=lang | default(value='sk')) }}' },
{ v: '{{ t(key='country-cz', lang=lang | default(value='sk')) }}', l: '🇨🇿 {{ t(key='country-cz', lang=lang | default(value='sk')) }}' },
{ v: '{{ t(key='country-at', lang=lang | default(value='sk')) }}', l: '🇦🇹 {{ t(key='country-at', lang=lang | default(value='sk')) }}' },
{ v: '{{ t(key='country-de', lang=lang | default(value='sk')) }}', l: '🇩🇪 {{ t(key='country-de', lang=lang | default(value='sk')) }}' },
{ v: '{{ t(key='country-pl', lang=lang | default(value='sk')) }}', l: '🇵🇱 {{ t(key='country-pl', lang=lang | default(value='sk')) }}' },
{ v: '{{ t(key='country-hu', lang=lang | default(value='sk')) }}', l: '🇭🇺 {{ t(key='country-hu', lang=lang | default(value='sk')) }}' }
], get filtered() { return this.opts.filter(o => !this.country || o.v.toLowerCase().includes(this.country.toLowerCase())) } }">
<input id="country" name="country" type="text" x-model="country" @focus="countryOpen = true" @input="countryOpen = true"
class="w-full rounded-radius border border-outline bg-surface py-2 pl-3 pr-8 text-sm text-on-surface focus:outline-2 focus:outline-primary dark:border-outline-dark dark:bg-surface-dark dark:text-on-surface-dark">
<button type="button" tabindex="-1" @click="countryOpen = !countryOpen"
class="absolute inset-y-0 right-0 flex w-8 items-center justify-center text-on-surface/60 dark:text-on-surface-dark/60">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"
class="size-4 transition-transform" :class="countryOpen && 'rotate-180'">
<path stroke-linecap="round" stroke-linejoin="round" d="m19.5 8.25-7.5 7.5-7.5-7.5" />
</svg>
</button>
<ul x-show="countryOpen" x-cloak x-transition
class="absolute z-20 mt-1 max-h-56 w-full overflow-auto rounded-radius border border-outline bg-surface p-1 shadow-lg dark:border-outline-dark dark:bg-surface-dark-alt">
<template x-for="o in filtered" :key="o.v">
<li><button type="button" @click="country = o.v; countryOpen = false" x-text="o.l"
class="block w-full rounded-radius px-3 py-1.5 text-left text-sm text-on-surface transition hover:bg-surface-alt dark:text-on-surface-dark dark:hover:bg-surface-dark"></button></li>
</template>
</ul>
</div>
</div>
</div>
</fieldset>
{{ ui::button(label=t(key="profile-save", lang=lang | default(value='sk')), type="submit", size="px-6 py-2.5 text-sm") }}
</form>
</div>
{% endblock content %}

View File

@@ -85,6 +85,13 @@
<button type="submit" class="text-sm font-medium text-danger underline-offset-2 transition hover:opacity-75 focus:outline-hidden focus-visible:underline">{{ t(key="logout", lang=lang | default(value='sk')) }}</button>
</form>
</li>
{% elif logged_in_customer %}
<li>{{ ui::nav_link(label=t(key="nav-profile", lang=lang | default(value='sk')), href="/account/profile", data_nav="/account") }}</li>
<li>
<form method="post" action="/logout" hx-boost="false">
<button type="submit" class="text-sm font-medium text-danger underline-offset-2 transition hover:opacity-75 focus:outline-hidden focus-visible:underline">{{ t(key="logout", lang=lang | default(value='sk')) }}</button>
</form>
</li>
{% else %}
<li>{{ ui::nav_link(label=t(key="nav-login", lang=lang | default(value='sk')), href="/login", data_nav="/login") }}</li>
<li>{{ ui::nav_link(label=t(key="nav-register", lang=lang | default(value='sk')), href="/register", data_nav="/register") }}</li>
@@ -131,6 +138,13 @@
<button type="submit" class="block w-full rounded-radius px-3 py-2 text-left text-sm font-medium text-danger underline-offset-2 transition hover:bg-primary/5 focus:outline-hidden focus-visible:underline">{{ t(key="logout", lang=lang | default(value='sk')) }}</button>
</form>
</li>
{% elif logged_in_customer %}
<li><a href="/account/profile" data-nav="/account" class="block rounded-radius px-3 py-2 text-sm font-medium text-on-surface underline-offset-2 transition hover:bg-primary/5 hover:text-primary focus:outline-hidden focus-visible:underline aria-[current=page]:font-semibold aria-[current=page]:bg-primary/10 aria-[current=page]:text-primary dark:text-on-surface-dark dark:hover:text-primary-dark dark:aria-[current=page]:text-primary-dark">{{ t(key="nav-profile", lang=lang | default(value='sk')) }}</a></li>
<li>
<form method="post" action="/logout" hx-boost="false">
<button type="submit" class="block w-full rounded-radius px-3 py-2 text-left text-sm font-medium text-danger underline-offset-2 transition hover:bg-primary/5 focus:outline-hidden focus-visible:underline">{{ t(key="logout", lang=lang | default(value='sk')) }}</button>
</form>
</li>
{% else %}
<li><a href="/login" data-nav="/login" class="block rounded-radius px-3 py-2 text-sm font-medium text-on-surface underline-offset-2 transition hover:bg-primary/5 hover:text-primary focus:outline-hidden focus-visible:underline aria-[current=page]:font-semibold aria-[current=page]:bg-primary/10 aria-[current=page]:text-primary dark:text-on-surface-dark dark:hover:text-primary-dark dark:aria-[current=page]:text-primary-dark">{{ t(key="nav-login", lang=lang | default(value='sk')) }}</a></li>
<li><a href="/register" data-nav="/register" class="block rounded-radius px-3 py-2 text-sm font-medium text-on-surface underline-offset-2 transition hover:bg-primary/5 hover:text-primary focus:outline-hidden focus-visible:underline aria-[current=page]:font-semibold aria-[current=page]:bg-primary/10 aria-[current=page]:text-primary dark:text-on-surface-dark dark:hover:text-primary-dark dark:aria-[current=page]:text-primary-dark">{{ t(key="nav-register", lang=lang | default(value='sk')) }}</a></li>

View File

@@ -36,18 +36,18 @@
<legend class="px-1 text-sm font-semibold text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="checkout-contact", lang=lang | default(value='sk')) }}</legend>
<div class="space-y-1.5">
<label for="email" class="text-sm font-medium text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="checkout-email", lang=lang | default(value='sk')) }}</label>
{{ ui::input(name="email", id="email", type="email", required=true, autocomplete="email") }}
{{ ui::input(name="email", id="email", type="email", value=prefill_email | default(value=''), required=true, autocomplete="email") }}
</div>
<div class="space-y-1.5">
<label for="customer_name" class="text-sm font-medium text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="checkout-name", lang=lang | default(value='sk')) }}</label>
{{ ui::input(name="customer_name", id="customer_name", required=true, autocomplete="name") }}
{{ ui::input(name="customer_name", id="customer_name", value=prefill_name | default(value=''), required=true, autocomplete="name") }}
</div>
<div class="space-y-1.5">
<label for="phone" class="text-sm font-medium text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="checkout-phone", lang=lang | default(value='sk')) }}</label>
<div class="flex gap-2">
<!-- editable combobox: type freely or pick from the dropdown -->
<div class="relative w-28 shrink-0" @click.outside="prefixOpen = false"
x-data="{ prefixOpen: false, prefix: '+421', opts: [
x-data="{ prefixOpen: false, prefix: '{{ prefill_phone_prefix | default(value='+421') }}', opts: [
{ v: '+421', l: '🇸🇰 +421' }, { v: '+420', l: '🇨🇿 +420' },
{ v: '+43', l: '🇦🇹 +43' }, { v: '+49', l: '🇩🇪 +49' },
{ v: '+48', l: '🇵🇱 +48' }, { v: '+36', l: '🇭🇺 +36' },
@@ -71,7 +71,7 @@
</template>
</ul>
</div>
{{ ui::input(name="phone", id="phone", type="tel", required=true, autocomplete="tel", placeholder="900 000 000", attrs='inputmode="tel"') }}
{{ ui::input(name="phone", id="phone", type="tel", value=prefill_phone | default(value=''), required=true, autocomplete="tel", placeholder="900 000 000", attrs='inputmode="tel"') }}
</div>
</div>
</fieldset>
@@ -81,21 +81,21 @@
<legend class="px-1 text-sm font-semibold text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="checkout-shipping", lang=lang | default(value='sk')) }}</legend>
<div class="space-y-1.5">
<label for="address" class="text-sm font-medium text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="checkout-address", lang=lang | default(value='sk')) }}</label>
{{ ui::input(name="address", id="address", required=true, autocomplete="street-address") }}
{{ ui::input(name="address", id="address", value=prefill_address | default(value=''), required=true, autocomplete="street-address") }}
</div>
<div class="grid gap-4 sm:grid-cols-3">
<div class="space-y-1.5">
<label for="city" class="text-sm font-medium text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="checkout-city", lang=lang | default(value='sk')) }}</label>
{{ ui::input(name="city", id="city", required=true, autocomplete="address-level2") }}
{{ ui::input(name="city", id="city", value=prefill_city | default(value=''), required=true, autocomplete="address-level2") }}
</div>
<div class="space-y-1.5">
<label for="zip" class="text-sm font-medium text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="checkout-zip", lang=lang | default(value='sk')) }}</label>
{{ ui::input(name="zip", id="zip", required=true, autocomplete="postal-code") }}
{{ ui::input(name="zip", id="zip", value=prefill_zip | default(value=''), required=true, autocomplete="postal-code") }}
</div>
<div class="space-y-1.5">
<label for="country" class="text-sm font-medium text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="checkout-country", lang=lang | default(value='sk')) }}</label>
<div class="relative" @click.outside="countryOpen = false"
x-data="{ countryOpen: false, country: '{{ t(key='country-sk', lang=lang | default(value='sk')) }}', opts: [
x-data="{ countryOpen: false, country: '{{ prefill_country | default(value=t(key='country-sk', lang=lang | default(value='sk'))) }}', opts: [
{ v: '{{ t(key='country-sk', lang=lang | default(value='sk')) }}', l: '🇸🇰 {{ t(key='country-sk', lang=lang | default(value='sk')) }}' },
{ v: '{{ t(key='country-cz', lang=lang | default(value='sk')) }}', l: '🇨🇿 {{ t(key='country-cz', lang=lang | default(value='sk')) }}' },
{ v: '{{ t(key='country-at', lang=lang | default(value='sk')) }}', l: '🇦🇹 {{ t(key='country-at', lang=lang | default(value='sk')) }}' },
@@ -177,6 +177,11 @@
<label for="note" class="text-sm font-medium text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="checkout-note", lang=lang | default(value='sk')) }}</label>
{{ ui::textarea(name="note", id="note", rows="3") }}
</div>
{% if logged_in_customer %}
<!-- logged-in customers can persist this address to their profile for next time -->
{{ ui::checkbox(name="save_profile", id="save_profile", label=t(key="checkout-save-profile", lang=lang | default(value='sk')), checked=true) }}
{% endif %}
</div>
<!-- summary -->

View File

@@ -31,6 +31,7 @@ mod m20260617_000001_add_carrier_to_shipping_methods;
mod m20260617_000002_add_shipment_to_orders;
mod m20260617_000003_add_phone_to_orders;
mod m20260618_000001_o_auth2_sessions;
mod m20260618_000002_customer_profiles;
pub struct Migrator;
#[async_trait::async_trait]
@@ -66,6 +67,7 @@ impl MigratorTrait for Migrator {
Box::new(m20260617_000002_add_shipment_to_orders::Migration),
Box::new(m20260617_000003_add_phone_to_orders::Migration),
Box::new(m20260618_000001_o_auth2_sessions::Migration),
Box::new(m20260618_000002_customer_profiles::Migration),
// inject-above (do not remove this comment)
]
}

View File

@@ -0,0 +1,44 @@
use loco_rs::schema::*;
use sea_orm_migration::prelude::*;
#[derive(DeriveMigrationName)]
pub struct Migration;
#[async_trait::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, m: &SchemaManager) -> Result<(), DbErr> {
// One shipping/contact profile per customer, used to prefill the
// checkout form. `name`/`email` already live on `users`; this table
// holds only the address + phone fields. `user` adds a user_id FK; the
// unique index below makes the relationship 1:1.
create_table(
m,
"customer_profiles",
&[
("id", ColType::PkAuto),
("phone_prefix", ColType::StringNull),
("phone", ColType::StringNull),
("address", ColType::StringNull),
("city", ColType::StringNull),
("zip", ColType::StringNull),
("country", ColType::StringNull),
],
&[("user", "")],
)
.await?;
m.create_index(
Index::create()
.name("idx_customer_profiles_user_id_unique")
.table(Alias::new("customer_profiles"))
.col(Alias::new("user_id"))
.unique()
.to_owned(),
)
.await
}
async fn down(&self, m: &SchemaManager) -> Result<(), DbErr> {
drop_table(m, "customer_profiles").await
}
}

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),
}
}