feat(ai-credits): real coupon validation endpoint; restore invoice FK integrity
All checks were successful
build-and-release / build (employees) (push) Successful in 1m46s
build-and-release / build (customers) (push) Successful in 2m0s
build-and-release / build (cron) (push) Successful in 2m13s
build-and-release / build (companies) (push) Successful in 2m20s
build-and-release / build (catering-services) (push) Successful in 2m36s
build-and-release / build (developers) (push) Successful in 2m52s
build-and-release / build (gateway) (push) Successful in 53s
build-and-release / build (jobs) (push) Successful in 44s
build-and-release / build (fitness-trainers) (push) Successful in 1m39s
build-and-release / build (job-seekers) (push) Successful in 2m14s
build-and-release / build (payments) (push) Successful in 1m52s
build-and-release / build (graphic-designers) (push) Successful in 2m37s
build-and-release / build (makeup-artists) (push) Successful in 3m3s
build-and-release / build (photographers) (push) Successful in 2m48s
build-and-release / build (social-media-managers) (push) Successful in 2m40s
backend-integration-tests / ai-credits (push) Successful in 45s
build-and-release / build (tutors) (push) Successful in 2m44s
build-and-release / build (ugc-content-creators) (push) Successful in 2m44s
build-and-release / build (video-editors) (push) Successful in 2m45s
build-and-release / build (users) (push) Successful in 4m49s

- Add POST /api/ai-credits/coupons/validate: a dry-run of the same
  validate_coupon() check create_order applies, so the checkout UI can
  show a real discount/error before Pay instead of only finding out at
  order-creation time. Never inserts anything.
- Add migration 20260814050000: restores integrity on invoices.payment_id
  after 20260814030000 dropped the hard FK to support polymorphic
  invoice_type (TRACECOIN_PURCHASE -> payments, AI_CREDIT_PURCHASE ->
  ai_credit_orders). A BEFORE INSERT/UPDATE trigger now validates
  payment_id against the right table per invoice_type instead of leaving
  it fully unchecked. Verified against a live Postgres in a scratch
  schema (valid/invalid payment_id, valid/bogus invoice_type).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Ashwin Kumar Sivakumar 2026-08-14 15:26:47 +05:30
parent 4e0e6af3e1
commit c394d9fc07
3 changed files with 120 additions and 0 deletions

View file

@ -41,6 +41,7 @@ pub fn router() -> Router<AppState> {
.route("/", get(list_packages)) .route("/", get(list_packages))
.route("/order", post(create_order)) .route("/order", post(create_order))
.route("/verify", post(verify_order)) .route("/verify", post(verify_order))
.route("/coupons/validate", post(validate_coupon_endpoint))
} }
/// Admin CRUD for the AI credit package catalog -- mounted at /// Admin CRUD for the AI credit package catalog -- mounted at
@ -221,6 +222,87 @@ async fn validate_coupon(
Ok(Some((discount_paise, coupon_id.to_string(), discounted_price))) Ok(Some((discount_paise, coupon_id.to_string(), discounted_price)))
} }
#[derive(Debug, Deserialize)]
struct ValidateCouponRequest {
package_id: String,
coupon_code: String,
}
#[derive(Debug, Serialize)]
struct ValidateCouponResponse {
valid: bool,
discount_paise: i32,
original_price_inr: i32,
final_price_inr: i32,
message: Option<String>,
}
/// Dry-run of the same coupon check create_order applies, so the checkout
/// UI can show a real discount/error before the user hits Pay instead of
/// only finding out at order-creation time. Never inserts anything -
/// redemption is still only recorded when verify_order confirms payment.
async fn validate_coupon_endpoint(
auth: AuthUser,
State(state): State<AppState>,
Json(payload): Json<ValidateCouponRequest>,
) -> Json<ValidateCouponResponse> {
let package_id = match Uuid::parse_str(&payload.package_id) {
Ok(id) => id,
Err(_) => {
return Json(ValidateCouponResponse {
valid: false,
discount_paise: 0,
original_price_inr: 0,
final_price_inr: 0,
message: Some("Invalid package id".to_string()),
})
}
};
let package = sqlx::query_as::<_, AiCreditPackagePriceRow>(
"SELECT name, credits, price_inr, applicable_roles FROM ai_credit_packages WHERE id = $1 AND is_active = TRUE",
)
.bind(package_id)
.fetch_optional(&state.pool)
.await
.ok()
.flatten();
let Some(package) = package else {
return Json(ValidateCouponResponse {
valid: false,
discount_paise: 0,
original_price_inr: 0,
final_price_inr: 0,
message: Some("Invalid or inactive AI credit package".to_string()),
});
};
match validate_coupon(&state.pool, auth.user_id, &payload.coupon_code, package_id, package.price_inr).await {
Ok(Some((discount_paise, _coupon_id, discounted_price))) => Json(ValidateCouponResponse {
valid: true,
discount_paise,
original_price_inr: package.price_inr,
final_price_inr: discounted_price,
message: None,
}),
Ok(None) => Json(ValidateCouponResponse {
valid: false,
discount_paise: 0,
original_price_inr: package.price_inr,
final_price_inr: package.price_inr,
message: Some("Invalid coupon code".to_string()),
}),
Err(e) => Json(ValidateCouponResponse {
valid: false,
discount_paise: 0,
original_price_inr: package.price_inr,
final_price_inr: package.price_inr,
message: Some(e),
}),
}
}
async fn create_order( async fn create_order(
auth: AuthUser, auth: AuthUser,
State(state): State<AppState>, State(state): State<AppState>,

View file

@ -0,0 +1,6 @@
BEGIN;
DROP TRIGGER IF EXISTS invoices_payment_id_check ON invoices;
DROP FUNCTION IF EXISTS check_invoices_payment_id();
COMMIT;

View file

@ -0,0 +1,32 @@
-- 20260814030000 dropped invoices_payment_id_fkey to allow AI_CREDIT_PURCHASE
-- invoices (payment_id -> ai_credit_orders(id)) alongside the pre-existing
-- TRACECOIN_PURCHASE invoices (payment_id -> payments(id)), but left no
-- replacement integrity check at all -- any invoice_type could reference a
-- nonexistent payment_id. Postgres has no native polymorphic FK, so enforce
-- this with a trigger that picks the right table based on invoice_type.
BEGIN;
CREATE OR REPLACE FUNCTION check_invoices_payment_id() RETURNS TRIGGER AS $$
BEGIN
IF NEW.invoice_type = 'TRACECOIN_PURCHASE' THEN
IF NOT EXISTS (SELECT 1 FROM payments WHERE id = NEW.payment_id) THEN
RAISE EXCEPTION 'invoices.payment_id % does not reference an existing payments row (invoice_type=TRACECOIN_PURCHASE)', NEW.payment_id;
END IF;
ELSIF NEW.invoice_type = 'AI_CREDIT_PURCHASE' THEN
IF NOT EXISTS (SELECT 1 FROM ai_credit_orders WHERE id = NEW.payment_id) THEN
RAISE EXCEPTION 'invoices.payment_id % does not reference an existing ai_credit_orders row (invoice_type=AI_CREDIT_PURCHASE)', NEW.payment_id;
END IF;
ELSE
RAISE EXCEPTION 'invoices.invoice_type % is not a recognized value (expected TRACECOIN_PURCHASE or AI_CREDIT_PURCHASE)', NEW.invoice_type;
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER invoices_payment_id_check
BEFORE INSERT OR UPDATE OF payment_id, invoice_type ON invoices
FOR EACH ROW
EXECUTE FUNCTION check_invoices_payment_id();
COMMIT;