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),
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user