personal discounts to businesses done
This commit is contained in:
175
src/controllers/admin_customers.rs
Normal file
175
src/controllers/admin_customers.rs
Normal file
@@ -0,0 +1,175 @@
|
||||
//! Admin management of business (company) accounts and their negotiated prices.
|
||||
//!
|
||||
//! Phase 1: list company accounts and, per account, set/clear a manually
|
||||
//! negotiated price per product ("personal agreement"). The effective price the
|
||||
//! business pays is always resolved by [`crate::shared::pricing`] (lowest of the
|
||||
//! public price and the negotiated price), shown here for reference.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use axum_extra::extract::cookie::CookieJar;
|
||||
use loco_rs::prelude::*;
|
||||
use sea_orm::{ColumnTrait, EntityTrait, PaginatorTrait, QueryFilter, QueryOrder};
|
||||
use serde::Deserialize;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::{
|
||||
controllers::i18n::current_lang,
|
||||
models::{account_product_prices, products, _entities::users},
|
||||
shared::{
|
||||
guard,
|
||||
money::{format_price, parse_price_to_cents},
|
||||
pricing,
|
||||
},
|
||||
};
|
||||
|
||||
const COMPANY: &str = "company";
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct PriceForm {
|
||||
price: String,
|
||||
}
|
||||
|
||||
async fn company_by_id(ctx: &AppContext, id: i32) -> Result<users::Model> {
|
||||
let user = users::Entity::find_by_id(id)
|
||||
.one(&ctx.db)
|
||||
.await?
|
||||
.ok_or_else(|| Error::NotFound)?;
|
||||
// Negotiated pricing only applies to company accounts.
|
||||
if user.account_type != COMPANY {
|
||||
return Err(Error::NotFound);
|
||||
}
|
||||
Ok(user)
|
||||
}
|
||||
|
||||
#[debug_handler]
|
||||
async fn index(
|
||||
auth: auth::JWT,
|
||||
jar: CookieJar,
|
||||
ViewEngine(v): ViewEngine<TeraView>,
|
||||
State(ctx): State<AppContext>,
|
||||
) -> Result<Response> {
|
||||
guard::current_admin(auth, &ctx).await?;
|
||||
let companies = users::Entity::find()
|
||||
.filter(users::Column::AccountType.eq(COMPANY))
|
||||
.order_by_asc(users::Column::Name)
|
||||
.all(&ctx.db)
|
||||
.await?;
|
||||
|
||||
let mut rows = Vec::with_capacity(companies.len());
|
||||
for company in &companies {
|
||||
let negotiated = account_product_prices::Entity::find()
|
||||
.filter(account_product_prices::Column::UserId.eq(company.id))
|
||||
.count(&ctx.db)
|
||||
.await?;
|
||||
rows.push(json!({
|
||||
"id": company.id,
|
||||
"name": company.name,
|
||||
"email": company.email,
|
||||
"negotiated_count": negotiated,
|
||||
}));
|
||||
}
|
||||
|
||||
format::view(
|
||||
&v,
|
||||
"admin/customers/index.html",
|
||||
json!({ "customers": rows, "lang": current_lang(&jar) }),
|
||||
)
|
||||
}
|
||||
|
||||
#[debug_handler]
|
||||
async fn show(
|
||||
auth: auth::JWT,
|
||||
jar: CookieJar,
|
||||
ViewEngine(v): ViewEngine<TeraView>,
|
||||
Path(id): Path<i32>,
|
||||
Query(params): Query<HashMap<String, String>>,
|
||||
State(ctx): State<AppContext>,
|
||||
) -> Result<Response> {
|
||||
guard::current_admin(auth, &ctx).await?;
|
||||
let company = company_by_id(&ctx, id).await?;
|
||||
|
||||
let list = products::Entity::find()
|
||||
.order_by_asc(products::Column::Name)
|
||||
.all(&ctx.db)
|
||||
.await?;
|
||||
let priced = pricing::price_many(&ctx, &list, Some(&company)).await?;
|
||||
let manual = account_product_prices::Model::map_for_user(&ctx.db, company.id).await?;
|
||||
|
||||
let rows: Vec<serde_json::Value> = list
|
||||
.iter()
|
||||
.zip(priced.iter())
|
||||
.map(|(product, priced)| {
|
||||
json!({
|
||||
"product_id": product.id,
|
||||
"name": product.name,
|
||||
"currency": product.currency,
|
||||
"regular_price": format_price(product.price_cents),
|
||||
"public_price": format_price(product.effective_price_cents()),
|
||||
"on_public_sale": product.on_sale(),
|
||||
"manual_price": manual.get(&product.id).copied().map(format_price),
|
||||
"effective_price": format_price(priced.price_cents),
|
||||
"is_business": priced.is_business,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
format::view(
|
||||
&v,
|
||||
"admin/customers/show.html",
|
||||
json!({
|
||||
"customer": { "id": company.id, "name": company.name, "email": company.email },
|
||||
"products": rows,
|
||||
"error": params.get("error"),
|
||||
"lang": current_lang(&jar),
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
#[debug_handler]
|
||||
async fn set_price(
|
||||
auth: auth::JWT,
|
||||
Path((id, product_id)): Path<(i32, i32)>,
|
||||
State(ctx): State<AppContext>,
|
||||
Form(form): Form<PriceForm>,
|
||||
) -> Result<Response> {
|
||||
guard::current_admin(auth, &ctx).await?;
|
||||
let company = company_by_id(&ctx, id).await?;
|
||||
|
||||
let entered = form.price.trim().to_string();
|
||||
// An empty value clears the negotiated price (same as the Remove action).
|
||||
if entered.is_empty() {
|
||||
account_product_prices::Model::clear(&ctx.db, company.id, product_id).await?;
|
||||
return format::redirect(&format!("/admin/customers/{id}"));
|
||||
}
|
||||
|
||||
let cents = match parse_price_to_cents(&entered) {
|
||||
Ok(cents) if cents > 0 => cents,
|
||||
_ => return format::redirect(&format!("/admin/customers/{id}?error=discount-must-be-positive")),
|
||||
};
|
||||
account_product_prices::Model::upsert(&ctx.db, company.id, product_id, cents).await?;
|
||||
format::redirect(&format!("/admin/customers/{id}"))
|
||||
}
|
||||
|
||||
#[debug_handler]
|
||||
async fn remove_price(
|
||||
auth: auth::JWT,
|
||||
Path((id, product_id)): Path<(i32, i32)>,
|
||||
State(ctx): State<AppContext>,
|
||||
) -> Result<Response> {
|
||||
guard::current_admin(auth, &ctx).await?;
|
||||
let company = company_by_id(&ctx, id).await?;
|
||||
account_product_prices::Model::clear(&ctx.db, company.id, product_id).await?;
|
||||
format::redirect(&format!("/admin/customers/{id}"))
|
||||
}
|
||||
|
||||
pub fn routes() -> Routes {
|
||||
Routes::new()
|
||||
.add("/admin/customers", get(index))
|
||||
.add("/admin/customers/{id}", get(show))
|
||||
.add("/admin/customers/{id}/prices/{product_id}", post(set_price))
|
||||
.add(
|
||||
"/admin/customers/{id}/prices/{product_id}/remove",
|
||||
post(remove_price),
|
||||
)
|
||||
}
|
||||
@@ -18,6 +18,7 @@ use crate::{
|
||||
shared::{
|
||||
guard,
|
||||
money::parse_price_to_cents,
|
||||
pricing,
|
||||
slug::{slugify, unique_slug},
|
||||
},
|
||||
models::{categories, product_images, products},
|
||||
@@ -129,7 +130,8 @@ async fn index(
|
||||
.map(|c| c.name),
|
||||
None => None,
|
||||
};
|
||||
rows.push(view::product_card(&product, image, category_name));
|
||||
let priced = pricing::price_for(&ctx, &product, None).await?;
|
||||
rows.push(view::product_card(&product, &priced, image, category_name));
|
||||
}
|
||||
format::view(
|
||||
&v,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::{controllers::i18n::current_lang, shared::{guard, money::format_price}, models::products};
|
||||
use crate::{controllers::i18n::current_lang, shared::{guard, money::format_price, pricing}, models::products};
|
||||
use axum::{
|
||||
http::{HeaderMap, StatusCode},
|
||||
response::Redirect,
|
||||
@@ -189,10 +189,10 @@ pub(crate) async fn resolve_cart(
|
||||
ctx: &AppContext,
|
||||
jar: &CookieJar,
|
||||
) -> Result<(Vec<serde_json::Value>, Vec<(i32, i32)>, i64)> {
|
||||
let mut lines = Vec::new();
|
||||
let mut valid = Vec::new();
|
||||
let mut total: i64 = 0;
|
||||
|
||||
// Resolve the cart entries to in-stock products first, then price them all
|
||||
// for the current viewer in one batch (the price depends on who's logged in).
|
||||
let user = guard::current_user(ctx, jar).await;
|
||||
let mut items: Vec<(products::Model, i32)> = Vec::new();
|
||||
for (id, qty) in parse_cart(jar) {
|
||||
let Some(product) = published_product(ctx, id).await? else {
|
||||
continue;
|
||||
@@ -201,15 +201,26 @@ pub(crate) async fn resolve_cart(
|
||||
if qty == 0 {
|
||||
continue;
|
||||
}
|
||||
let unit_price = product.effective_price_cents();
|
||||
let line_total = unit_price * i64::from(qty);
|
||||
items.push((product, qty));
|
||||
}
|
||||
let products_only: Vec<products::Model> = items.iter().map(|(p, _)| p.clone()).collect();
|
||||
let priced = pricing::price_many(ctx, &products_only, user.as_ref()).await?;
|
||||
|
||||
let mut lines = Vec::new();
|
||||
let mut valid = Vec::new();
|
||||
let mut total: i64 = 0;
|
||||
for ((product, qty), priced) in items.iter().zip(priced.iter()) {
|
||||
let unit_price = priced.price_cents;
|
||||
let line_total = unit_price * i64::from(*qty);
|
||||
total += line_total;
|
||||
valid.push((product.id, qty));
|
||||
valid.push((product.id, *qty));
|
||||
lines.push(json!({
|
||||
"id": product.id,
|
||||
"name": product.name,
|
||||
"slug": product.slug,
|
||||
"price": format_price(unit_price),
|
||||
"regular_price": format_price(priced.regular_cents),
|
||||
"on_sale": priced.is_reduced(),
|
||||
"currency": product.currency,
|
||||
"quantity": qty,
|
||||
"stock": product.stock,
|
||||
|
||||
@@ -331,6 +331,7 @@ async fn place_order(
|
||||
pickup_point_id,
|
||||
pickup_point_name,
|
||||
},
|
||||
logged_in_customer,
|
||||
)
|
||||
.await?;
|
||||
|
||||
|
||||
@@ -12,8 +12,9 @@ async fn index(
|
||||
ViewEngine(v): ViewEngine<TeraView>,
|
||||
State(ctx): State<AppContext>,
|
||||
) -> Result<Response> {
|
||||
let products = shop::featured_products(&ctx, 8).await?;
|
||||
let c = guard::chrome(&ctx, &jar).await;
|
||||
let user = guard::current_user(&ctx, &jar).await;
|
||||
let products = shop::featured_products(&ctx, user.as_ref(), 8).await?;
|
||||
let c = guard::chrome_from(&ctx, user.as_ref());
|
||||
|
||||
format::view(
|
||||
&v,
|
||||
|
||||
@@ -3,6 +3,7 @@ pub mod auth;
|
||||
pub mod auth_pages;
|
||||
pub mod oauth2;
|
||||
pub mod admin_categories;
|
||||
pub mod admin_customers;
|
||||
pub mod admin_dashboard;
|
||||
pub mod admin_discounts;
|
||||
pub mod admin_form;
|
||||
|
||||
@@ -8,17 +8,23 @@ use serde_json::json;
|
||||
|
||||
use crate::{
|
||||
controllers::i18n::current_lang,
|
||||
shared::guard,
|
||||
models::{categories, product_images, products},
|
||||
shared::{guard, pricing},
|
||||
models::{categories, product_images, products, users},
|
||||
views::shop as view,
|
||||
};
|
||||
|
||||
/// Shape a list of products into card rows, loading each one's primary image.
|
||||
async fn product_rows(ctx: &AppContext, list: Vec<products::Model>) -> Result<Vec<serde_json::Value>> {
|
||||
/// Shape a list of products into card rows for `user` (None = public), pricing
|
||||
/// each via [`pricing::price_many`] and loading its primary image.
|
||||
async fn product_rows(
|
||||
ctx: &AppContext,
|
||||
user: Option<&users::Model>,
|
||||
list: Vec<products::Model>,
|
||||
) -> Result<Vec<serde_json::Value>> {
|
||||
let priced = pricing::price_many(ctx, &list, user).await?;
|
||||
let mut rows = Vec::with_capacity(list.len());
|
||||
for product in list {
|
||||
for (product, priced) in list.iter().zip(priced.iter()) {
|
||||
let image = product_images::first_for(ctx, product.id).await?;
|
||||
rows.push(view::product_card(&product, image, None));
|
||||
rows.push(view::product_card(product, priced, image, None));
|
||||
}
|
||||
Ok(rows)
|
||||
}
|
||||
@@ -27,6 +33,7 @@ async fn product_rows(ctx: &AppContext, list: Vec<products::Model>) -> Result<Ve
|
||||
/// by the home-page landing grid.
|
||||
pub(crate) async fn featured_products(
|
||||
ctx: &AppContext,
|
||||
user: Option<&users::Model>,
|
||||
limit: u64,
|
||||
) -> Result<Vec<serde_json::Value>> {
|
||||
let list = products::Entity::find()
|
||||
@@ -35,7 +42,7 @@ pub(crate) async fn featured_products(
|
||||
.limit(limit)
|
||||
.all(&ctx.db)
|
||||
.await?;
|
||||
product_rows(ctx, list).await
|
||||
product_rows(ctx, user, list).await
|
||||
}
|
||||
|
||||
/// The site-wide category sidebar, loaded lazily via htmx by the base layout so
|
||||
@@ -69,12 +76,13 @@ async fn index(
|
||||
.all(&ctx.db)
|
||||
.await?;
|
||||
|
||||
let c = guard::chrome(&ctx, &jar).await;
|
||||
let user = guard::current_user(&ctx, &jar).await;
|
||||
let c = guard::chrome_from(&ctx, user.as_ref());
|
||||
format::view(
|
||||
&v,
|
||||
"shop/index.html",
|
||||
json!({
|
||||
"products": product_rows(&ctx, list).await?,
|
||||
"products": product_rows(&ctx, user.as_ref(), list).await?,
|
||||
"logged_in_admin": c.logged_in_admin,
|
||||
"logged_in_customer": c.logged_in_customer,
|
||||
"customer_name": c.customer_name,
|
||||
@@ -112,12 +120,14 @@ async fn show(
|
||||
None => None,
|
||||
};
|
||||
|
||||
let c = guard::chrome(&ctx, &jar).await;
|
||||
let user = guard::current_user(&ctx, &jar).await;
|
||||
let priced = pricing::price_for(&ctx, &product, user.as_ref()).await?;
|
||||
let c = guard::chrome_from(&ctx, user.as_ref());
|
||||
format::view(
|
||||
&v,
|
||||
"shop/show.html",
|
||||
json!({
|
||||
"product": view::product_card(&product, None, category.as_ref().map(|c| c.name.clone())),
|
||||
"product": view::product_card(&product, &priced, 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": c.logged_in_admin,
|
||||
@@ -159,7 +169,8 @@ async fn category(
|
||||
.all(&ctx.db)
|
||||
.await?;
|
||||
|
||||
let c = guard::chrome(&ctx, &jar).await;
|
||||
let user = guard::current_user(&ctx, &jar).await;
|
||||
let c = guard::chrome_from(&ctx, user.as_ref());
|
||||
format::view(
|
||||
&v,
|
||||
"shop/category.html",
|
||||
@@ -167,7 +178,7 @@ async fn category(
|
||||
"category": category,
|
||||
"breadcrumbs": breadcrumbs,
|
||||
"children": children,
|
||||
"products": product_rows(&ctx, list).await?,
|
||||
"products": product_rows(&ctx, user.as_ref(), list).await?,
|
||||
"logged_in_admin": c.logged_in_admin,
|
||||
"logged_in_customer": c.logged_in_customer,
|
||||
"customer_name": c.customer_name,
|
||||
|
||||
Reference in New Issue
Block a user