From c394d9fc0766bf3fe88ffe816b381aae0ee54ba3 Mon Sep 17 00:00:00 2001 From: Ashwin Kumar Sivakumar Date: Fri, 14 Aug 2026 15:26:47 +0530 Subject: [PATCH] feat(ai-credits): real coupon validation endpoint; restore invoice FK integrity - 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 --- apps/payments/src/ai_credits.rs | 82 +++++++++++++++++++ ...ices_payment_id_polymorphic_check.down.sql | 6 ++ ...voices_payment_id_polymorphic_check.up.sql | 32 ++++++++ 3 files changed, 120 insertions(+) create mode 100644 crates/db/migrations/20260814050000_invoices_payment_id_polymorphic_check.down.sql create mode 100644 crates/db/migrations/20260814050000_invoices_payment_id_polymorphic_check.up.sql diff --git a/apps/payments/src/ai_credits.rs b/apps/payments/src/ai_credits.rs index c267582..63a8cb6 100644 --- a/apps/payments/src/ai_credits.rs +++ b/apps/payments/src/ai_credits.rs @@ -41,6 +41,7 @@ pub fn router() -> Router { .route("/", get(list_packages)) .route("/order", post(create_order)) .route("/verify", post(verify_order)) + .route("/coupons/validate", post(validate_coupon_endpoint)) } /// 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))) } +#[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, +} + +/// 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, + Json(payload): Json, +) -> Json { + 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( auth: AuthUser, State(state): State, diff --git a/crates/db/migrations/20260814050000_invoices_payment_id_polymorphic_check.down.sql b/crates/db/migrations/20260814050000_invoices_payment_id_polymorphic_check.down.sql new file mode 100644 index 0000000..79efeea --- /dev/null +++ b/crates/db/migrations/20260814050000_invoices_payment_id_polymorphic_check.down.sql @@ -0,0 +1,6 @@ +BEGIN; + +DROP TRIGGER IF EXISTS invoices_payment_id_check ON invoices; +DROP FUNCTION IF EXISTS check_invoices_payment_id(); + +COMMIT; diff --git a/crates/db/migrations/20260814050000_invoices_payment_id_polymorphic_check.up.sql b/crates/db/migrations/20260814050000_invoices_payment_id_polymorphic_check.up.sql new file mode 100644 index 0000000..2623404 --- /dev/null +++ b/crates/db/migrations/20260814050000_invoices_payment_id_polymorphic_check.up.sql @@ -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;