Collapse multiple invoice tables into one
This commit is contained in:
+2
-2
@@ -36,7 +36,7 @@ use crate::query::Query;
|
||||
use crate::robot::Robot;
|
||||
use crate::stripe::Stripe;
|
||||
use crate::routes::identity::get_identity;
|
||||
use crate::routes::invoices::{get_invoice, get_invoice_bolt11, list_tenant_invoices};
|
||||
use crate::routes::invoices::{get_invoice, get_lightning_invoice, list_tenant_invoices};
|
||||
use crate::routes::plans::{get_plan, list_plans};
|
||||
use crate::routes::relays::{
|
||||
create_relay, deactivate_relay, get_relay, list_relay_activity, list_relay_members,
|
||||
@@ -98,7 +98,7 @@ impl Api {
|
||||
.route("/relays/:id/reactivate", post(reactivate_relay))
|
||||
.route("/tenants/:pubkey/invoices", get(list_tenant_invoices))
|
||||
.route("/invoices/:id", get(get_invoice))
|
||||
.route("/invoices/:id/bolt11", get(get_invoice_bolt11))
|
||||
.route("/invoices/:id/bolt11", get(get_lightning_invoice))
|
||||
.route("/tenants/:pubkey/stripe/session", get(create_stripe_session))
|
||||
.route("/stripe/webhook", post(stripe_webhook))
|
||||
.with_state(api)
|
||||
|
||||
+113
-179
@@ -11,11 +11,10 @@ use crate::wallet::Wallet;
|
||||
|
||||
const LIGHTNING_INVOICE_DESCRIPTION: &str = "Relay subscription payment";
|
||||
|
||||
pub enum NwcInvoicePaymentOutcome {
|
||||
Paid,
|
||||
Fallback(anyhow::Error),
|
||||
Pending(anyhow::Error),
|
||||
}
|
||||
/// How long a freshly minted bolt11 stays valid. Once it lapses, an unpaid
|
||||
/// invoice's bolt11 is regenerated on next access, so the tenant is never shown
|
||||
/// a dead invoice and the sat amount stays pegged to the current BTC price.
|
||||
const BOLT11_EXPIRY_SECS: i64 = 3600;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Billing {
|
||||
@@ -234,78 +233,65 @@ impl Billing {
|
||||
pub async fn create_bolt11(&self, amount_due_minor: i64, currency: &str) -> Result<String> {
|
||||
let amount_msats = bitcoin::fiat_to_msats(amount_due_minor, currency).await?;
|
||||
self.wallet
|
||||
.make_invoice(amount_msats, LIGHTNING_INVOICE_DESCRIPTION)
|
||||
.make_invoice(
|
||||
amount_msats,
|
||||
LIGHTNING_INVOICE_DESCRIPTION,
|
||||
BOLT11_EXPIRY_SECS as u64,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn pay_outstanding_nwc_invoices(&self, tenant: &crate::models::Tenant) -> Result<()> {
|
||||
if tenant.nwc_url.is_empty() {
|
||||
return Ok(());
|
||||
/// Return the current valid bolt11 for an open invoice, minting one if none
|
||||
/// exists and regenerating it if the stored one has expired. There is
|
||||
/// exactly one bolt11 per invoice: whoever pays it — the tenant's NWC wallet
|
||||
/// or a human — settles the same Lightning invoice, so the bolt11 itself is
|
||||
/// the double-charge guard.
|
||||
pub async fn ensure_lightning_invoice(
|
||||
&self,
|
||||
stripe_invoice_id: &str,
|
||||
tenant_pubkey: &str,
|
||||
amount_due_minor: i64,
|
||||
currency: &str,
|
||||
) -> Result<String> {
|
||||
let now = chrono::Utc::now().timestamp();
|
||||
|
||||
if let Some(existing) = self.query.get_lightning_invoice(stripe_invoice_id).await? {
|
||||
// Keep a still-valid invoice, or any bolt11 we've already settled.
|
||||
if existing.status != "pending" || now < existing.expires_at {
|
||||
return Ok(existing.bolt11);
|
||||
}
|
||||
// The stored invoice expired unpaid, so mint a fresh one. The old
|
||||
// invoice can no longer be paid, so no settlement can be missed.
|
||||
let bolt11 = self.create_bolt11(amount_due_minor, currency).await?;
|
||||
self.command
|
||||
.regenerate_lightning_invoice(stripe_invoice_id, &bolt11, now + BOLT11_EXPIRY_SECS)
|
||||
.await?;
|
||||
return Ok(bolt11);
|
||||
}
|
||||
|
||||
let plain_nwc_url = self.env.decrypt(&tenant.nwc_url)?;
|
||||
|
||||
let invoices = self
|
||||
.stripe
|
||||
.list_invoices(&tenant.stripe_customer_id)
|
||||
.await?;
|
||||
|
||||
for invoice in &invoices {
|
||||
if invoice.status != "open" || invoice.amount_due == 0 {
|
||||
continue;
|
||||
}
|
||||
let invoice_id = invoice.id.as_str();
|
||||
|
||||
match self
|
||||
.nwc_pay_invoice(
|
||||
invoice_id,
|
||||
&tenant.pubkey,
|
||||
invoice.amount_due,
|
||||
&invoice.currency,
|
||||
&plain_nwc_url,
|
||||
)
|
||||
let bolt11 = self.create_bolt11(amount_due_minor, currency).await?;
|
||||
if self
|
||||
.command
|
||||
.insert_pending_lightning_invoice(
|
||||
stripe_invoice_id,
|
||||
tenant_pubkey,
|
||||
&bolt11,
|
||||
now + BOLT11_EXPIRY_SECS,
|
||||
)
|
||||
.await?
|
||||
{
|
||||
Ok(bolt11)
|
||||
} else {
|
||||
// Lost the insert race; use whatever the winner stored.
|
||||
Ok(self
|
||||
.query
|
||||
.get_lightning_invoice(stripe_invoice_id)
|
||||
.await?
|
||||
{
|
||||
NwcInvoicePaymentOutcome::Paid => {
|
||||
if let Err(e) = self
|
||||
.mark_invoice_paid_out_of_band_after_nwc(invoice_id, &tenant.pubkey)
|
||||
.await
|
||||
{
|
||||
tracing::error!(
|
||||
error = %e,
|
||||
invoice_id,
|
||||
"failed to mark invoice paid out of band"
|
||||
);
|
||||
}
|
||||
}
|
||||
NwcInvoicePaymentOutcome::Fallback(e) => {
|
||||
let error_msg = format!("{e}");
|
||||
tracing::error!(
|
||||
error = %e,
|
||||
invoice_id,
|
||||
"nwc payment failed for outstanding invoice"
|
||||
);
|
||||
let _ = self
|
||||
.command
|
||||
.set_tenant_nwc_error(&tenant.pubkey, &error_msg)
|
||||
.await;
|
||||
}
|
||||
NwcInvoicePaymentOutcome::Pending(e) => {
|
||||
let error_msg = format!("{e}");
|
||||
tracing::error!(
|
||||
error = %e,
|
||||
invoice_id,
|
||||
"outstanding invoice requires NWC reconciliation before retry"
|
||||
);
|
||||
let _ = self
|
||||
.command
|
||||
.set_tenant_nwc_error(&tenant.pubkey, &error_msg)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
.ok_or_else(|| {
|
||||
anyhow!("lightning_invoice row missing after insert race for invoice {stripe_invoice_id}")
|
||||
})?
|
||||
.bolt11)
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn pay_outstanding_card_invoices(
|
||||
@@ -332,7 +318,7 @@ impl Billing {
|
||||
if let Err(error) = self.stripe.pay_invoice(&invoice.id).await {
|
||||
tracing::error!(
|
||||
error = %error,
|
||||
invoice_id = %invoice.id,
|
||||
stripe_invoice_id = %invoice.id,
|
||||
"failed to retry card payment for outstanding invoice"
|
||||
);
|
||||
}
|
||||
@@ -343,40 +329,58 @@ impl Billing {
|
||||
|
||||
// --- Lightning / NWC orchestration ---
|
||||
|
||||
pub async fn mark_invoice_paid_out_of_band_after_nwc(
|
||||
/// Push a payment for an invoice's persisted bolt11 from the tenant's NWC
|
||||
/// wallet, then confirm settlement against the system wallet. On success the
|
||||
/// Stripe invoice is marked paid out of band and `Ok(())` is returned; on
|
||||
/// failure the returned error is the reason to surface to the tenant (the
|
||||
/// caller falls through to other payment methods rather than propagating
|
||||
/// it). Reusing the same bolt11 means a retry — or a concurrent manual
|
||||
/// payment — can never double-charge.
|
||||
pub async fn nwc_pay_invoice(
|
||||
&self,
|
||||
invoice_id: &str,
|
||||
stripe_invoice_id: &str,
|
||||
tenant_pubkey: &str,
|
||||
bolt11: &str,
|
||||
tenant_nwc_url: &str,
|
||||
) -> Result<()> {
|
||||
self.stripe.pay_invoice_out_of_band(invoice_id).await?;
|
||||
self.command.clear_tenant_nwc_error(tenant_pubkey).await?;
|
||||
Ok(())
|
||||
let tenant_wallet = Wallet::from_url(tenant_nwc_url)?;
|
||||
|
||||
match tenant_wallet.pay_invoice(bolt11.to_string()).await {
|
||||
Ok(()) => self.settle_invoice(stripe_invoice_id, tenant_pubkey, "nwc").await,
|
||||
Err(pay_error) => {
|
||||
// The pay request errored, but the payment may have landed
|
||||
// before the response was lost. Confirm against the system
|
||||
// wallet before reporting failure.
|
||||
if self.wallet.is_settled(bolt11).await.unwrap_or(false) {
|
||||
self.settle_invoice(stripe_invoice_id, tenant_pubkey, "nwc").await
|
||||
} else {
|
||||
Err(pay_error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn reconcile_manual_lightning_invoice(
|
||||
&self,
|
||||
invoice_id: &str,
|
||||
invoice: &StripeInvoice,
|
||||
) -> Result<StripeInvoice> {
|
||||
/// If an open invoice's bolt11 has settled on Lightning, record it as paid.
|
||||
/// This is the shared settlement path for both NWC payments that landed late
|
||||
/// and manual payments; it is driven by the actual Lightning settlement
|
||||
/// rather than our local state, so it self-corrects if a previous attempt
|
||||
/// updated Stripe but not our row (or vice versa).
|
||||
pub async fn reconcile_invoice(&self, invoice: &StripeInvoice) -> Result<StripeInvoice> {
|
||||
if invoice.status != "open" {
|
||||
return Ok(invoice.clone());
|
||||
}
|
||||
|
||||
let Some(bolt11) = self
|
||||
.query
|
||||
.get_invoice_manual_lightning_bolt11(invoice_id)
|
||||
.await?
|
||||
else {
|
||||
let Some(row) = self.query.get_lightning_invoice(&invoice.id).await? else {
|
||||
return Ok(invoice.clone());
|
||||
};
|
||||
|
||||
let settled = match self.is_manual_lightning_invoice_settled(&bolt11).await {
|
||||
let settled = match self.wallet.is_settled(&row.bolt11).await {
|
||||
Ok(settled) => settled,
|
||||
Err(error) => {
|
||||
tracing::warn!(
|
||||
error = %error,
|
||||
invoice_id,
|
||||
"failed to lookup manual lightning invoice settlement"
|
||||
stripe_invoice_id = %invoice.id,
|
||||
"failed to look up bolt11 invoice settlement"
|
||||
);
|
||||
return Ok(invoice.clone());
|
||||
}
|
||||
@@ -386,108 +390,38 @@ impl Billing {
|
||||
return Ok(invoice.clone());
|
||||
}
|
||||
|
||||
if let Err(error) = self.stripe.pay_invoice_out_of_band(invoice_id).await {
|
||||
if let Err(error) = self.settle_invoice(&invoice.id, &row.tenant_pubkey, "manual").await {
|
||||
tracing::warn!(
|
||||
error = %error,
|
||||
invoice_id,
|
||||
"failed to mark settled manual lightning invoice as paid_out_of_band"
|
||||
stripe_invoice_id = %invoice.id,
|
||||
"failed to mark settled bolt11 invoice as paid"
|
||||
);
|
||||
}
|
||||
|
||||
// The invoice existed when we called pay_invoice_out_of_band a moment ago;
|
||||
// if Stripe suddenly returns 404, fall back to the pre-reconcile snapshot
|
||||
// rather than failing the request.
|
||||
// The invoice existed a moment ago; if Stripe suddenly returns 404, fall
|
||||
// back to the pre-reconcile snapshot rather than failing the request.
|
||||
Ok(self
|
||||
.stripe
|
||||
.get_invoice(invoice_id)
|
||||
.get_invoice(&invoice.id)
|
||||
.await?
|
||||
.unwrap_or_else(|| invoice.clone()))
|
||||
}
|
||||
|
||||
async fn is_manual_lightning_invoice_settled(&self, bolt11: &str) -> Result<bool> {
|
||||
self.wallet.is_settled(bolt11).await
|
||||
}
|
||||
|
||||
/// Charges a Stripe invoice over Lightning: the system wallet issues a bolt11
|
||||
/// invoice for the fiat amount, the tenant's wallet pays it. A `pending` row in
|
||||
/// `invoice_nwc_payment` guards against double-charging across retries.
|
||||
pub async fn nwc_pay_invoice(
|
||||
/// Record a settled bolt11 invoice as paid by `method`, mark the Stripe
|
||||
/// invoice paid out of band, and clear any lingering NWC error. The Stripe
|
||||
/// call is idempotent across retries, and `mark_lightning_invoice_paid` is
|
||||
/// first-writer-wins, so the recorded method reflects whoever settled first.
|
||||
async fn settle_invoice(
|
||||
&self,
|
||||
invoice_id: &str,
|
||||
stripe_invoice_id: &str,
|
||||
tenant_pubkey: &str,
|
||||
amount_due_minor: i64,
|
||||
currency: &str,
|
||||
tenant_nwc_url: &str,
|
||||
) -> Result<NwcInvoicePaymentOutcome> {
|
||||
if let Some(existing_outcome) = self
|
||||
.existing_invoice_nwc_payment_outcome(invoice_id)
|
||||
.await?
|
||||
{
|
||||
return Ok(existing_outcome);
|
||||
}
|
||||
|
||||
let amount_msats = match bitcoin::fiat_to_msats(amount_due_minor, currency).await {
|
||||
Ok(msats) => msats,
|
||||
Err(error) => return Ok(NwcInvoicePaymentOutcome::Fallback(error)),
|
||||
};
|
||||
|
||||
let bolt11 = match self
|
||||
.wallet
|
||||
.make_invoice(amount_msats, LIGHTNING_INVOICE_DESCRIPTION)
|
||||
.await
|
||||
{
|
||||
Ok(bolt11) => bolt11,
|
||||
Err(error) => return Ok(NwcInvoicePaymentOutcome::Fallback(error)),
|
||||
};
|
||||
|
||||
let tenant_wallet = match Wallet::from_url(tenant_nwc_url) {
|
||||
Ok(wallet) => wallet,
|
||||
Err(error) => return Ok(NwcInvoicePaymentOutcome::Fallback(error)),
|
||||
};
|
||||
|
||||
if !self
|
||||
.command
|
||||
.insert_pending_invoice_nwc_payment(invoice_id, tenant_pubkey)
|
||||
.await?
|
||||
{
|
||||
if let Some(existing_outcome) = self
|
||||
.existing_invoice_nwc_payment_outcome(invoice_id)
|
||||
.await?
|
||||
{
|
||||
return Ok(existing_outcome);
|
||||
}
|
||||
return Err(anyhow!(
|
||||
"invoice_nwc_payment row missing after insert race for invoice {invoice_id}"
|
||||
));
|
||||
}
|
||||
|
||||
match tenant_wallet.pay_invoice(bolt11).await {
|
||||
Ok(()) => match self.command.mark_invoice_nwc_payment_paid(invoice_id).await {
|
||||
Ok(()) => Ok(NwcInvoicePaymentOutcome::Paid),
|
||||
Err(error) => Ok(NwcInvoicePaymentOutcome::Pending(anyhow!(
|
||||
"invoice {invoice_id} was charged over NWC but failed to persist paid state: {error}"
|
||||
))),
|
||||
},
|
||||
Err(error) => Ok(NwcInvoicePaymentOutcome::Pending(anyhow!(
|
||||
"invoice {invoice_id} NWC payment attempt requires reconciliation: {error}"
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
async fn existing_invoice_nwc_payment_outcome(
|
||||
&self,
|
||||
invoice_id: &str,
|
||||
) -> Result<Option<NwcInvoicePaymentOutcome>> {
|
||||
let state = self.query.get_invoice_nwc_payment_state(invoice_id).await?;
|
||||
match state.as_deref() {
|
||||
Some("paid") => Ok(Some(NwcInvoicePaymentOutcome::Paid)),
|
||||
Some("pending") => Ok(Some(NwcInvoicePaymentOutcome::Pending(anyhow!(
|
||||
"invoice {invoice_id} has a pending NWC reconciliation; refusing to create a new Lightning charge"
|
||||
)))),
|
||||
Some(other) => Err(anyhow!(
|
||||
"unknown invoice_nwc_payment state '{other}' for invoice {invoice_id}"
|
||||
)),
|
||||
None => Ok(None),
|
||||
}
|
||||
method: &str,
|
||||
) -> Result<()> {
|
||||
self.command
|
||||
.mark_lightning_invoice_paid(stripe_invoice_id, method)
|
||||
.await?;
|
||||
self.stripe.pay_invoice_out_of_band(stripe_invoice_id).await?;
|
||||
self.command.clear_tenant_nwc_error(tenant_pubkey).await?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
+42
-32
@@ -298,19 +298,27 @@ impl Command {
|
||||
|
||||
// Invoices
|
||||
|
||||
pub async fn insert_pending_invoice_nwc_payment(
|
||||
/// Insert a freshly minted pending bolt11 for an invoice. Returns `false` if
|
||||
/// a row already exists (lost an insert race), in which case the caller
|
||||
/// should read and use the existing row's bolt11.
|
||||
pub async fn insert_pending_lightning_invoice(
|
||||
&self,
|
||||
invoice_id: &str,
|
||||
stripe_invoice_id: &str,
|
||||
tenant_pubkey: &str,
|
||||
bolt11: &str,
|
||||
expires_at: i64,
|
||||
) -> Result<bool> {
|
||||
let now = chrono::Utc::now().timestamp();
|
||||
let result = sqlx::query(
|
||||
"INSERT INTO invoice_nwc_payment (invoice_id, tenant_pubkey, state, created_at, updated_at)
|
||||
VALUES (?, ?, 'pending', ?, ?)
|
||||
ON CONFLICT(invoice_id) DO NOTHING",
|
||||
"INSERT INTO lightning_invoice
|
||||
(stripe_invoice_id, tenant_pubkey, bolt11, status, expires_at, created_at, updated_at)
|
||||
VALUES (?, ?, ?, 'pending', ?, ?, ?)
|
||||
ON CONFLICT(stripe_invoice_id) DO NOTHING",
|
||||
)
|
||||
.bind(invoice_id)
|
||||
.bind(stripe_invoice_id)
|
||||
.bind(tenant_pubkey)
|
||||
.bind(bolt11)
|
||||
.bind(expires_at)
|
||||
.bind(now)
|
||||
.bind(now)
|
||||
.execute(&self.pool)
|
||||
@@ -319,46 +327,48 @@ impl Command {
|
||||
Ok(result.rows_affected() > 0)
|
||||
}
|
||||
|
||||
pub async fn mark_invoice_nwc_payment_paid(&self, invoice_id: &str) -> Result<()> {
|
||||
/// Replace the stored bolt11 for a still-pending invoice whose previous
|
||||
/// invoice expired. No-op once the invoice is paid, so this can never
|
||||
/// overwrite a settled invoice.
|
||||
pub async fn regenerate_lightning_invoice(
|
||||
&self,
|
||||
stripe_invoice_id: &str,
|
||||
bolt11: &str,
|
||||
expires_at: i64,
|
||||
) -> Result<()> {
|
||||
let now = chrono::Utc::now().timestamp();
|
||||
let result = sqlx::query(
|
||||
"UPDATE invoice_nwc_payment
|
||||
SET state = 'paid', updated_at = ?
|
||||
WHERE invoice_id = ?",
|
||||
sqlx::query(
|
||||
"UPDATE lightning_invoice
|
||||
SET bolt11 = ?, expires_at = ?, updated_at = ?
|
||||
WHERE stripe_invoice_id = ? AND status = 'pending'",
|
||||
)
|
||||
.bind(bolt11)
|
||||
.bind(expires_at)
|
||||
.bind(now)
|
||||
.bind(invoice_id)
|
||||
.bind(stripe_invoice_id)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
|
||||
if result.rows_affected() == 0 {
|
||||
anyhow::bail!("invoice_nwc_payment row missing for invoice_id: {invoice_id}");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn insert_manual_lightning_invoice_payment(
|
||||
&self,
|
||||
invoice_id: &str,
|
||||
tenant_pubkey: &str,
|
||||
bolt11: &str,
|
||||
) -> Result<bool> {
|
||||
/// Mark a pending invoice paid, recording which method settled it. The
|
||||
/// `status = 'pending'` guard makes this idempotent and first-writer-wins:
|
||||
/// a later reconcile won't clobber the method recorded by whoever settled
|
||||
/// it first.
|
||||
pub async fn mark_lightning_invoice_paid(&self, stripe_invoice_id: &str, method: &str) -> Result<()> {
|
||||
let now = chrono::Utc::now().timestamp();
|
||||
let result = sqlx::query(
|
||||
"INSERT INTO invoice_manual_lightning_payment
|
||||
(invoice_id, tenant_pubkey, bolt11, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
ON CONFLICT(invoice_id) DO NOTHING",
|
||||
sqlx::query(
|
||||
"UPDATE lightning_invoice
|
||||
SET status = 'paid', paid_method = ?, updated_at = ?
|
||||
WHERE stripe_invoice_id = ? AND status = 'pending'",
|
||||
)
|
||||
.bind(invoice_id)
|
||||
.bind(tenant_pubkey)
|
||||
.bind(bolt11)
|
||||
.bind(now)
|
||||
.bind(method)
|
||||
.bind(now)
|
||||
.bind(stripe_invoice_id)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
|
||||
Ok(result.rows_affected() > 0)
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,6 +36,18 @@ pub struct Tenant {
|
||||
pub past_due_at: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
|
||||
pub struct LightningInvoice {
|
||||
pub stripe_invoice_id: String,
|
||||
pub tenant_pubkey: String,
|
||||
pub bolt11: String,
|
||||
pub status: String,
|
||||
pub paid_method: Option<String>,
|
||||
pub expires_at: i64,
|
||||
pub created_at: i64,
|
||||
pub updated_at: i64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
|
||||
pub struct Relay {
|
||||
pub id: String,
|
||||
|
||||
+9
-19
@@ -2,7 +2,7 @@ use anyhow::Result;
|
||||
use sqlx::SqlitePool;
|
||||
|
||||
use crate::env::Env;
|
||||
use crate::models::{Activity, Plan, Relay, Tenant};
|
||||
use crate::models::{Activity, LightningInvoice, Plan, Relay, Tenant};
|
||||
|
||||
fn select_tenant(tail: &str) -> String {
|
||||
format!("SELECT * FROM tenant {tail}")
|
||||
@@ -134,29 +134,19 @@ impl Query {
|
||||
Ok(row)
|
||||
}
|
||||
|
||||
// Invoice state
|
||||
// Invoices
|
||||
|
||||
pub async fn get_invoice_nwc_payment_state(&self, invoice_id: &str) -> Result<Option<String>> {
|
||||
let state = sqlx::query_scalar::<_, String>(
|
||||
"SELECT state FROM invoice_nwc_payment WHERE invoice_id = ?",
|
||||
)
|
||||
.bind(invoice_id)
|
||||
.fetch_optional(&self.pool)
|
||||
.await?;
|
||||
Ok(state)
|
||||
}
|
||||
|
||||
pub async fn get_invoice_manual_lightning_bolt11(
|
||||
pub async fn get_lightning_invoice(
|
||||
&self,
|
||||
invoice_id: &str,
|
||||
) -> Result<Option<String>> {
|
||||
let bolt11 = sqlx::query_scalar::<_, String>(
|
||||
"SELECT bolt11 FROM invoice_manual_lightning_payment WHERE invoice_id = ?",
|
||||
stripe_invoice_id: &str,
|
||||
) -> Result<Option<LightningInvoice>> {
|
||||
let row = sqlx::query_as::<_, LightningInvoice>(
|
||||
"SELECT * FROM lightning_invoice WHERE stripe_invoice_id = ?",
|
||||
)
|
||||
.bind(invoice_id)
|
||||
.bind(stripe_invoice_id)
|
||||
.fetch_optional(&self.pool)
|
||||
.await?;
|
||||
Ok(bolt11)
|
||||
Ok(row)
|
||||
}
|
||||
|
||||
// Activity
|
||||
|
||||
@@ -26,47 +26,30 @@ pub async fn get_invoice(
|
||||
AuthedPubkey(auth): AuthedPubkey,
|
||||
Path(id): Path<String>,
|
||||
) -> ApiResult {
|
||||
let Some(invoice) = self.stripe.get_invoice(id).await? else {
|
||||
return not_found("invoice not found")
|
||||
};
|
||||
|
||||
let tenant = api
|
||||
.query
|
||||
.get_tenant_by_stripe_customer_id(&invoice.customer)
|
||||
.await?
|
||||
.ok_or_else(|| anyhow!("invoice not found"))?;
|
||||
|
||||
api.require_admin_or_tenant(&auth, &tenant.pubkey)?;
|
||||
let (invoice, _tenant) = load_authorized_invoice(&api, &auth, &id).await?;
|
||||
|
||||
let invoice = api
|
||||
.billing
|
||||
.reconcile_manual_lightning_invoice(&id, &invoice)
|
||||
.reconcile_invoice(&invoice)
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
|
||||
ok(invoice)
|
||||
}
|
||||
|
||||
pub async fn get_invoice_bolt11(
|
||||
pub async fn get_lightning_invoice(
|
||||
State(api): State<Arc<Api>>,
|
||||
AuthedPubkey(auth): AuthedPubkey,
|
||||
Path(id): Path<String>,
|
||||
) -> ApiResult {
|
||||
let Some(invoice) = self.stripe.get_invoice(id).await? else {
|
||||
return not_found("invoice not found")
|
||||
};
|
||||
|
||||
let tenant = api
|
||||
.query
|
||||
.get_tenant_by_stripe_customer_id(&invoice.customer)
|
||||
.await?
|
||||
.ok_or_else(|| anyhow!("invoice not found"))?;
|
||||
|
||||
api.require_admin_or_tenant(&auth, &tenant.pubkey)?;
|
||||
let (invoice, tenant) = load_authorized_invoice(&api, &auth, &id).await?;
|
||||
|
||||
// Settle first: this checks the currently-stored bolt11 against the wallet,
|
||||
// so a payment that landed before expiry is always caught before we'd
|
||||
// consider regenerating below.
|
||||
let invoice = api
|
||||
.billing
|
||||
.reconcile_manual_lightning_invoice(&id, &invoice)
|
||||
.reconcile_invoice(&invoice)
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
|
||||
@@ -74,39 +57,37 @@ pub async fn get_invoice_bolt11(
|
||||
return Err(bad_request("invoice-not-open", "invoice is not open"));
|
||||
}
|
||||
|
||||
let bolt11 = if let Some(existing_bolt11) = api
|
||||
.query
|
||||
.get_invoice_manual_lightning_bolt11(&id)
|
||||
let bolt11 = api
|
||||
.billing
|
||||
.ensure_lightning_invoice(&invoice.id, &tenant.pubkey, invoice.amount_due, &invoice.currency)
|
||||
.await
|
||||
.map_err(internal)?
|
||||
{
|
||||
existing_bolt11
|
||||
} else {
|
||||
let bolt11 = api
|
||||
.billing
|
||||
.create_bolt11(invoice.amount_due, &invoice.currency)
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
|
||||
if api
|
||||
.command
|
||||
.insert_manual_lightning_invoice_payment(&id, &tenant.pubkey, &bolt11)
|
||||
.await
|
||||
.map_err(internal)?
|
||||
{
|
||||
bolt11
|
||||
} else {
|
||||
api.query
|
||||
.get_invoice_manual_lightning_bolt11(&id)
|
||||
.await
|
||||
.map_err(internal)?
|
||||
.ok_or_else(|| {
|
||||
internal(format!(
|
||||
"manual lightning payment row missing after insert race for invoice {id}"
|
||||
))
|
||||
})?
|
||||
}
|
||||
};
|
||||
.map_err(internal)?;
|
||||
|
||||
ok(serde_json::json!({ "bolt11": bolt11 }))
|
||||
}
|
||||
|
||||
/// Fetch a Stripe invoice and the tenant that owns it, enforcing that the
|
||||
/// caller is that tenant (or an admin). Returns 404 if the invoice or its
|
||||
/// tenant can't be found.
|
||||
async fn load_authorized_invoice(
|
||||
api: &Api,
|
||||
auth: &str,
|
||||
stripe_invoice_id: &str,
|
||||
) -> Result<(crate::stripe::StripeInvoice, crate::models::Tenant), crate::web::ApiError> {
|
||||
let Some(invoice) = api.stripe.get_invoice(stripe_invoice_id).await.map_err(internal)? else {
|
||||
return Err(not_found("invoice not found"));
|
||||
};
|
||||
|
||||
let Some(tenant) = api
|
||||
.query
|
||||
.get_tenant_by_stripe_customer_id(&invoice.customer)
|
||||
.await
|
||||
.map_err(internal)?
|
||||
else {
|
||||
return Err(not_found("invoice not found"));
|
||||
};
|
||||
|
||||
api.require_admin_or_tenant(auth, &tenant.pubkey)?;
|
||||
|
||||
Ok((invoice, tenant))
|
||||
}
|
||||
|
||||
@@ -9,7 +9,6 @@ use axum::{
|
||||
use serde::Deserialize;
|
||||
|
||||
use crate::api::{Api, AuthedPubkey};
|
||||
use crate::billing::NwcInvoicePaymentOutcome;
|
||||
use crate::models::{RELAY_STATUS_ACTIVE, RELAY_STATUS_DELINQUENT};
|
||||
use crate::web::{ApiResult, bad_request, internal, ok};
|
||||
|
||||
@@ -75,8 +74,8 @@ async fn handle_webhook(api: &Api, payload: &str, signature: &str) -> Result<()>
|
||||
let customer = obj["customer"].as_str().unwrap_or_default();
|
||||
let amount_due = obj["amount_due"].as_i64().unwrap_or(0);
|
||||
let currency = obj["currency"].as_str().unwrap_or("usd");
|
||||
let invoice_id = obj["id"].as_str().unwrap_or_default();
|
||||
handle_invoice_created(api, customer, amount_due, currency, invoice_id).await?;
|
||||
let stripe_invoice_id = obj["id"].as_str().unwrap_or_default();
|
||||
handle_invoice_created(api, customer, amount_due, currency, stripe_invoice_id).await?;
|
||||
}
|
||||
"invoice.paid" => {
|
||||
let customer = obj["customer"].as_str().unwrap_or_default();
|
||||
@@ -114,7 +113,7 @@ async fn handle_invoice_created(
|
||||
stripe_customer_id: &str,
|
||||
amount_due: i64,
|
||||
currency: &str,
|
||||
invoice_id: &str,
|
||||
stripe_invoice_id: &str,
|
||||
) -> Result<()> {
|
||||
if amount_due == 0 {
|
||||
return Ok(());
|
||||
@@ -128,6 +127,12 @@ async fn handle_invoice_created(
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
// Mint (or reuse) the single bolt11 that both NWC and manual payment settle.
|
||||
let bolt11 = api
|
||||
.billing
|
||||
.ensure_lightning_invoice(stripe_invoice_id, &tenant.pubkey, amount_due, currency)
|
||||
.await?;
|
||||
|
||||
let mut nwc_error_for_dm: Option<String> = None;
|
||||
|
||||
// 1. NWC auto-pay: if the tenant has a nwc_url
|
||||
@@ -135,22 +140,11 @@ async fn handle_invoice_created(
|
||||
let plain_nwc_url = api.env.decrypt(&tenant.nwc_url)?;
|
||||
match api
|
||||
.billing
|
||||
.nwc_pay_invoice(
|
||||
invoice_id,
|
||||
&tenant.pubkey,
|
||||
amount_due,
|
||||
currency,
|
||||
&plain_nwc_url,
|
||||
)
|
||||
.await?
|
||||
.nwc_pay_invoice(stripe_invoice_id, &tenant.pubkey, &bolt11, &plain_nwc_url)
|
||||
.await
|
||||
{
|
||||
NwcInvoicePaymentOutcome::Paid => {
|
||||
api.billing
|
||||
.mark_invoice_paid_out_of_band_after_nwc(invoice_id, &tenant.pubkey)
|
||||
.await?;
|
||||
return Ok(());
|
||||
}
|
||||
NwcInvoicePaymentOutcome::Fallback(e) => {
|
||||
Ok(()) => return Ok(()),
|
||||
Err(e) => {
|
||||
let error_msg = format!("{e}");
|
||||
api.command
|
||||
.set_tenant_nwc_error(&tenant.pubkey, &error_msg)
|
||||
@@ -159,25 +153,11 @@ async fn handle_invoice_created(
|
||||
error = %e,
|
||||
tenant_pubkey = %tenant.pubkey,
|
||||
stripe_customer_id,
|
||||
invoice_id,
|
||||
stripe_invoice_id,
|
||||
"nwc auto-payment failed for invoice.created"
|
||||
);
|
||||
nwc_error_for_dm = summarize_nwc_error_for_dm(&error_msg);
|
||||
// Fall through to next option
|
||||
}
|
||||
NwcInvoicePaymentOutcome::Pending(e) => {
|
||||
let error_msg = format!("{e}");
|
||||
api.command
|
||||
.set_tenant_nwc_error(&tenant.pubkey, &error_msg)
|
||||
.await?;
|
||||
tracing::error!(
|
||||
error = %e,
|
||||
tenant_pubkey = %tenant.pubkey,
|
||||
stripe_customer_id,
|
||||
invoice_id,
|
||||
"nwc auto-payment requires reconciliation before retry"
|
||||
);
|
||||
return Err(e);
|
||||
// Fall through to card / manual payment
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,14 +17,19 @@ impl Wallet {
|
||||
Ok(Self { url })
|
||||
}
|
||||
|
||||
pub async fn make_invoice(&self, amount_msats: u64, description: &str) -> Result<String> {
|
||||
pub async fn make_invoice(
|
||||
&self,
|
||||
amount_msats: u64,
|
||||
description: &str,
|
||||
expiry_secs: u64,
|
||||
) -> Result<String> {
|
||||
let nwc = NWC::new(self.url.clone());
|
||||
let result = nwc
|
||||
.make_invoice(MakeInvoiceRequest {
|
||||
amount: amount_msats,
|
||||
description: Some(description.to_string()),
|
||||
description_hash: None,
|
||||
expiry: None,
|
||||
expiry: Some(expiry_secs),
|
||||
})
|
||||
.await;
|
||||
nwc.shutdown().await;
|
||||
|
||||
Reference in New Issue
Block a user