Shop-scoped threshold rules with bilingual names, integer threshold/reduction (reduction < threshold), active windows and display order. Checkout applies the best eligible rule per shop with currency conversion; coupon/threshold/activity pricing are mutually exclusive per shop order. Reduction persists in orders.discount_minor + threshold_promotion_id and flows into payment totals; checkout idempotency covers the threshold selection. Delete archives referenced rules, hard-deletes unreferenced ones. - migration 0026: threshold_promotions + orders.threshold_promotion_id + coupon/threshold exclusivity CHECK - api: modules/promotion (CRUD, preview, checkout integration) - shared: ThresholdPromotion types, shop CRUD + preview client methods, checkout threshold_by_shop - shop-admin: promotions page + nav + en/zh locales - mall: exclusive promotion radio on checkout, live preview wiring, threshold label on order detail - tests: promotions.rs (scoping, validation, best-rule, exclusivity, activity-priced 409, totals, replay, archive-vs-delete) - openspec: archived 2026-10-19-add-threshold-promotions; spec threshold-promotions created, order/frontend specs updated
502 lines
16 KiB
Rust
502 lines
16 KiB
Rust
mod common;
|
||
|
||
use std::collections::HashMap;
|
||
|
||
use common::{
|
||
add_to_cart, client, create_shop, login_admin, register_customer, setup_sellable, spawn_app,
|
||
TestApp,
|
||
};
|
||
use serial_test::serial;
|
||
use uuid::Uuid;
|
||
|
||
fn rule_body(threshold: i64, reduction: i64) -> serde_json::Value {
|
||
serde_json::json!({
|
||
"name": {"en": "Test threshold", "zh": "测试满减"},
|
||
"currency": "USD",
|
||
"threshold_minor": threshold,
|
||
"reduction_minor": reduction,
|
||
"enabled": true,
|
||
"display_order": 0,
|
||
"starts_at": "2020-01-01T00:00:00Z",
|
||
"ends_at": "2999-01-01T00:00:00Z",
|
||
})
|
||
}
|
||
|
||
async fn create_rule(app: &TestApp, owner: &str, body: serde_json::Value) -> String {
|
||
let res = client()
|
||
.post(app.url("/api/shop/threshold-promotions"))
|
||
.bearer_auth(owner)
|
||
.json(&body)
|
||
.send()
|
||
.await
|
||
.unwrap();
|
||
assert_eq!(res.status(), 201, "create rule: {:?}", res.text().await);
|
||
res.json::<serde_json::Value>().await.unwrap()["id"]
|
||
.as_str()
|
||
.unwrap()
|
||
.to_string()
|
||
}
|
||
|
||
async fn checkout_with(
|
||
app: &TestApp,
|
||
token: &str,
|
||
coupon_by_shop: HashMap<String, String>,
|
||
threshold_by_shop: HashMap<String, String>,
|
||
idempotency_key: &str,
|
||
) -> reqwest::Response {
|
||
client()
|
||
.post(app.url("/api/orders/checkout"))
|
||
.bearer_auth(token)
|
||
.header("Idempotency-Key", idempotency_key)
|
||
.json(&serde_json::json!({
|
||
"shipping_address": {
|
||
"recipient": "Test Recipient",
|
||
"phone": "123456",
|
||
"country": "US",
|
||
"region": "CA",
|
||
"city": "San Jose",
|
||
"line1": "1 Test Way",
|
||
"postal_code": "95131"
|
||
},
|
||
"currency": "USD",
|
||
"coupon_by_shop": coupon_by_shop,
|
||
"threshold_by_shop": threshold_by_shop,
|
||
}))
|
||
.send()
|
||
.await
|
||
.unwrap()
|
||
}
|
||
|
||
#[tokio::test]
|
||
#[serial]
|
||
async fn shop_manages_only_its_own_rules() {
|
||
let app = spawn_app().await;
|
||
let admin = login_admin(&app).await;
|
||
let shop_a = create_shop(&app, &admin, "tp-own-a").await;
|
||
let shop_b = create_shop(&app, &admin, "tp-own-b").await;
|
||
let owner_a = common::make_shop_owner(&app, &admin, &shop_a).await;
|
||
let owner_b = common::make_shop_owner(&app, &admin, &shop_b).await;
|
||
|
||
let rule = create_rule(&app, &owner_a, rule_body(9900, 800)).await;
|
||
|
||
// Owner B cannot see, update or delete shop A's rule.
|
||
let res = client()
|
||
.put(app.url(&format!("/api/shop/threshold-promotions/{rule}")))
|
||
.bearer_auth(&owner_b)
|
||
.json(&rule_body(5000, 400))
|
||
.send()
|
||
.await
|
||
.unwrap();
|
||
assert_eq!(res.status(), 404);
|
||
let res = client()
|
||
.delete(app.url(&format!("/api/shop/threshold-promotions/{rule}")))
|
||
.bearer_auth(&owner_b)
|
||
.send()
|
||
.await
|
||
.unwrap();
|
||
assert_eq!(res.status(), 404);
|
||
|
||
// Shop A's list contains the rule; shop B's does not.
|
||
let list: serde_json::Value = client()
|
||
.get(app.url("/api/shop/threshold-promotions"))
|
||
.bearer_auth(&owner_a)
|
||
.send()
|
||
.await
|
||
.unwrap()
|
||
.json()
|
||
.await
|
||
.unwrap();
|
||
assert_eq!(list.as_array().unwrap().len(), 1);
|
||
let list: serde_json::Value = client()
|
||
.get(app.url("/api/shop/threshold-promotions"))
|
||
.bearer_auth(&owner_b)
|
||
.send()
|
||
.await
|
||
.unwrap()
|
||
.json()
|
||
.await
|
||
.unwrap();
|
||
assert_eq!(list.as_array().unwrap().len(), 0);
|
||
}
|
||
|
||
#[tokio::test]
|
||
#[serial]
|
||
async fn invalid_amounts_and_window_are_rejected() {
|
||
let app = spawn_app().await;
|
||
let admin = login_admin(&app).await;
|
||
let shop = create_shop(&app, &admin, "tp-invalid").await;
|
||
let owner = common::make_shop_owner(&app, &admin, &shop).await;
|
||
|
||
// Reduction not smaller than threshold.
|
||
let res = client()
|
||
.post(app.url("/api/shop/threshold-promotions"))
|
||
.bearer_auth(&owner)
|
||
.json(&rule_body(1000, 1000))
|
||
.send()
|
||
.await
|
||
.unwrap();
|
||
assert_eq!(res.status(), 400);
|
||
// Non-positive threshold.
|
||
let res = client()
|
||
.post(app.url("/api/shop/threshold-promotions"))
|
||
.bearer_auth(&owner)
|
||
.json(&rule_body(0, 1))
|
||
.send()
|
||
.await
|
||
.unwrap();
|
||
assert_eq!(res.status(), 400);
|
||
// Incomplete bilingual name.
|
||
let res = client()
|
||
.post(app.url("/api/shop/threshold-promotions"))
|
||
.bearer_auth(&owner)
|
||
.json(&serde_json::json!({
|
||
"name": {"en": "Only english"},
|
||
"currency": "USD",
|
||
"threshold_minor": 1000,
|
||
"reduction_minor": 100,
|
||
"enabled": true,
|
||
"starts_at": "2020-01-01T00:00:00Z",
|
||
"ends_at": "2999-01-01T00:00:00Z",
|
||
}))
|
||
.send()
|
||
.await
|
||
.unwrap();
|
||
assert_eq!(res.status(), 400);
|
||
// Nothing was written for this shop.
|
||
let count: i64 = sqlx::query_scalar(
|
||
"SELECT count(*) FROM threshold_promotions WHERE shop_id = $1::uuid",
|
||
)
|
||
.bind(&shop)
|
||
.fetch_one(&app.db)
|
||
.await
|
||
.unwrap();
|
||
assert_eq!(count, 0);
|
||
}
|
||
|
||
#[tokio::test]
|
||
#[serial]
|
||
async fn threshold_reduces_the_shop_order_total() {
|
||
let app = spawn_app().await;
|
||
let admin = login_admin(&app).await;
|
||
let (owner, shop_id, _, sku_id) = setup_sellable(&app, &admin, "tp-apply", 10000, 10).await;
|
||
let rule = create_rule(&app, &owner, rule_body(9900, 800)).await;
|
||
let (token, _) = register_customer(&app, "tp-apply").await;
|
||
add_to_cart(&app, &token, &sku_id, 1).await;
|
||
|
||
let res = checkout_with(
|
||
&app,
|
||
&token,
|
||
HashMap::new(),
|
||
HashMap::from([(shop_id.clone(), rule.clone())]),
|
||
&Uuid::new_v4().to_string(),
|
||
)
|
||
.await;
|
||
assert_eq!(res.status(), 201, "checkout: {:?}", res.text().await);
|
||
let body: serde_json::Value = res.json().await.unwrap();
|
||
let order = &body["orders"][0];
|
||
assert_eq!(order["discount_minor"], 800);
|
||
assert_eq!(order["threshold_promotion_id"], rule);
|
||
assert!(order["coupon_id"].is_null());
|
||
// Subtotal 10000 − 800 + shipping, persisted server-side.
|
||
let total = order["total_minor"].as_i64().unwrap();
|
||
let shipping = order["shipping_fee_minor"].as_i64().unwrap();
|
||
assert_eq!(total, 10000 - 800 + shipping);
|
||
|
||
// The payment created for the checkout charges exactly the reduced total.
|
||
let payment_id = body["payment_id"].as_str().unwrap();
|
||
let charged: i64 = sqlx::query_scalar(
|
||
"SELECT total_minor FROM payments WHERE id = $1::uuid",
|
||
)
|
||
.bind(payment_id)
|
||
.fetch_one(&app.db)
|
||
.await
|
||
.unwrap();
|
||
assert_eq!(charged, total);
|
||
}
|
||
|
||
#[tokio::test]
|
||
#[serial]
|
||
async fn below_threshold_and_coupon_conflict_are_rejected() {
|
||
let app = spawn_app().await;
|
||
let admin = login_admin(&app).await;
|
||
let (owner, shop_id, _, sku_id) = setup_sellable(&app, &admin, "tp-reject", 10000, 10).await;
|
||
let high_rule = create_rule(&app, &owner, rule_body(20000, 1000)).await;
|
||
let rule = create_rule(&app, &owner, rule_body(9900, 800)).await;
|
||
// A claimable coupon for the same shop.
|
||
let template_res = client()
|
||
.post(app.url("/api/shop/coupon-templates"))
|
||
.bearer_auth(&owner)
|
||
.json(&serde_json::json!({
|
||
"title": {"en": "Coupon", "zh": "优惠券"},
|
||
"amount_minor": 500,
|
||
"threshold_minor": 0,
|
||
"currency": "USD",
|
||
"stock": 5,
|
||
"enabled": true,
|
||
"starts_at": "2020-01-01T00:00:00Z",
|
||
"ends_at": "2999-01-01T00:00:00Z",
|
||
}))
|
||
.send()
|
||
.await
|
||
.unwrap();
|
||
let template_id = template_res.json::<serde_json::Value>().await.unwrap()["id"]
|
||
.as_str()
|
||
.unwrap()
|
||
.to_string();
|
||
|
||
let (token, user_id) = register_customer(&app, "tp-reject").await;
|
||
// Claim the coupon.
|
||
let res = client()
|
||
.post(app.url("/api/me/coupons"))
|
||
.bearer_auth(&token)
|
||
.json(&serde_json::json!({ "template_id": template_id }))
|
||
.send()
|
||
.await
|
||
.unwrap();
|
||
assert_eq!(res.status(), 201);
|
||
let coupon_id = res.json::<serde_json::Value>().await.unwrap()["id"]
|
||
.as_str()
|
||
.unwrap()
|
||
.to_string();
|
||
|
||
add_to_cart(&app, &token, &sku_id, 1).await;
|
||
|
||
// Subtotal 10000 below the 20000 threshold → 409, no orders.
|
||
let res = checkout_with(
|
||
&app,
|
||
&token,
|
||
HashMap::new(),
|
||
HashMap::from([(shop_id.clone(), high_rule)]),
|
||
&Uuid::new_v4().to_string(),
|
||
)
|
||
.await;
|
||
assert_eq!(res.status(), 409, "below threshold: {:?}", res.text().await);
|
||
|
||
// Coupon and threshold together → 409, no orders.
|
||
let res = checkout_with(
|
||
&app,
|
||
&token,
|
||
HashMap::from([(shop_id.clone(), coupon_id)]),
|
||
HashMap::from([(shop_id.clone(), rule)]),
|
||
&Uuid::new_v4().to_string(),
|
||
)
|
||
.await;
|
||
assert_eq!(res.status(), 409, "conflict: {:?}", res.text().await);
|
||
|
||
let orders: i64 = sqlx::query_scalar("SELECT count(*) FROM orders WHERE user_id = $1::uuid")
|
||
.bind(&user_id)
|
||
.fetch_one(&app.db)
|
||
.await
|
||
.unwrap();
|
||
assert_eq!(orders, 0);
|
||
}
|
||
|
||
#[tokio::test]
|
||
#[serial]
|
||
async fn activity_priced_shop_order_rejects_a_threshold() {
|
||
let app = spawn_app().await;
|
||
let admin = login_admin(&app).await;
|
||
let (owner, shop_id, _, sku_id) = setup_sellable(&app, &admin, "tp-flash", 10000, 10).await;
|
||
let rule = create_rule(&app, &owner, rule_body(9900, 800)).await;
|
||
|
||
// Put the SKU into an active flash sale so the shop order is activity priced.
|
||
let res = client()
|
||
.post(app.url("/api/shop/flash-sales"))
|
||
.bearer_auth(&owner)
|
||
.json(&serde_json::json!({
|
||
"label": {"en": "Flash", "zh": "秒杀"},
|
||
"starts_at": "2020-01-01T00:00:00Z",
|
||
"ends_at": "2999-01-01T00:00:00Z",
|
||
"enabled": true,
|
||
}))
|
||
.send()
|
||
.await
|
||
.unwrap();
|
||
assert_eq!(res.status(), 201);
|
||
let session_id = res.json::<serde_json::Value>().await.unwrap()["id"]
|
||
.as_str()
|
||
.unwrap()
|
||
.to_string();
|
||
let res = client()
|
||
.post(app.url(&format!("/api/shop/flash-sales/{session_id}/items")))
|
||
.bearer_auth(&owner)
|
||
.json(&serde_json::json!({
|
||
"sku_id": sku_id,
|
||
"sale_price_minor": 8000,
|
||
"currency": "USD",
|
||
"reserved_stock": 5,
|
||
"per_customer_limit": 2,
|
||
}))
|
||
.send()
|
||
.await
|
||
.unwrap();
|
||
assert_eq!(res.status(), 201, "add item: {:?}", res.text().await);
|
||
|
||
let (token, user_id) = register_customer(&app, "tp-flash").await;
|
||
add_to_cart(&app, &token, &sku_id, 1).await;
|
||
|
||
let res = checkout_with(
|
||
&app,
|
||
&token,
|
||
HashMap::new(),
|
||
HashMap::from([(shop_id.clone(), rule)]),
|
||
&Uuid::new_v4().to_string(),
|
||
)
|
||
.await;
|
||
assert_eq!(res.status(), 409, "activity priced: {:?}", res.text().await);
|
||
|
||
let orders: i64 = sqlx::query_scalar("SELECT count(*) FROM orders WHERE user_id = $1::uuid")
|
||
.bind(&user_id)
|
||
.fetch_one(&app.db)
|
||
.await
|
||
.unwrap();
|
||
assert_eq!(orders, 0);
|
||
}
|
||
|
||
#[tokio::test]
|
||
#[serial]
|
||
async fn preview_reports_the_best_eligible_rule() {
|
||
let app = spawn_app().await;
|
||
let admin = login_admin(&app).await;
|
||
let (owner, shop_id, _, sku_id) = setup_sellable(&app, &admin, "tp-preview", 10000, 10).await;
|
||
create_rule(&app, &owner, rule_body(9900, 800)).await;
|
||
let better = create_rule(&app, &owner, rule_body(9900, 1200)).await;
|
||
create_rule(&app, &owner, rule_body(50000, 9000)).await;
|
||
|
||
let (token, _) = register_customer(&app, "tp-preview").await;
|
||
add_to_cart(&app, &token, &sku_id, 1).await;
|
||
|
||
let res = client()
|
||
.get(app.url("/api/checkout/threshold-preview?currency=USD"))
|
||
.bearer_auth(&token)
|
||
.send()
|
||
.await
|
||
.unwrap();
|
||
assert_eq!(res.status(), 200, "preview: {:?}", res.text().await);
|
||
let body: serde_json::Value = res.json().await.unwrap();
|
||
let shops = body.as_array().unwrap();
|
||
let entry = shops
|
||
.iter()
|
||
.find(|s| s["shop_id"] == shop_id)
|
||
.expect("preview covers the cart shop");
|
||
assert_eq!(entry["subtotal_minor"], 10000);
|
||
// Highest eligible reduction wins; the 50000-threshold rule is ineligible.
|
||
assert_eq!(entry["best"]["id"], better);
|
||
assert_eq!(entry["best"]["converted_reduction_minor"], 1200);
|
||
}
|
||
|
||
#[tokio::test]
|
||
#[serial]
|
||
async fn replay_and_changed_selection_follow_idempotency() {
|
||
let app = spawn_app().await;
|
||
let admin = login_admin(&app).await;
|
||
let (owner, shop_id, _, sku_id) = setup_sellable(&app, &admin, "tp-replay", 10000, 10).await;
|
||
let rule = create_rule(&app, &owner, rule_body(9900, 800)).await;
|
||
let (token, user_id) = register_customer(&app, "tp-replay").await;
|
||
add_to_cart(&app, &token, &sku_id, 1).await;
|
||
|
||
let key = Uuid::new_v4().to_string();
|
||
let res = checkout_with(
|
||
&app,
|
||
&token,
|
||
HashMap::new(),
|
||
HashMap::from([(shop_id.clone(), rule.clone())]),
|
||
&key,
|
||
)
|
||
.await;
|
||
assert_eq!(res.status(), 201);
|
||
let first: serde_json::Value = res.json().await.unwrap();
|
||
|
||
// Identical replay returns the durable result without new orders.
|
||
let res = checkout_with(
|
||
&app,
|
||
&token,
|
||
HashMap::new(),
|
||
HashMap::from([(shop_id.clone(), rule.clone())]),
|
||
&key,
|
||
)
|
||
.await;
|
||
assert_eq!(res.status(), 201, "replay: {:?}", res.text().await);
|
||
let replayed: serde_json::Value = res.json().await.unwrap();
|
||
assert_eq!(first["payment_id"], replayed["payment_id"]);
|
||
|
||
// Changed selection with the same key is a 409.
|
||
let res = checkout_with(&app, &token, HashMap::new(), HashMap::new(), &key).await;
|
||
assert_eq!(res.status(), 409);
|
||
|
||
let orders: i64 = sqlx::query_scalar("SELECT count(*) FROM orders WHERE user_id = $1::uuid")
|
||
.bind(&user_id)
|
||
.fetch_one(&app.db)
|
||
.await
|
||
.unwrap();
|
||
assert_eq!(orders, 1);
|
||
}
|
||
|
||
#[tokio::test]
|
||
#[serial]
|
||
async fn referenced_rule_is_archived_not_deleted() {
|
||
let app = spawn_app().await;
|
||
let admin = login_admin(&app).await;
|
||
let (owner, shop_id, _, sku_id) = setup_sellable(&app, &admin, "tp-arch", 10000, 10).await;
|
||
let referenced = create_rule(&app, &owner, rule_body(9900, 800)).await;
|
||
let stray = create_rule(&app, &owner, rule_body(5000, 400)).await;
|
||
|
||
let (token, _) = register_customer(&app, "tp-arch").await;
|
||
add_to_cart(&app, &token, &sku_id, 1).await;
|
||
let res = checkout_with(
|
||
&app,
|
||
&token,
|
||
HashMap::new(),
|
||
HashMap::from([(shop_id.clone(), referenced.clone())]),
|
||
&Uuid::new_v4().to_string(),
|
||
)
|
||
.await;
|
||
assert_eq!(res.status(), 201);
|
||
|
||
// Deleting a referenced rule archives it and disables it.
|
||
let res = client()
|
||
.delete(app.url(&format!("/api/shop/threshold-promotions/{referenced}")))
|
||
.bearer_auth(&owner)
|
||
.send()
|
||
.await
|
||
.unwrap();
|
||
assert_eq!(res.status(), 204);
|
||
let (archived, enabled): (bool, bool) =
|
||
sqlx::query_as("SELECT archived, enabled FROM threshold_promotions WHERE id = $1::uuid")
|
||
.bind(&referenced)
|
||
.fetch_one(&app.db)
|
||
.await
|
||
.unwrap();
|
||
assert!(archived && !enabled);
|
||
|
||
// Deleting an unreferenced rule removes the row.
|
||
let res = client()
|
||
.delete(app.url(&format!("/api/shop/threshold-promotions/{stray}")))
|
||
.bearer_auth(&owner)
|
||
.send()
|
||
.await
|
||
.unwrap();
|
||
assert_eq!(res.status(), 204);
|
||
let gone: bool = sqlx::query_scalar(
|
||
"SELECT NOT EXISTS(SELECT 1 FROM threshold_promotions WHERE id = $1::uuid)",
|
||
)
|
||
.bind(&stray)
|
||
.fetch_one(&app.db)
|
||
.await
|
||
.unwrap();
|
||
assert!(gone);
|
||
|
||
// The archived rule no longer applies to a new checkout.
|
||
let (token2, _) = register_customer(&app, "tp-arch-2").await;
|
||
add_to_cart(&app, &token2, &sku_id, 1).await;
|
||
let res = checkout_with(
|
||
&app,
|
||
&token2,
|
||
HashMap::new(),
|
||
HashMap::from([(shop_id.clone(), referenced)]),
|
||
&Uuid::new_v4().to_string(),
|
||
)
|
||
.await;
|
||
assert_eq!(res.status(), 409, "archived: {:?}", res.text().await);
|
||
}
|