Files
vmall/apps/api/tests/pricing.rs
T
Chengdong ZhangandCursor 3188bf7672 feat(pricing): price configurable products before marketing
Versioned common and linear rules compute the payable price and snapshot it on the order, with the design reference for later strategies such as agreement pricing.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-18 14:25:06 +08:00

409 lines
14 KiB
Rust

mod common;
use common::{add_to_cart, client, login_admin, register_customer, setup_sellable, spawn_app};
use serial_test::serial;
fn groups(server_product: &str) -> serde_json::Value {
serde_json::json!({
"groups": [
{
"key": "seats",
"group_type": "quantity",
"label": {"en": "Seats", "zh": "席位"},
"constraints": {"min": 5, "max": 100, "step": 5}
},
{
"key": "storage",
"group_type": "choice",
"label": {"en": "Storage", "zh": "存储"},
"constraints": {"options": [
{"key": "2t", "label": {"en": "2 TB", "zh": "2 TB"}},
{"key": "10t", "label": {"en": "10 TB", "zh": "10 TB"}}
]}
},
{
"key": "server",
"group_type": "component",
"label": {"en": "Server", "zh": "服务器"},
"constraints": {},
"component_product_id": server_product
},
{
"key": "term",
"group_type": "term",
"label": {"en": "Term", "zh": "账期"},
"constraints": {"months": [12, 24, 36]}
}
]
})
}
fn rule(seat_price: i64) -> serde_json::Value {
serde_json::json!({
"currency": "USD",
"sales_cap": 5,
"groups": [
{"type": "quantity", "key": "seats", "tiers": [{"from": 5, "unit_price_minor": seat_price}]},
{"type": "choice", "key": "storage", "options": [
{"key": "2t", "unit_price_minor": 30000},
{"key": "10t", "unit_price_minor": 80000}
]},
{"type": "component", "key": "server"},
{"type": "term", "key": "term", "terms": [
{"months": 12, "discount_bps": 0},
{"months": 24, "discount_bps": 1500},
{"months": 36, "discount_bps": 2000}
]}
]
})
}
fn config(server_sku: &str) -> serde_json::Value {
serde_json::json!({
"seats": 5,
"storage": "2t",
"server": server_sku,
"term": 24
})
}
#[tokio::test]
#[serial]
async fn common_line_price_is_unchanged() {
let app = spawn_app().await;
let admin = login_admin(&app).await;
let (buyer, _) = register_customer(&app, "price-common").await;
let (owner, _shop, _product, sku) = setup_sellable(&app, &admin, "price-common", 1999, 10).await;
add_to_cart(&app, &buyer, &sku, 2).await;
let res = client()
.post(app.url("/api/orders/checkout"))
.bearer_auth(&buyer)
.header("Idempotency-Key", uuid::Uuid::new_v4().to_string())
.json(&serde_json::json!({
"currency": "USD",
"shipping_address": {
"recipient": "Ada", "phone": "13800000000", "country": "CN",
"region": "ZJ", "city": "HZ", "line1": "1 Road", "postal_code": "310000"
}
}))
.send()
.await
.unwrap();
assert_eq!(res.status(), 201, "{}", res.text().await.unwrap());
let body = res.json::<serde_json::Value>().await.unwrap();
let item = &body["orders"][0]["items"][0];
assert_eq!(item["unit_price_minor"].as_i64(), Some(1999));
assert_eq!(item["qty"].as_i64(), Some(2));
let _ = owner;
}
#[tokio::test]
#[serial]
async fn configurable_quote_checkout_and_version_snapshot() {
let app = spawn_app().await;
let admin = login_admin(&app).await;
let (buyer, _) = register_customer(&app, "price-linear").await;
let (owner, shop, physical, _sku) =
setup_sellable(&app, &admin, "price-linear", 1000, 10).await;
let server = client()
.post(app.url("/api/shop/products"))
.bearer_auth(&owner)
.json(&serde_json::json!({
"slug": format!("srv-{}", &uuid::Uuid::new_v4().simple().to_string()[..8]),
"name": {"en": "Server", "zh": "服务器"},
"fulfillment_kind": "provisioned_service"
}))
.send()
.await
.unwrap();
assert_eq!(server.status(), 201, "{}", server.text().await.unwrap());
let server_id = server.json::<serde_json::Value>().await.unwrap()["id"]
.as_str()
.unwrap()
.to_string();
let flag = client()
.put(app.url(&format!("/api/shop/products/{server_id}/component-only")))
.bearer_auth(&owner)
.json(&serde_json::json!({"component_only": true}))
.send()
.await
.unwrap();
assert_eq!(flag.status(), 204, "{}", flag.text().await.unwrap());
let bare = client()
.post(app.url(&format!("/api/shop/products/{server_id}/skus")))
.bearer_auth(&owner)
.json(&serde_json::json!({
"sku_code": "bare",
"price_minor": 1000,
"currency": "USD",
"stock": 9,
"attributes": {"vcpu": "4", "mem_gb": "16"}
}))
.send()
.await
.unwrap();
assert_eq!(bare.status(), 400, "missing bandwidth must be rejected");
let made = client()
.post(app.url(&format!("/api/shop/products/{server_id}/skus")))
.bearer_auth(&owner)
.json(&serde_json::json!({
"sku_code": "4c16g",
"price_minor": 80000,
"currency": "USD",
"stock": 9,
"attributes": {"vcpu": "4", "mem_gb": "16", "bandwidth_mbps": "100"}
}))
.send()
.await
.unwrap();
assert_eq!(made.status(), 200, "{}", made.text().await.unwrap());
let server_sku = made.json::<serde_json::Value>().await.unwrap()["id"]
.as_str()
.unwrap()
.to_string();
let published = client()
.post(app.url(&format!("/api/shop/products/{server_id}/publish")))
.bearer_auth(&owner)
.send()
.await
.unwrap();
assert_eq!(published.status(), 200, "{}", published.text().await.unwrap());
let listed = client()
.get(app.url(&format!("/api/products?shop_id={shop}&per_page=50")))
.send()
.await
.unwrap()
.json::<serde_json::Value>()
.await
.unwrap();
let visible = listed["items"].as_array().unwrap();
assert!(visible.iter().all(|item| item["id"] != server_id));
let hidden = client()
.get(app.url(&format!("/api/products/{server_id}")))
.send()
.await
.unwrap();
assert_eq!(hidden.status(), 404);
let cart = client()
.post(app.url("/api/cart/items"))
.bearer_auth(&buyer)
.json(&serde_json::json!({"sku_id": server_sku, "qty": 1}))
.send()
.await
.unwrap();
assert_eq!(cart.status(), 400);
let parent = client()
.post(app.url("/api/shop/products"))
.bearer_auth(&owner)
.json(&serde_json::json!({
"slug": format!("desk-{}", &uuid::Uuid::new_v4().simple().to_string()[..8]),
"name": {"en": "Care desk", "zh": "客服台"},
"fulfillment_kind": "provisioned_service"
}))
.send()
.await
.unwrap();
assert_eq!(parent.status(), 201, "{}", parent.text().await.unwrap());
let parent_id = parent.json::<serde_json::Value>().await.unwrap()["id"]
.as_str()
.unwrap()
.to_string();
let saved = client()
.put(app.url(&format!("/api/shop/products/{parent_id}/option-groups")))
.bearer_auth(&owner)
.json(&groups(&server_id))
.send()
.await
.unwrap();
assert_eq!(saved.status(), 200, "{}", saved.text().await.unwrap());
let too_soon = client()
.post(app.url(&format!("/api/shop/products/{parent_id}/publish")))
.bearer_auth(&owner)
.send()
.await
.unwrap();
assert_eq!(too_soon.status(), 400);
let physical_rule = client()
.post(app.url(&format!("/api/shop/products/{physical}/pricing-rules")))
.bearer_auth(&owner)
.json(&rule(19900))
.send()
.await
.unwrap();
assert_eq!(physical_rule.status(), 400);
let mut two_tiers = rule(19900);
two_tiers["groups"][0]["tiers"] = serde_json::json!([
{"from": 5, "unit_price_minor": 19900},
{"from": 50, "unit_price_minor": 10000}
]);
let tiers = client()
.post(app.url(&format!("/api/shop/products/{parent_id}/pricing-rules")))
.bearer_auth(&owner)
.json(&two_tiers)
.send()
.await
.unwrap();
assert_eq!(tiers.status(), 400, "{}", tiers.text().await.unwrap());
let priced = client()
.post(app.url(&format!("/api/shop/products/{parent_id}/pricing-rules")))
.bearer_auth(&owner)
.json(&rule(19900))
.send()
.await
.unwrap();
assert_eq!(priced.status(), 201, "{}", priced.text().await.unwrap());
let first_rule = priced.json::<serde_json::Value>().await.unwrap()["id"]
.as_str()
.unwrap()
.to_string();
let published = client()
.post(app.url(&format!("/api/shop/products/{parent_id}/publish")))
.bearer_auth(&owner)
.send()
.await
.unwrap();
assert_eq!(published.status(), 200, "{}", published.text().await.unwrap());
let mut bad = config(&server_sku);
bad["seats"] = serde_json::json!(7);
let off = client()
.post(app.url(&format!("/api/products/{parent_id}/quote")))
.json(&serde_json::json!({"configuration": bad, "currency": "USD"}))
.send()
.await
.unwrap();
assert_eq!(off.status(), 400);
let quote = client()
.post(app.url(&format!("/api/products/{parent_id}/quote")))
.json(&serde_json::json!({"configuration": config(&server_sku), "currency": "USD"}))
.send()
.await
.unwrap();
assert_eq!(quote.status(), 200, "{}", quote.text().await.unwrap());
let quote = quote.json::<serde_json::Value>().await.unwrap();
assert_eq!(quote["total_minor"].as_i64(), Some(4_273_800));
let selectable = quote["component_skus"].as_array().unwrap();
assert_eq!(selectable.len(), 1);
assert_eq!(selectable[0]["sku_code"], "4c16g");
let detail = client()
.get(app.url(&format!("/api/products/{parent_id}")))
.send()
.await
.unwrap()
.json::<serde_json::Value>()
.await
.unwrap();
assert_eq!(detail["listing_price_minor"].as_i64(), Some(2_514_000));
let anchor = detail["anchor_sku_id"].as_str().unwrap().to_string();
let stale = client()
.post(app.url("/api/orders/checkout"))
.bearer_auth(&buyer)
.header("Idempotency-Key", "stale-price")
.json(&serde_json::json!({
"currency": "USD",
"direct": {
"sku_id": anchor,
"configuration": config(&server_sku),
"expected_total_minor": 1
}
}))
.send()
.await
.unwrap();
assert_eq!(stale.status(), 409, "{}", stale.text().await.unwrap());
let stale_body = stale.json::<serde_json::Value>().await.unwrap();
assert_eq!(stale_body["error"]["code"], "PRICE_CHANGED");
assert_eq!(stale_body["error"]["quote"]["total_minor"].as_i64(), Some(4_273_800));
let key = "buy-desk";
let bought = client()
.post(app.url("/api/orders/checkout"))
.bearer_auth(&buyer)
.header("Idempotency-Key", key)
.json(&serde_json::json!({
"currency": "USD",
"direct": {
"sku_id": anchor,
"configuration": config(&server_sku),
"expected_total_minor": 4_273_800
}
}))
.send()
.await
.unwrap();
assert_eq!(bought.status(), 201, "{}", bought.text().await.unwrap());
let order = bought.json::<serde_json::Value>().await.unwrap();
let item = &order["orders"][0]["items"][0];
assert_eq!(item["unit_price_minor"].as_i64(), Some(4_273_800));
assert_eq!(item["qty"].as_i64(), Some(1));
assert_eq!(item["pricing_rule_id"].as_str(), Some(first_rule.as_str()));
assert_eq!(item["configuration"]["components"][0]["sku_code"], "4c16g");
let order_id = order["orders"][0]["id"].as_str().unwrap().to_string();
let stock: i32 = sqlx::query_scalar("SELECT stock FROM skus WHERE id = $1::uuid")
.bind(&server_sku)
.fetch_one(&app.db)
.await
.unwrap();
assert_eq!(stock, 9);
let repriced = client()
.post(app.url(&format!("/api/shop/products/{parent_id}/pricing-rules")))
.bearer_auth(&owner)
.json(&rule(25000))
.send()
.await
.unwrap();
assert_eq!(repriced.status(), 201, "{}", repriced.text().await.unwrap());
let replay = client()
.post(app.url("/api/orders/checkout"))
.bearer_auth(&buyer)
.header("Idempotency-Key", key)
.json(&serde_json::json!({
"currency": "USD",
"direct": {
"sku_id": anchor,
"configuration": config(&server_sku),
"expected_total_minor": 4_273_800
}
}))
.send()
.await
.unwrap();
let replay_status = replay.status();
let replay_body = replay.text().await.unwrap();
assert_eq!(replay_status.as_u16(), 201, "{}", &replay_body[..replay_body.len().min(180)]);
let replayed: serde_json::Value = serde_json::from_str(&replay_body).unwrap();
assert_eq!(replayed["orders"][0]["id"].as_str(), Some(order_id.as_str()));
let stored: (i64, String) = sqlx::query_as(
"SELECT unit_price_minor, pricing_rule_id::text FROM order_items WHERE order_id = $1::uuid",
)
.bind(&order_id)
.fetch_one(&app.db)
.await
.unwrap();
assert_eq!(stored.0, 4_273_800);
assert_eq!(stored.1, first_rule);
let history = client()
.get(app.url(&format!("/api/shop/products/{parent_id}/pricing-rules")))
.bearer_auth(&owner)
.send()
.await
.unwrap()
.json::<serde_json::Value>()
.await
.unwrap();
assert!(history.as_array().unwrap().len() >= 2);
}