Tier upgrades Phase 4 — admin force-change + renewal-worker hook
Closes the operator side of TIER_UPGRADES_DESIGN.md. With this in,
operators can force-change any license to any policy under the same
product (sideways, cross-NULL-rank, perpetual downgrades all
allowed) — and scheduled tier changes (e.g. recurring downgrades
recorded with future effective_at) actually fire at cycle boundaries.
New endpoint:
- POST /v1/admin/licenses/:id/change-tier
Body: { to_policy_slug, skip_payment: bool, reason?: string }
skip_payment=true (comp upgrade / support fix-up): apply
immediately, write a tier_changes row with proration=0 and
invoice_id=NULL, fire the license.tier_changed webhook, audit-log
with actor=admin_api_key.
skip_payment=false: same as buyer's /v1/upgrade — create a
provider invoice for the prorated charge, persist the local
invoice + a tier_changes row tied to it, return the checkout URL.
Operator forwards it to the buyer through whatever channel they
use. Webhook applies on settle.
Bypasses ladder rules entirely (sideways, perpetual downgrade,
recurring → perpetual all OK). Same-product / different-policy /
active-target checks still apply.
QuoteMode refactor (src/upgrades.rs):
- compute_upgrade_quote now takes QuoteMode::{Buyer, Admin}.
- Buyer mode = strict ladder rules (per Phase 2).
- Admin mode = bypass ladder + downgrade gates; infer direction
from rank-diff if both ranked, else from price-diff.
- Buyer endpoint passes Buyer; admin endpoint passes Admin.
Renewal-worker hook (src/subscriptions.rs):
- Before pricing each renewal cycle, the worker calls
apply_pending_tier_changes(state, sub). This finds tier_changes
rows for the sub's license where effective_at <= now AND
invoice_id IS NULL AND license.policy_id != to_policy_id (i.e.
scheduled comp/admin changes that haven't been applied yet).
Each pending change is applied via apply_tier_change (which
also rewrites the sub's policy_id / listed_value / period_days).
After applying, the worker re-fetches the sub and prices the
next invoice at the NEW tier's listed_value.
- This is what makes recurring downgrades actually take effect at
the cycle boundary (admin records "Pro → Standard at next
renewal", the worker applies it, the new invoice bills at
Standard's price).
- Idempotent: re-running the hook on a license already on the
target tier finds zero pending rows (the policy_id != check
filters them out).
Tests (+5, total now 77):
- admin_change_tier_skip_payment_applies_immediately — comp path
flips license + writes tier_change row with no invoice
- admin_change_tier_allows_perpetual_downgrade — the case the
buyer endpoint rejects with 400 "admin-only"
- admin_change_tier_rejects_zero_charge_paid_path — sideways
attempt with skip_payment=false hints at switching to true
- admin_change_tier_requires_admin_token — 401 without auth
- renewal_worker_applies_pending_tier_change_before_billing —
the headline behavior: a pending downgrade tier_change with
effective_at=now causes the next renewal to bill at the new
(lower) tier's price, NOT the old one. Uses a CapturingProvider
mock that stashes the last sat amount it saw so the assertion
is on what the worker actually billed.
This commit is contained in:
@@ -2656,6 +2656,144 @@ async fn webhook_settle_on_tier_change_applies_instead_of_issuing() {
|
||||
let _ = invoice_id;
|
||||
}
|
||||
|
||||
/// Admin can force-change a license to any policy under the same
|
||||
/// product. skip_payment=true applies immediately with no invoice.
|
||||
#[tokio::test]
|
||||
async fn admin_change_tier_skip_payment_applies_immediately() {
|
||||
let (state, _tmp) = make_test_state().await;
|
||||
let auth = format!("Bearer {}", TEST_ADMIN_KEY);
|
||||
let (license_id, _key, _std, pro_id) = seed_perpetual_ladder_with_key(&state).await;
|
||||
|
||||
let req = build_request(
|
||||
"POST",
|
||||
&format!("/v1/admin/licenses/{license_id}/change-tier"),
|
||||
&[("authorization", &auth)],
|
||||
Some(json!({
|
||||
"to_policy_slug": "pro",
|
||||
"skip_payment": true,
|
||||
"reason": "comp upgrade per support ticket #1234"
|
||||
})),
|
||||
);
|
||||
let resp = send(&state, req).await;
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
let body = body_json(resp).await;
|
||||
assert_eq!(body["applied"], true);
|
||||
assert_eq!(body["skip_payment"], true);
|
||||
let tc_id = body["tier_change_id"].as_str().unwrap().to_string();
|
||||
|
||||
let license_after = repo::get_license_by_id(&state.db, &license_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
license_after.policy_id.as_deref(),
|
||||
Some(pro_id.as_str()),
|
||||
"skip_payment=true should apply on the spot"
|
||||
);
|
||||
|
||||
let tc = keysat::upgrades::get_tier_change(&state.db, &tc_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(tc.actor, "admin");
|
||||
assert_eq!(tc.proration_charge_value, 0);
|
||||
assert_eq!(tc.invoice_id, None, "comp upgrade has no invoice");
|
||||
assert_eq!(
|
||||
tc.reason.as_deref(),
|
||||
Some("comp upgrade per support ticket #1234")
|
||||
);
|
||||
}
|
||||
|
||||
/// Admin can force a perpetual downgrade. Buyer endpoint rejects
|
||||
/// these (refund decision per design doc).
|
||||
#[tokio::test]
|
||||
async fn admin_change_tier_allows_perpetual_downgrade() {
|
||||
let (state, _tmp) = make_test_state().await;
|
||||
let auth = format!("Bearer {}", TEST_ADMIN_KEY);
|
||||
let (license_id, _key, std_id, pro_id) = seed_perpetual_ladder_with_key(&state).await;
|
||||
sqlx::query("UPDATE licenses SET policy_id = ? WHERE id = ?")
|
||||
.bind(&pro_id)
|
||||
.bind(&license_id)
|
||||
.execute(&state.db)
|
||||
.await
|
||||
.unwrap();
|
||||
let req = build_request(
|
||||
"POST",
|
||||
&format!("/v1/admin/licenses/{license_id}/change-tier"),
|
||||
&[("authorization", &auth)],
|
||||
Some(json!({
|
||||
"to_policy_slug": "standard",
|
||||
"skip_payment": true,
|
||||
"reason": "honoring partial refund"
|
||||
})),
|
||||
);
|
||||
let resp = send(&state, req).await;
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
let license_after = repo::get_license_by_id(&state.db, &license_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(license_after.policy_id.as_deref(), Some(std_id.as_str()));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn admin_change_tier_rejects_zero_charge_paid_path() {
|
||||
let (state, _tmp) = make_test_state().await;
|
||||
let auth = format!("Bearer {}", TEST_ADMIN_KEY);
|
||||
let (license_id, _key, std_id, _pro) = seed_perpetual_ladder_with_key(&state).await;
|
||||
let std_policy = repo::get_policy_by_id(&state.db, &std_id).await.unwrap().unwrap();
|
||||
let _sideways = repo::create_policy(
|
||||
&state.db,
|
||||
&std_policy.product_id,
|
||||
"Standard Plus",
|
||||
"standard-plus",
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
false,
|
||||
Some(2500),
|
||||
&["core".into()],
|
||||
&json!({}),
|
||||
None,
|
||||
0,
|
||||
None,
|
||||
repo::RecurringConfig::off(),
|
||||
Some(1),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let req = build_request(
|
||||
"POST",
|
||||
&format!("/v1/admin/licenses/{license_id}/change-tier"),
|
||||
&[("authorization", &auth)],
|
||||
Some(json!({
|
||||
"to_policy_slug": "standard-plus",
|
||||
"skip_payment": false
|
||||
})),
|
||||
);
|
||||
let resp = send(&state, req).await;
|
||||
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
|
||||
let body = body_json(resp).await;
|
||||
assert!(
|
||||
body["message"].as_str().unwrap_or("").contains("skip_payment"),
|
||||
"error should hint at the skip_payment toggle: {body:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn admin_change_tier_requires_admin_token() {
|
||||
let (state, _tmp) = make_test_state().await;
|
||||
let (license_id, _key, _std, _pro) = seed_perpetual_ladder_with_key(&state).await;
|
||||
let req = build_request(
|
||||
"POST",
|
||||
&format!("/v1/admin/licenses/{license_id}/change-tier"),
|
||||
&[],
|
||||
Some(json!({"to_policy_slug": "pro", "skip_payment": true})),
|
||||
);
|
||||
let resp = send(&state, req).await;
|
||||
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
|
||||
}
|
||||
|
||||
/// Buyer-initiated downgrade is rejected from this endpoint in v0.2.x
|
||||
/// (Phase 4 admin endpoint covers downgrades).
|
||||
#[tokio::test]
|
||||
|
||||
Reference in New Issue
Block a user