hardcode of dpd and packeta

This commit is contained in:
Priec
2026-06-17 17:27:19 +02:00
parent e8c0362a54
commit cd7a756a54
24 changed files with 694 additions and 152 deletions

View File

@@ -1,4 +1,4 @@
//! Admin order list, detail, and status updates.
//! Admin order list, detail, status updates, and manual carrier dispatch.
use axum_extra::extract::cookie::CookieJar;
use loco_rs::prelude::*;
@@ -7,7 +7,8 @@ use serde::Deserialize;
use serde_json::json;
use crate::{
models::{order_items, orders},
integrations::{self, ShipmentRequest},
models::{order_items, orders, shipping_methods},
views::checkout as view,
controllers::i18n::current_lang,
shared::{guard, settings},
@@ -15,6 +16,9 @@ use crate::{
pub(crate) const ORDER_STATUSES: [&str; 4] = ["pending", "paid", "shipped", "cancelled"];
/// Fallback parcel weight when products carry no weight of their own.
const DEFAULT_PARCEL_WEIGHT_GRAMS: i32 = 1000;
#[derive(Debug, Deserialize)]
struct StatusForm {
status: String,
@@ -40,15 +44,28 @@ async fn index(
)
}
#[debug_handler]
async fn show(
auth: auth::JWT,
jar: CookieJar,
ViewEngine(v): ViewEngine<TeraView>,
Path(id): Path<i32>,
State(ctx): State<AppContext>,
/// Resolve the carrier code (`none`/`packeta`/`dpd`/`dhl`) for an order from its
/// chosen shipping method, defaulting to `none` when unknown.
async fn order_carrier(ctx: &AppContext, order: &orders::Model) -> Result<String> {
let Some(code) = order.carrier_code.as_deref() else {
return Ok("none".to_string());
};
Ok(shipping_methods::Entity::find()
.filter(shipping_methods::Column::Code.eq(code))
.one(&ctx.db)
.await?
.map(|m| m.carrier)
.unwrap_or_else(|| "none".to_string()))
}
/// Render the order detail page, optionally with a dispatch error banner.
async fn render_show(
jar: &CookieJar,
v: &TeraView,
ctx: &AppContext,
id: i32,
error: Option<String>,
) -> Result<Response> {
guard::current_admin(auth, &ctx).await?;
let order = orders::Entity::find_by_id(id)
.one(&ctx.db)
.await?
@@ -58,22 +75,42 @@ async fn show(
.all(&ctx.db)
.await?;
let carrier = order_carrier(ctx, &order).await?;
// The order can be sent only if it maps to a real carrier and hasn't been
// dispatched yet.
let can_ship = carrier != "none" && order.tracking_number.is_none();
format::view(
&v,
v,
"admin/orders/show.html",
json!({
"order": view::detail(
&order,
settings::get(&ctx, "bank_iban").unwrap_or(""),
settings::get(&ctx, "bank_account_name").unwrap_or(""),
settings::get(ctx, "bank_iban").unwrap_or(""),
settings::get(ctx, "bank_account_name").unwrap_or(""),
),
"items": view::items(&items),
"statuses": ORDER_STATUSES,
"lang": current_lang(&jar),
"carrier": carrier,
"can_ship": can_ship,
"ship_error": error,
"lang": current_lang(jar),
}),
)
}
#[debug_handler]
async fn show(
auth: auth::JWT,
jar: CookieJar,
ViewEngine(v): ViewEngine<TeraView>,
Path(id): Path<i32>,
State(ctx): State<AppContext>,
) -> Result<Response> {
guard::current_admin(auth, &ctx).await?;
render_show(&jar, &v, &ctx, id, None).await
}
#[debug_handler]
async fn update_status(
auth: auth::JWT,
@@ -96,9 +133,82 @@ async fn update_status(
format::redirect(&format!("/admin/orders/{id}"))
}
/// Manually dispatch an order to its carrier. This is the *only* place that
/// calls a carrier API, and it is triggered exclusively by an admin clicking
/// "Send to carrier" after the goods are verified and ready.
#[debug_handler]
async fn ship(
auth: auth::JWT,
jar: CookieJar,
ViewEngine(v): ViewEngine<TeraView>,
Path(id): Path<i32>,
State(ctx): State<AppContext>,
) -> Result<Response> {
guard::current_admin(auth, &ctx).await?;
let order = orders::Entity::find_by_id(id)
.one(&ctx.db)
.await?
.ok_or_else(|| Error::NotFound)?;
// Idempotency: never create a second shipment for an already-dispatched order.
if order.tracking_number.is_some() {
return render_show(
&jar,
&v,
&ctx,
id,
Some("This order has already been sent to the carrier.".to_string()),
)
.await;
}
let carrier = order_carrier(&ctx, &order).await?;
let goods_value = (order.total_cents - order.shipping_cents).max(0);
let cod_cents = match order.payment_method.as_deref() {
Some("cod") => order.total_cents,
_ => 0,
};
let recipient = order
.customer_name
.as_deref()
.filter(|s| !s.is_empty())
.unwrap_or(&order.email);
let req = ShipmentRequest {
order_number: &order.order_number,
recipient_name: recipient,
email: &order.email,
address: order.address.as_deref(),
city: order.city.as_deref(),
zip: order.zip.as_deref(),
country: order.country.as_deref(),
pickup_point_id: order.pickup_point_id.as_deref(),
cod_cents,
currency: &order.currency,
value_cents: goods_value,
weight_grams: DEFAULT_PARCEL_WEIGHT_GRAMS,
};
match integrations::create_shipment(&ctx, &carrier, req).await {
Ok(result) => {
let mut active = order.into_active_model();
active.tracking_number = Set(Some(result.tracking_number));
active.shipment_id = Set(Some(result.shipment_id));
active.label_url = Set(result.label_url);
active.status = Set("shipped".to_string());
active.update(&ctx.db).await?;
format::redirect(&format!("/admin/orders/{id}"))
}
// Show the carrier's error in-page rather than a generic error screen,
// so the admin can fix the cause and retry.
Err(err) => render_show(&jar, &v, &ctx, id, Some(err.to_string())).await,
}
}
pub fn routes() -> Routes {
Routes::new()
.add("/admin/orders", get(index))
.add("/admin/orders/{id}", get(show))
.add("/admin/orders/{id}/status", post(update_status))
.add("/admin/orders/{id}/ship", post(ship))
}

View File

@@ -1,11 +1,12 @@
//! Admin management of shipping methods: add, edit (price + enabled), remove.
//! Admin management of the built-in delivery options (Packeta, DPD).
//!
//! The options themselves are fixed and seeded by `initializers::shipping_seeder`
//! — they cannot be added or removed here. The admin only sets each one's price
//! and toggles whether it is offered at checkout.
use axum_extra::extract::cookie::CookieJar;
use loco_rs::prelude::*;
use sea_orm::{
ActiveModelTrait, ColumnTrait, EntityTrait, ModelTrait, PaginatorTrait, QueryFilter,
QueryOrder, Set,
};
use sea_orm::{ActiveModelTrait, EntityTrait, QueryOrder, Set};
use serde::Deserialize;
use serde_json::json;
@@ -15,7 +16,6 @@ use crate::{
shared::{
guard,
money::{format_price, parse_price_to_cents},
slug::{slugify, unique_slug},
},
};
@@ -25,14 +25,6 @@ struct ShippingForm {
enabled: Option<String>,
}
#[derive(Debug, Deserialize)]
struct NewShippingForm {
name: String,
price: String,
requires_pickup_point: Option<String>,
enabled: Option<String>,
}
fn is_checked(value: &Option<String>) -> bool {
matches!(value.as_deref(), Some("on" | "true" | "1"))
}
@@ -57,6 +49,7 @@ async fn index(
"code": m.code,
"name": m.name,
"price": format_price(m.price_cents),
"carrier": m.carrier,
"requires_pickup_point": m.requires_pickup_point,
"enabled": m.enabled,
})
@@ -69,48 +62,6 @@ async fn index(
)
}
#[debug_handler]
async fn create(
auth: auth::JWT,
State(ctx): State<AppContext>,
Form(form): Form<NewShippingForm>,
) -> Result<Response> {
guard::current_admin(auth, &ctx).await?;
let name = form.name.trim().to_string();
if name.is_empty() {
return Err(Error::BadRequest("name is required".to_string()));
}
// Stable unique `code` derived from the name; it's what checkout submits and
// what an order stores, so it must not collide with an existing method.
let code = unique_slug(&slugify(&name), |candidate| {
let ctx = ctx.clone();
async move {
Ok(shipping_methods::Entity::find()
.filter(shipping_methods::Column::Code.eq(candidate))
.count(&ctx.db)
.await?
> 0)
}
})
.await?;
// Append after existing methods.
let position = shipping_methods::Entity::find().count(&ctx.db).await? as i32;
shipping_methods::ActiveModel {
code: Set(code),
name: Set(name),
price_cents: Set(parse_price_to_cents(&form.price)?),
requires_pickup_point: Set(is_checked(&form.requires_pickup_point)),
enabled: Set(is_checked(&form.enabled)),
position: Set(position),
..Default::default()
}
.insert(&ctx.db)
.await?;
format::redirect("/admin/shipping")
}
#[debug_handler]
async fn update(
auth: auth::JWT,
@@ -130,25 +81,8 @@ async fn update(
format::redirect("/admin/shipping")
}
#[debug_handler]
async fn delete(
auth: auth::JWT,
Path(id): Path<i32>,
State(ctx): State<AppContext>,
) -> Result<Response> {
guard::current_admin(auth, &ctx).await?;
let method = shipping_methods::Entity::find_by_id(id)
.one(&ctx.db)
.await?
.ok_or_else(|| Error::NotFound)?;
method.delete(&ctx.db).await?;
format::redirect("/admin/shipping")
}
pub fn routes() -> Routes {
Routes::new()
.add("/admin/shipping", get(index))
.add("/admin/shipping", post(create))
.add("/admin/shipping/{id}", post(update))
.add("/admin/shipping/{id}/delete", post(delete))
}