Compare commits
7 Commits
8c44d8cc0f
...
v0.1.0
| Author | SHA1 | Date | |
|---|---|---|---|
| 43eaad1621 | |||
| 5e6d5ab7c4 | |||
| a9f66dc3e5 | |||
| ffb1491f00 | |||
| 4dc8ea942d | |||
| 0e18d4020a | |||
| b702733559 |
@@ -21,6 +21,8 @@ When referring to a tenant's pubkey, always name it `tenant_pubkey`, not `tenant
|
|||||||
|
|
||||||
Pre-release: squash schema changes into `0001_init.sql` rather than adding new migration files. Once released, migrations become append-only.
|
Pre-release: squash schema changes into `0001_init.sql` rather than adding new migration files. Once released, migrations become append-only.
|
||||||
|
|
||||||
|
Document indexes (what use cases they support), but not tables (those are documented in `models.rs`).
|
||||||
|
|
||||||
## Markdown
|
## Markdown
|
||||||
|
|
||||||
Do not hard-break markdown files at a certain number of characters. Allow readers to implement line wrapping naturally instead.
|
Do not hard-break markdown files at a certain number of characters. Allow readers to implement line wrapping naturally instead.
|
||||||
|
|||||||
@@ -69,6 +69,7 @@ CREATE TABLE IF NOT EXISTS invoice_item (
|
|||||||
amount INTEGER NOT NULL,
|
amount INTEGER NOT NULL,
|
||||||
description TEXT NOT NULL DEFAULT '',
|
description TEXT NOT NULL DEFAULT '',
|
||||||
created_at INTEGER NOT NULL,
|
created_at INTEGER NOT NULL,
|
||||||
|
voided_at INTEGER,
|
||||||
FOREIGN KEY (invoice_id) REFERENCES invoice(id),
|
FOREIGN KEY (invoice_id) REFERENCES invoice(id),
|
||||||
FOREIGN KEY (tenant_pubkey) REFERENCES tenant(pubkey)
|
FOREIGN KEY (tenant_pubkey) REFERENCES tenant(pubkey)
|
||||||
);
|
);
|
||||||
@@ -87,7 +88,21 @@ CREATE TABLE IF NOT EXISTS bolt11 (
|
|||||||
CREATE TABLE IF NOT EXISTS intent (
|
CREATE TABLE IF NOT EXISTS intent (
|
||||||
id TEXT PRIMARY KEY,
|
id TEXT PRIMARY KEY,
|
||||||
invoice_id TEXT NOT NULL,
|
invoice_id TEXT NOT NULL,
|
||||||
|
payment_method_id TEXT NOT NULL,
|
||||||
|
payment_intent_id TEXT,
|
||||||
created_at INTEGER NOT NULL,
|
created_at INTEGER NOT NULL,
|
||||||
|
settled_at INTEGER,
|
||||||
|
FOREIGN KEY (invoice_id) REFERENCES invoice(id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS checkout (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
invoice_id TEXT NOT NULL,
|
||||||
|
session_id TEXT NOT NULL,
|
||||||
|
url TEXT NOT NULL,
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
expires_at INTEGER NOT NULL,
|
||||||
|
settled_at INTEGER,
|
||||||
FOREIGN KEY (invoice_id) REFERENCES invoice(id)
|
FOREIGN KEY (invoice_id) REFERENCES invoice(id)
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -106,9 +121,15 @@ CREATE INDEX IF NOT EXISTS idx_invoice_open ON invoice (tenant_pubkey, created_a
|
|||||||
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_invoice_item_invoice ON invoice_item (invoice_id);
|
CREATE INDEX IF NOT EXISTS idx_invoice_item_invoice ON invoice_item (invoice_id);
|
||||||
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_invoice_item_outstanding ON invoice_item (tenant_pubkey) WHERE invoice_id IS NULL;
|
CREATE INDEX IF NOT EXISTS idx_invoice_item_outstanding ON invoice_item (tenant_pubkey) WHERE invoice_id IS NULL AND voided_at IS NULL;
|
||||||
|
|
||||||
-- At most one line item per billable activity to ensure no double-billing.
|
-- At most one line item per billable activity to ensure no double-billing.
|
||||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_invoice_item_activity ON invoice_item (activity_id);
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_invoice_item_activity ON invoice_item (activity_id);
|
||||||
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_bolt11_invoice_created ON bolt11 (invoice_id, created_at);
|
CREATE INDEX IF NOT EXISTS idx_bolt11_invoice_created ON bolt11 (invoice_id, created_at);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_checkout_invoice_created ON checkout (invoice_id, created_at);
|
||||||
|
|
||||||
|
-- At most one unsettled write-ahead intent per invoice: enforces the invariant
|
||||||
|
-- and is the ON CONFLICT target for the get-or-create in `ensure_pending_intent`.
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_intent_unsettled ON intent (invoice_id) WHERE settled_at IS NULL;
|
||||||
|
|||||||
+3
-1
@@ -33,7 +33,8 @@ use crate::query;
|
|||||||
use crate::robot::Robot;
|
use crate::robot::Robot;
|
||||||
use crate::routes::identity::get_identity;
|
use crate::routes::identity::get_identity;
|
||||||
use crate::routes::invoices::{
|
use crate::routes::invoices::{
|
||||||
ensure_invoice_bolt11, get_invoice, list_invoice_items, list_invoices, reconcile_invoice,
|
ensure_invoice_bolt11, ensure_invoice_checkout, get_invoice, list_invoice_items, list_invoices,
|
||||||
|
reconcile_invoice,
|
||||||
};
|
};
|
||||||
use crate::routes::plans::{get_plan, list_plans};
|
use crate::routes::plans::{get_plan, list_plans};
|
||||||
use crate::routes::relays::{
|
use crate::routes::relays::{
|
||||||
@@ -93,6 +94,7 @@ impl Api {
|
|||||||
.route("/invoices", get(list_invoices))
|
.route("/invoices", get(list_invoices))
|
||||||
.route("/invoices/:id", get(get_invoice))
|
.route("/invoices/:id", get(get_invoice))
|
||||||
.route("/invoices/:id/reconcile", post(reconcile_invoice))
|
.route("/invoices/:id/reconcile", post(reconcile_invoice))
|
||||||
|
.route("/invoices/:id/checkout", post(ensure_invoice_checkout))
|
||||||
.route("/invoices/:id/bolt11", post(ensure_invoice_bolt11))
|
.route("/invoices/:id/bolt11", post(ensure_invoice_bolt11))
|
||||||
.route("/invoices/:id/items", get(list_invoice_items))
|
.route("/invoices/:id/items", get(list_invoice_items))
|
||||||
.with_state(api)
|
.with_state(api)
|
||||||
|
|||||||
+203
-73
@@ -5,7 +5,7 @@ use crate::bitcoin;
|
|||||||
use crate::command;
|
use crate::command;
|
||||||
use crate::env;
|
use crate::env;
|
||||||
use crate::models::{
|
use crate::models::{
|
||||||
Activity, Bolt11, Invoice, InvoiceItem, RELAY_STATUS_ACTIVE, Snapshot, Tenant,
|
Activity, Bolt11, Checkout, Invoice, InvoiceItem, RELAY_STATUS_ACTIVE, Snapshot, Tenant,
|
||||||
};
|
};
|
||||||
use crate::query;
|
use crate::query;
|
||||||
use crate::robot::Robot;
|
use crate::robot::Robot;
|
||||||
@@ -89,13 +89,15 @@ impl Billing {
|
|||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
let mut tenant = tenant.clone();
|
let mut tenant = tenant.clone();
|
||||||
|
|
||||||
let activities = query::list_billable_activity(&tenant.pubkey).await?;
|
let mut activities = query::list_billable_activity(&tenant.pubkey).await?;
|
||||||
|
|
||||||
// A churned tenant with fresh billable activity is using the service
|
// A churned tenant with fresh billable activity is using the service
|
||||||
// again: re-activate billing (and restore their relays) before billing it.
|
// again: re-activate billing (and restore their relays) before billing it.
|
||||||
|
// Reactivation records a billable activity for each restored relay; fold
|
||||||
|
// those into this pass so their prorated charges land on the same invoice.
|
||||||
if tenant.churned_at.is_some() && !activities.is_empty() {
|
if tenant.churned_at.is_some() && !activities.is_empty() {
|
||||||
let relays = query::list_relays_for_tenant(&tenant.pubkey).await?;
|
let relays = query::list_relays_for_tenant(&tenant.pubkey).await?;
|
||||||
command::reactivate_tenant(&tenant.pubkey, &relays).await?;
|
activities.extend(command::reactivate_tenant(&tenant.pubkey, &relays).await?);
|
||||||
tenant.churned_at = None;
|
tenant.churned_at = None;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -120,10 +122,25 @@ impl Billing {
|
|||||||
command::create_invoice(&tenant, &period).await?;
|
command::create_invoice(&tenant, &period).await?;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Attempt payment on every open invoice after syncing with stripe.
|
// Fetch the tenant's open invoices once
|
||||||
|
let invoices = query::list_open_invoices(&tenant.pubkey).await?;
|
||||||
|
|
||||||
|
// If the tenant is past due, churn them
|
||||||
|
if self.maybe_churn_tenant(&tenant, &invoices).await? {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
// If we're going to try to collect, make sure we have an updated payment method
|
||||||
if attempt_payment {
|
if attempt_payment {
|
||||||
tenant.stripe_payment_method_id = self.sync_stripe_customer(&tenant).await?;
|
tenant.stripe_payment_method_id = self.sync_stripe_customer(&tenant).await?;
|
||||||
self.collect_open_invoices(&tenant).await?;
|
}
|
||||||
|
|
||||||
|
// Reconcile out-of-band payments (and, when collecting, charge) on every
|
||||||
|
// open invoice. The out-of-band checks run even when attempt_payment is
|
||||||
|
// false, so a checkout or bolt11 paid out of band settles on any reconcile.
|
||||||
|
for invoice in &invoices {
|
||||||
|
self.reconcile_payments(&tenant, invoice, attempt_payment, true)
|
||||||
|
.await?;
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -139,12 +156,12 @@ impl Billing {
|
|||||||
self.make_prorated_item(tenant, activity, 1, "New relay created")
|
self.make_prorated_item(tenant, activity, 1, "New relay created")
|
||||||
.await?
|
.await?
|
||||||
}
|
}
|
||||||
"activate_relay" => {
|
"activate_relay" | "unmark_relay_delinquent" => {
|
||||||
self.make_prorated_item(tenant, activity, 1, "Relay reactivated")
|
self.make_prorated_item(tenant, activity, 1, "Relay reactivated")
|
||||||
.await?
|
.await?
|
||||||
}
|
}
|
||||||
"deactivate_relay" => {
|
"deactivate_relay" => {
|
||||||
self.make_prorated_item(tenant, activity, -1, "Relay deactivated (prorated credit)")
|
self.make_prorated_item(tenant, activity, -1, "Relay deactivated")
|
||||||
.await?
|
.await?
|
||||||
}
|
}
|
||||||
"update_relay" => self.make_plan_change_item(tenant, activity).await?,
|
"update_relay" => self.make_plan_change_item(tenant, activity).await?,
|
||||||
@@ -188,6 +205,7 @@ impl Billing {
|
|||||||
amount,
|
amount,
|
||||||
description: description.to_string(),
|
description: description.to_string(),
|
||||||
created_at: activity.created_at,
|
created_at: activity.created_at,
|
||||||
|
voided_at: None,
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -234,6 +252,7 @@ impl Billing {
|
|||||||
amount,
|
amount,
|
||||||
description,
|
description,
|
||||||
created_at: activity.created_at,
|
created_at: activity.created_at,
|
||||||
|
voided_at: None,
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -276,6 +295,7 @@ impl Billing {
|
|||||||
amount: plan.amount,
|
amount: plan.amount,
|
||||||
description: "Subscription renewal".to_string(),
|
description: "Subscription renewal".to_string(),
|
||||||
created_at: period.start,
|
created_at: period.start,
|
||||||
|
voided_at: None,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -284,87 +304,114 @@ impl Billing {
|
|||||||
command::insert_invoice_items_for_renewal(&line_items, period).await
|
command::insert_invoice_items_for_renewal(&line_items, period).await
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Payments ---
|
// --- Auto-churn ---
|
||||||
|
|
||||||
/// Dunning pass over a tenant's open invoices: if the oldest has been unpaid
|
/// Churn a tenant whose oldest open invoice has blown past the grace period:
|
||||||
/// past the grace period, churn the tenant; otherwise retry payment on each.
|
/// pause their relays and DM them once, on the transition into churn. Returns
|
||||||
async fn collect_open_invoices(&self, tenant: &Tenant) -> Result<()> {
|
/// whether the tenant is past due, so the caller can skip collecting this pass.
|
||||||
let open = query::list_open_invoices(&tenant.pubkey).await?;
|
async fn maybe_churn_tenant(&self, tenant: &Tenant, invoices: &[Invoice]) -> Result<bool> {
|
||||||
let Some(oldest) = open.first() else {
|
let Some(oldest) = invoices.first() else {
|
||||||
return Ok(());
|
return Ok(false);
|
||||||
};
|
};
|
||||||
|
|
||||||
let now = chrono::Utc::now().timestamp();
|
let now = chrono::Utc::now().timestamp();
|
||||||
if now - oldest.created_at >= GRACE_PERIOD_SECS {
|
if now - oldest.created_at < GRACE_PERIOD_SECS {
|
||||||
if tenant.churned_at.is_none() {
|
return Ok(false);
|
||||||
let relays = query::list_relays_for_tenant(&tenant.pubkey).await?;
|
}
|
||||||
command::churn_tenant(&tenant.pubkey, now, &relays).await?;
|
|
||||||
|
|
||||||
// Notify the tenant once, on the transition into churn (the guard
|
// Past due. Churn once (the guard fires a single time on the transition)
|
||||||
// above fires this a single time). Log-and-continue on failure.
|
// and notify the tenant, logging and continuing on DM failure.
|
||||||
let message = format!("{CHURN_DM}\n\n{}/account", env::get().app_url);
|
if tenant.churned_at.is_none() {
|
||||||
if let Err(e) = self.robot.send_dm(&tenant.pubkey, &message).await {
|
let relays = query::list_relays_for_tenant(&tenant.pubkey).await?;
|
||||||
tracing::error!(tenant = %tenant.pubkey, error = %e, "failed to send churn DM");
|
command::churn_tenant(&tenant.pubkey, now, &relays).await?;
|
||||||
}
|
|
||||||
|
let message = format!("{CHURN_DM}\n\n{}/account", env::get().app_url);
|
||||||
|
if let Err(e) = self.robot.send_dm(&tenant.pubkey, &message).await {
|
||||||
|
tracing::error!(tenant = %tenant.pubkey, error = %e, "failed to send churn DM");
|
||||||
}
|
}
|
||||||
return Ok(());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
for invoice in &open {
|
Ok(true)
|
||||||
self.attempt_payment(tenant, invoice, true).await?;
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Collect an invoice via NWC, then a saved card, then (when `notify`) a
|
// --- Payments ---
|
||||||
/// manual DM. A failing method's error is stored on the tenant (to warn them
|
|
||||||
/// in the UI) but never aborts the cascade or future retries; a method's
|
/// Collect an invoice. We check the out-of-band rails first — a Lightning
|
||||||
/// error is cleared when it next succeeds. Caller-initiated payments pass
|
/// invoice or Checkout session the tenant may have already paid — and only
|
||||||
/// `notify = false` to skip the dunning DM, since the failure is already
|
/// then initiate a fresh charge (NWC, then a saved card), so a payment that's
|
||||||
/// surfaced on screen.
|
/// already in flight is never duplicated. Falling all the way through sends a
|
||||||
pub async fn attempt_payment(
|
/// manual-payment DM (when `notify`). A failing charge's error is stored on
|
||||||
|
/// the tenant (to warn them in the UI) but never aborts the cascade or future
|
||||||
|
/// retries; it's cleared when a method next succeeds. Caller-initiated
|
||||||
|
/// payments pass `notify = false` to skip the dunning DM, since the failure
|
||||||
|
/// is already surfaced on screen.
|
||||||
|
pub async fn reconcile_payments(
|
||||||
&self,
|
&self,
|
||||||
tenant: &Tenant,
|
tenant: &Tenant,
|
||||||
invoice: &Invoice,
|
invoice: &Invoice,
|
||||||
|
autopay: bool,
|
||||||
notify: bool,
|
notify: bool,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
let mut error_message: Option<String> = None;
|
let mut error_message: Option<String> = None;
|
||||||
|
|
||||||
// 1. NWC auto-pay: if the tenant has configured an nwc_url, try it first.
|
// 1. Out-of-band lightning: settle a bolt11 paid out of band (e.g. a
|
||||||
if !tenant.nwc_url.is_empty() {
|
// manual QR scan, or an NWC pay that completed but failed to record).
|
||||||
match self.attempt_payment_using_nwc(tenant, invoice).await {
|
// Checked before any charge so we never bill on top of it.
|
||||||
Ok(()) => return Ok(()),
|
|
||||||
Err(e) => error_message = Some(format!("{e}")),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2. Out-of-band lightning: catches partially failed NWC or manual payment
|
|
||||||
if let Some(bolt11) = query::get_bolt11_for_invoice(&invoice.id).await?
|
if let Some(bolt11) = query::get_bolt11_for_invoice(&invoice.id).await?
|
||||||
&& bolt11.settled_at.is_none()
|
&& bolt11.settled_at.is_none()
|
||||||
&& self.wallet.is_settled(&bolt11.lnbc).await.unwrap_or(false)
|
&& self.wallet.is_settled(&bolt11.lnbc).await.unwrap_or(false)
|
||||||
{
|
{
|
||||||
command::settle_invoice_out_of_band(&bolt11.id, &invoice.id).await?;
|
command::settle_invoice_out_of_band(&bolt11.id, &invoice.id).await?;
|
||||||
|
return self.cleanup_pending_payments(invoice).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Hosted Checkout: settle an invoice the tenant paid (and
|
||||||
|
// authenticated) on a Stripe Checkout session that has since completed.
|
||||||
|
// Also checked before any charge so we never bill on top of it.
|
||||||
|
if let Some(checkout) = query::get_checkout_for_invoice(&invoice.id).await?
|
||||||
|
&& checkout.settled_at.is_none()
|
||||||
|
&& self
|
||||||
|
.stripe
|
||||||
|
.is_checkout_paid(&checkout.session_id)
|
||||||
|
.await
|
||||||
|
.unwrap_or(false)
|
||||||
|
{
|
||||||
|
command::settle_invoice_via_checkout(&tenant.pubkey, &checkout.id, &invoice.id).await?;
|
||||||
|
return self.cleanup_pending_payments(invoice).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
if !autopay {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3. Payment method on file: charge the tenant's cached Stripe payment
|
// 3. NWC auto-pay: if the tenant has configured an nwc_url, charge it.
|
||||||
|
if !tenant.nwc_url.is_empty() {
|
||||||
|
match self.attempt_payment_using_nwc(tenant, invoice).await {
|
||||||
|
Ok(()) => return self.cleanup_pending_payments(invoice).await,
|
||||||
|
Err(e) => error_message = Some(format!("{e}")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. Payment method on file: charge the tenant's cached Stripe payment
|
||||||
// method, kept fresh by sync_stripe_payment_method before collection.
|
// method, kept fresh by sync_stripe_payment_method before collection.
|
||||||
if let Some(payment_method) = &tenant.stripe_payment_method_id {
|
if let Some(payment_method) = &tenant.stripe_payment_method_id {
|
||||||
match self
|
match self
|
||||||
.attempt_payment_using_stripe(tenant, invoice, payment_method)
|
.attempt_payment_using_stripe(tenant, invoice, payment_method)
|
||||||
.await
|
.await
|
||||||
{
|
{
|
||||||
Ok(()) => return Ok(()),
|
Ok(()) => return self.cleanup_pending_payments(invoice).await,
|
||||||
Err(e) => error_message = error_message.or_else(|| Some(format!("{e}"))),
|
Err(e) => error_message = error_message.or_else(|| Some(format!("{e}"))),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 4. Manual payment: DM a link to the in-app payment page for this invoice.
|
if !notify {
|
||||||
if notify
|
return Ok(());
|
||||||
&& let Err(e) = self
|
}
|
||||||
.attempt_payment_using_dm(tenant, invoice, error_message)
|
|
||||||
.await
|
// 5. Manual payment: DM a link to the in-app payment page for this invoice.
|
||||||
|
if let Err(e) = self
|
||||||
|
.attempt_payment_using_dm(tenant, invoice, error_message)
|
||||||
|
.await
|
||||||
{
|
{
|
||||||
tracing::error!(
|
tracing::error!(
|
||||||
tenant = %tenant.pubkey,
|
tenant = %tenant.pubkey,
|
||||||
@@ -403,28 +450,36 @@ impl Billing {
|
|||||||
invoice: &Invoice,
|
invoice: &Invoice,
|
||||||
payment_method_id: &str,
|
payment_method_id: &str,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
let result: Result<()> = async {
|
let intent = command::ensure_pending_intent(&invoice.id, payment_method_id).await?;
|
||||||
let intent_id = self
|
|
||||||
.stripe
|
|
||||||
.create_payment_intent(
|
|
||||||
&tenant.stripe_customer_id,
|
|
||||||
payment_method_id,
|
|
||||||
&invoice.id,
|
|
||||||
invoice.amount,
|
|
||||||
"usd",
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
command::settle_invoice_via_stripe(&tenant.pubkey, &intent_id, &invoice.id).await
|
let payment_intent_id = match self
|
||||||
}
|
.stripe
|
||||||
.await;
|
.create_payment_intent(
|
||||||
|
&tenant.stripe_customer_id,
|
||||||
|
&intent.payment_method_id,
|
||||||
|
&invoice.id,
|
||||||
|
invoice.amount,
|
||||||
|
"usd",
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(id) => id,
|
||||||
|
// Drop the attempt so the next pass retries cleanly on the tenant's
|
||||||
|
// current method, and record the failure to warn the user in the UI.
|
||||||
|
Err(error) => {
|
||||||
|
command::delete_intent(&intent.id).await?;
|
||||||
|
command::set_tenant_stripe_error(&tenant.pubkey, &format!("{error}")).await?;
|
||||||
|
return Err(error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
// Record the failure on the tenant (to warn them in the UI) but still
|
command::settle_invoice_via_intent(
|
||||||
// surface it, so the cascade can fall through and summarize it in the DM.
|
&tenant.pubkey,
|
||||||
if let Err(error) = &result {
|
&intent.id,
|
||||||
command::set_tenant_stripe_error(&tenant.pubkey, &format!("{error}")).await?;
|
&payment_intent_id,
|
||||||
}
|
&invoice.id,
|
||||||
result
|
)
|
||||||
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn attempt_payment_using_dm(
|
async fn attempt_payment_using_dm(
|
||||||
@@ -472,6 +527,26 @@ impl Billing {
|
|||||||
command::mark_invoice_notified(invoice_id).await
|
command::mark_invoice_notified(invoice_id).await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Run after an invoice is settled to invalidate out-of-band payment methods
|
||||||
|
/// so the tenant can't pay twice. Only Stripe Checkout sessions can actually
|
||||||
|
/// be invalidated (by expiring them); Lightning/NWC has no such mechanism.
|
||||||
|
/// The session that just paid (if any) was marked settled in its settle
|
||||||
|
/// transaction, so it's excluded here and not needlessly expired.
|
||||||
|
async fn cleanup_pending_payments(&self, invoice: &Invoice) -> Result<()> {
|
||||||
|
for checkout in query::list_pending_checkouts_for_invoice(&invoice.id).await? {
|
||||||
|
if let Err(error) = self.stripe.expire_checkout_session(&checkout.session_id).await {
|
||||||
|
tracing::debug!(
|
||||||
|
invoice = %invoice.id,
|
||||||
|
checkout = %checkout.id,
|
||||||
|
error = %error,
|
||||||
|
"could not expire checkout session"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
// --- Bolt11 utils ---
|
// --- Bolt11 utils ---
|
||||||
|
|
||||||
pub async fn ensure_bolt11_for_invoice(&self, invoice: &Invoice) -> Result<Bolt11> {
|
pub async fn ensure_bolt11_for_invoice(&self, invoice: &Invoice) -> Result<Bolt11> {
|
||||||
@@ -501,6 +576,61 @@ impl Billing {
|
|||||||
.ok_or_else(|| anyhow!("failed to insert bolt11"))
|
.ok_or_else(|| anyhow!("failed to insert bolt11"))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- Checkout utils ---
|
||||||
|
|
||||||
|
/// Idempotently produce a hosted Stripe Checkout session for an open invoice,
|
||||||
|
/// reusing an unsettled, unexpired one if present — the on-session card
|
||||||
|
/// counterpart to [`Self::ensure_bolt11_for_invoice`]. Checkout lets the
|
||||||
|
/// tenant clear a 3D Secure challenge the off-session card charge can't. On
|
||||||
|
/// success Stripe returns the tenant to their account page, where collection
|
||||||
|
/// is reconciled (here and on the dunning poll) once the session reads paid.
|
||||||
|
pub async fn ensure_checkout_for_invoice(
|
||||||
|
&self,
|
||||||
|
tenant: &Tenant,
|
||||||
|
invoice: &Invoice,
|
||||||
|
) -> Result<Checkout> {
|
||||||
|
let now = chrono::Utc::now().timestamp();
|
||||||
|
|
||||||
|
// Never open a Checkout for an invoice that's already resolved.
|
||||||
|
if invoice.paid_at.is_some() || invoice.voided_at.is_some() {
|
||||||
|
return Err(anyhow!("invoice is not open"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reuse a still-valid pending session so repeated clicks land on one page.
|
||||||
|
if let Some(existing) = query::get_checkout_for_invoice(&invoice.id).await?
|
||||||
|
&& now < existing.expires_at
|
||||||
|
{
|
||||||
|
if existing.settled_at.is_some() {
|
||||||
|
return Err(anyhow!(
|
||||||
|
"a checkout has already been settled for this invoice"
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
return Ok(existing);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Stripe returns the tenant to their account page on success or cancel.
|
||||||
|
// The landing page reconciles the tenant, which now settles a paid
|
||||||
|
// Checkout out of band, so the URL needs no per-invoice marker.
|
||||||
|
let return_url = format!("{}/account", env::get().app_url);
|
||||||
|
|
||||||
|
let (session_id, url, expires_at) = self
|
||||||
|
.stripe
|
||||||
|
.create_checkout_session(
|
||||||
|
&tenant.stripe_customer_id,
|
||||||
|
&invoice.id,
|
||||||
|
invoice.amount,
|
||||||
|
"usd",
|
||||||
|
&return_url,
|
||||||
|
&return_url,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
command::insert_checkout(&invoice.id, &session_id, &url, expires_at)
|
||||||
|
.await?
|
||||||
|
.ok_or_else(|| anyhow!("failed to insert checkout"))
|
||||||
|
}
|
||||||
|
|
||||||
// --- Stripe utils ---
|
// --- Stripe utils ---
|
||||||
|
|
||||||
/// Refresh stripe-related state for a tenant, returning the synced payment
|
/// Refresh stripe-related state for a tenant, returning the synced payment
|
||||||
|
|||||||
+297
-154
@@ -5,8 +5,8 @@ use sqlx::{Sqlite, Transaction};
|
|||||||
use crate::billing::BillingPeriod;
|
use crate::billing::BillingPeriod;
|
||||||
use crate::db::{pool, publish, with_tx};
|
use crate::db::{pool, publish, with_tx};
|
||||||
use crate::models::{
|
use crate::models::{
|
||||||
Activity, Bolt11, Invoice, InvoiceItem, RELAY_STATUS_ACTIVE, RELAY_STATUS_DELINQUENT,
|
Activity, Bolt11, Checkout, Intent, Invoice, InvoiceItem, RELAY_STATUS_ACTIVE,
|
||||||
RELAY_STATUS_INACTIVE, Relay, Snapshot, Tenant,
|
RELAY_STATUS_DELINQUENT, RELAY_STATUS_INACTIVE, Relay, Snapshot, Tenant,
|
||||||
};
|
};
|
||||||
|
|
||||||
// --- Tenants ---
|
// --- Tenants ---
|
||||||
@@ -114,8 +114,10 @@ pub async fn churn_tenant(tenant_pubkey: &str, now: i64, relays: &[Relay]) -> Re
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Atomically re-activate a churned tenant: clear the churn marker, restore every
|
/// Atomically re-activate a churned tenant: clear the churn marker, restore every
|
||||||
/// delinquent relay to active, and void any still-open invoices.
|
/// delinquent relay to active, and void any still-open invoices. Returns the
|
||||||
pub async fn reactivate_tenant(tenant_pubkey: &str, relays: &[Relay]) -> Result<()> {
|
/// `unmark_relay_delinquent` activities recorded for the restored relays, so the
|
||||||
|
/// caller can fold their prorated charges into the same reconcile pass.
|
||||||
|
pub async fn reactivate_tenant(tenant_pubkey: &str, relays: &[Relay]) -> Result<Vec<Activity>> {
|
||||||
let activities = with_tx(async |tx| {
|
let activities = with_tx(async |tx| {
|
||||||
set_tenant_churned_at_tx(tx, tenant_pubkey, None).await?;
|
set_tenant_churned_at_tx(tx, tenant_pubkey, None).await?;
|
||||||
|
|
||||||
@@ -135,10 +137,10 @@ pub async fn reactivate_tenant(tenant_pubkey: &str, relays: &[Relay]) -> Result<
|
|||||||
})
|
})
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
for activity in activities {
|
for activity in &activities {
|
||||||
publish(activity);
|
publish(activity.clone());
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(activities)
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Relays ---
|
// --- Relays ---
|
||||||
@@ -348,20 +350,22 @@ pub async fn mark_activity_billed(activity_id: &str) -> Result<()> {
|
|||||||
|
|
||||||
// --- Invoices ---
|
// --- Invoices ---
|
||||||
|
|
||||||
/// Claim all of a tenant's outstanding items onto a new invoice. A non-positive
|
/// Claim a tenant's outstanding items onto a new invoice once the balance clears
|
||||||
/// balance leaves the items outstanding so the credit carries to the next positive
|
/// the minimum.
|
||||||
/// invoice. Returns the invoice, or `None` when there's nothing to bill.
|
|
||||||
pub async fn create_invoice(tenant: &Tenant, period: &BillingPeriod) -> Result<Option<Invoice>> {
|
pub async fn create_invoice(tenant: &Tenant, period: &BillingPeriod) -> Result<Option<Invoice>> {
|
||||||
with_tx(async |tx| {
|
with_tx(async |tx| {
|
||||||
let total = sqlx::query_scalar::<_, i64>(
|
let total = sqlx::query_scalar::<_, i64>(
|
||||||
"SELECT COALESCE(SUM(amount), 0) FROM invoice_item
|
"SELECT COALESCE(SUM(amount), 0) FROM invoice_item
|
||||||
WHERE tenant_pubkey = ? AND invoice_id IS NULL",
|
WHERE tenant_pubkey = ? AND invoice_id IS NULL AND voided_at IS NULL",
|
||||||
)
|
)
|
||||||
.bind(&tenant.pubkey)
|
.bind(&tenant.pubkey)
|
||||||
.fetch_one(&mut **tx)
|
.fetch_one(&mut **tx)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
if total <= 0 {
|
// Stripe's minimum charge is $0.50 USD; $1 leaves margin so a later
|
||||||
|
// small credit can't drop a fresh invoice under that floor. Leave
|
||||||
|
// items outstanding and carry to a later invoice.
|
||||||
|
if total <= 100 {
|
||||||
return Ok(None);
|
return Ok(None);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -369,7 +373,7 @@ pub async fn create_invoice(tenant: &Tenant, period: &BillingPeriod) -> Result<O
|
|||||||
|
|
||||||
sqlx::query(
|
sqlx::query(
|
||||||
"UPDATE invoice_item SET invoice_id = ?
|
"UPDATE invoice_item SET invoice_id = ?
|
||||||
WHERE tenant_pubkey = ? AND invoice_id IS NULL",
|
WHERE tenant_pubkey = ? AND invoice_id IS NULL AND voided_at IS NULL",
|
||||||
)
|
)
|
||||||
.bind(&invoice.id)
|
.bind(&invoice.id)
|
||||||
.bind(&tenant.pubkey)
|
.bind(&tenant.pubkey)
|
||||||
@@ -383,6 +387,16 @@ pub async fn create_invoice(tenant: &Tenant, period: &BillingPeriod) -> Result<O
|
|||||||
|
|
||||||
// --- Payment settlement ---
|
// --- Payment settlement ---
|
||||||
|
|
||||||
|
/// Atomically record a Lightning settlement that happened out of band.
|
||||||
|
pub async fn settle_invoice_out_of_band(bolt11_id: &str, invoice_id: &str) -> Result<()> {
|
||||||
|
with_tx(async |tx| {
|
||||||
|
mark_bolt11_settled_tx(tx, bolt11_id).await?;
|
||||||
|
mark_invoice_paid_tx(tx, invoice_id, "oob").await?;
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
/// Atomically record an NWC-settled invoice: clear the tenant's stored NWC error,
|
/// Atomically record an NWC-settled invoice: clear the tenant's stored NWC error,
|
||||||
/// mark the bolt11 settled, and mark the invoice paid.
|
/// mark the bolt11 settled, and mark the invoice paid.
|
||||||
pub async fn settle_invoice_via_nwc(
|
pub async fn settle_invoice_via_nwc(
|
||||||
@@ -399,26 +413,37 @@ pub async fn settle_invoice_via_nwc(
|
|||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Atomically record a Lightning settlement that happened out of band.
|
/// Atomically settle an invoice paid off-session: stamp the write-ahead intent
|
||||||
pub async fn settle_invoice_out_of_band(bolt11_id: &str, invoice_id: &str) -> Result<()> {
|
/// with the Stripe PaymentIntent that confirmed it, clear the tenant's stored
|
||||||
|
/// Stripe error, and mark the invoice paid. `intent_id` is our row id (from
|
||||||
|
/// [`insert_pending_intent`]); `payment_intent_id` is the Stripe `pi_…`.
|
||||||
|
pub async fn settle_invoice_via_intent(
|
||||||
|
tenant_pubkey: &str,
|
||||||
|
intent_id: &str,
|
||||||
|
payment_intent_id: &str,
|
||||||
|
invoice_id: &str,
|
||||||
|
) -> Result<()> {
|
||||||
with_tx(async |tx| {
|
with_tx(async |tx| {
|
||||||
mark_bolt11_settled_tx(tx, bolt11_id).await?;
|
clear_tenant_stripe_error_tx(tx, tenant_pubkey).await?;
|
||||||
mark_invoice_paid_tx(tx, invoice_id, "oob").await?;
|
mark_intent_settled_tx(tx, intent_id, payment_intent_id).await?;
|
||||||
|
mark_invoice_paid_tx(tx, invoice_id, "stripe").await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Atomically record a Stripe-settled invoice: persist the PaymentIntent, clear
|
/// Atomically record an invoice paid via a hosted Checkout session: stamp the
|
||||||
/// the tenant's stored Stripe error, and mark the invoice paid.
|
/// checkout settled, clear the tenant's stored Stripe error, and mark the invoice
|
||||||
pub async fn settle_invoice_via_stripe(
|
/// paid. The checkout was inserted unsettled by [`insert_checkout`]. `checkout_id`
|
||||||
|
/// is our row id, not the Stripe Checkout Session id.
|
||||||
|
pub async fn settle_invoice_via_checkout(
|
||||||
tenant_pubkey: &str,
|
tenant_pubkey: &str,
|
||||||
intent_id: &str,
|
checkout_id: &str,
|
||||||
invoice_id: &str,
|
invoice_id: &str,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
with_tx(async |tx| {
|
with_tx(async |tx| {
|
||||||
insert_intent_tx(tx, intent_id, invoice_id).await?;
|
|
||||||
clear_tenant_stripe_error_tx(tx, tenant_pubkey).await?;
|
clear_tenant_stripe_error_tx(tx, tenant_pubkey).await?;
|
||||||
|
mark_checkout_settled_tx(tx, checkout_id).await?;
|
||||||
mark_invoice_paid_tx(tx, invoice_id, "stripe").await?;
|
mark_invoice_paid_tx(tx, invoice_id, "stripe").await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
})
|
})
|
||||||
@@ -463,8 +488,38 @@ pub async fn insert_bolt11(
|
|||||||
.await?)
|
.await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- Checkout records ---
|
||||||
|
|
||||||
|
/// Record a pending Stripe Checkout session for an invoice, returning the stored
|
||||||
|
/// [`Checkout`]. Mirrors [`insert_bolt11`]: created unsettled with our own id,
|
||||||
|
/// then stamped by [`settle_invoice_via_checkout`] once the session is paid.
|
||||||
|
pub async fn insert_checkout(
|
||||||
|
invoice_id: &str,
|
||||||
|
session_id: &str,
|
||||||
|
url: &str,
|
||||||
|
expires_at: i64,
|
||||||
|
) -> Result<Option<Checkout>> {
|
||||||
|
let id = uuid::Uuid::new_v4().to_string();
|
||||||
|
let created_at = chrono::Utc::now().timestamp();
|
||||||
|
|
||||||
|
Ok(sqlx::query_as::<_, Checkout>(
|
||||||
|
"INSERT INTO checkout (id, invoice_id, session_id, url, created_at, expires_at)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?) RETURNING *",
|
||||||
|
)
|
||||||
|
.bind(id)
|
||||||
|
.bind(invoice_id)
|
||||||
|
.bind(session_id)
|
||||||
|
.bind(url)
|
||||||
|
.bind(created_at)
|
||||||
|
.bind(expires_at)
|
||||||
|
.fetch_optional(pool())
|
||||||
|
.await?)
|
||||||
|
}
|
||||||
|
|
||||||
// --- Internal utils that take an explicit transaction ---
|
// --- Internal utils that take an explicit transaction ---
|
||||||
|
|
||||||
|
// --- Activities ---
|
||||||
|
|
||||||
async fn insert_activity_tx(
|
async fn insert_activity_tx(
|
||||||
tx: &mut Transaction<'_, Sqlite>,
|
tx: &mut Transaction<'_, Sqlite>,
|
||||||
activity_type: &str,
|
activity_type: &str,
|
||||||
@@ -511,52 +566,6 @@ async fn insert_activity_tx(
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn insert_invoice_tx(
|
|
||||||
tx: &mut Transaction<'_, Sqlite>,
|
|
||||||
tenant: &Tenant,
|
|
||||||
period: &BillingPeriod,
|
|
||||||
amount: i64,
|
|
||||||
) -> Result<Invoice> {
|
|
||||||
let now = chrono::Utc::now().timestamp();
|
|
||||||
let invoice_id = uuid::Uuid::new_v4().to_string();
|
|
||||||
|
|
||||||
Ok(sqlx::query_as::<_, Invoice>(
|
|
||||||
"INSERT INTO invoice (id, tenant_pubkey, amount, period_start, period_end, created_at)
|
|
||||||
VALUES (?, ?, ?, ?, ?, ?) RETURNING *",
|
|
||||||
)
|
|
||||||
.bind(invoice_id)
|
|
||||||
.bind(&tenant.pubkey)
|
|
||||||
.bind(amount)
|
|
||||||
.bind(period.start)
|
|
||||||
.bind(period.end)
|
|
||||||
.bind(now)
|
|
||||||
.fetch_one(&mut **tx)
|
|
||||||
.await?)
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn insert_invoice_item_tx(
|
|
||||||
tx: &mut Transaction<'_, Sqlite>,
|
|
||||||
item: &InvoiceItem,
|
|
||||||
) -> Result<()> {
|
|
||||||
sqlx::query(
|
|
||||||
"INSERT INTO invoice_item
|
|
||||||
(id, invoice_id, activity_id, tenant_pubkey, relay_id, plan_id, amount, description, created_at)
|
|
||||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
|
||||||
)
|
|
||||||
.bind(&item.id)
|
|
||||||
.bind(&item.invoice_id)
|
|
||||||
.bind(&item.activity_id)
|
|
||||||
.bind(&item.tenant_pubkey)
|
|
||||||
.bind(&item.relay_id)
|
|
||||||
.bind(&item.plan_id)
|
|
||||||
.bind(item.amount)
|
|
||||||
.bind(&item.description)
|
|
||||||
.bind(item.created_at)
|
|
||||||
.execute(&mut **tx)
|
|
||||||
.await?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Claim an activity as billed. Returns `true` if this call set the marker, and
|
/// Claim an activity as billed. Returns `true` if this call set the marker, and
|
||||||
/// `false` if it was already set — e.g. a concurrent reconcile pass won the race —
|
/// `false` if it was already set — e.g. a concurrent reconcile pass won the race —
|
||||||
/// so callers can skip work that would otherwise double-bill.
|
/// so callers can skip work that would otherwise double-bill.
|
||||||
@@ -574,79 +583,7 @@ async fn mark_activity_billed_tx(
|
|||||||
Ok(result.rows_affected() > 0)
|
Ok(result.rows_affected() > 0)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Set a relay's status (and flag it for re-sync), recording the matching
|
// --- Tenants ---
|
||||||
/// activity. Returns the activity so the caller can `publish` it after the
|
|
||||||
/// enclosing transaction commits.
|
|
||||||
async fn set_relay_status_tx(
|
|
||||||
tx: &mut Transaction<'_, Sqlite>,
|
|
||||||
relay: &Relay,
|
|
||||||
status: &str,
|
|
||||||
activity_type: &str,
|
|
||||||
) -> Result<Activity> {
|
|
||||||
sqlx::query("UPDATE relay SET status = ?, synced = 0 WHERE id = ?")
|
|
||||||
.bind(status)
|
|
||||||
.bind(&relay.id)
|
|
||||||
.execute(&mut **tx)
|
|
||||||
.await?;
|
|
||||||
let snapshot = Snapshot::Relay {
|
|
||||||
plan: relay.plan_id.clone(),
|
|
||||||
status: status.to_string(),
|
|
||||||
};
|
|
||||||
insert_activity_tx(tx, activity_type, &relay.id, snapshot).await
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Stamp a bolt11 as settled but don't overwrite an existing settled_at.
|
|
||||||
async fn mark_bolt11_settled_tx(tx: &mut Transaction<'_, Sqlite>, bolt11_id: &str) -> Result<()> {
|
|
||||||
let settled_at = chrono::Utc::now().timestamp();
|
|
||||||
|
|
||||||
sqlx::query("UPDATE bolt11 SET settled_at = ? WHERE id = ? AND settled_at IS NULL")
|
|
||||||
.bind(settled_at)
|
|
||||||
.bind(bolt11_id)
|
|
||||||
.execute(&mut **tx)
|
|
||||||
.await?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Mark an invoice paid, but only while it is still open — a late Lightning
|
|
||||||
/// payment never flips a voided/forgiven invoice to paid, and a Stripe-paid
|
|
||||||
/// invoice never has its provenance overwritten by a later bolt11.
|
|
||||||
async fn mark_invoice_paid_tx(
|
|
||||||
tx: &mut Transaction<'_, Sqlite>,
|
|
||||||
invoice_id: &str,
|
|
||||||
method: &str,
|
|
||||||
) -> Result<()> {
|
|
||||||
let paid_at = chrono::Utc::now().timestamp();
|
|
||||||
|
|
||||||
sqlx::query(
|
|
||||||
"UPDATE invoice SET method = ?, paid_at = ?
|
|
||||||
WHERE id = ? AND paid_at IS NULL AND voided_at IS NULL",
|
|
||||||
)
|
|
||||||
.bind(method)
|
|
||||||
.bind(paid_at)
|
|
||||||
.bind(invoice_id)
|
|
||||||
.execute(&mut **tx)
|
|
||||||
.await?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Void all of a tenant's open invoices, forgiving the balance — used when a
|
|
||||||
/// tenant churns or re-activates, so old debt never has to be collected.
|
|
||||||
async fn void_open_invoices_tx(
|
|
||||||
tx: &mut Transaction<'_, Sqlite>,
|
|
||||||
tenant_pubkey: &str,
|
|
||||||
) -> Result<()> {
|
|
||||||
let voided_at = chrono::Utc::now().timestamp();
|
|
||||||
|
|
||||||
sqlx::query(
|
|
||||||
"UPDATE invoice SET voided_at = ?
|
|
||||||
WHERE tenant_pubkey = ? AND paid_at IS NULL AND voided_at IS NULL",
|
|
||||||
)
|
|
||||||
.bind(voided_at)
|
|
||||||
.bind(tenant_pubkey)
|
|
||||||
.execute(&mut **tx)
|
|
||||||
.await?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Set or clear the tenant's churn marker. Set when an invoice ages past the
|
/// Set or clear the tenant's churn marker. Set when an invoice ages past the
|
||||||
/// grace period, cleared when billing is re-activated.
|
/// grace period, cleared when billing is re-activated.
|
||||||
@@ -682,23 +619,229 @@ async fn clear_tenant_stripe_error_tx(
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Record the Stripe PaymentIntent that paid an invoice. Keyed by the Stripe
|
// --- Relays ---
|
||||||
/// PaymentIntent id, so it's idempotent.
|
|
||||||
async fn insert_intent_tx(
|
|
||||||
tx: &mut Transaction<'_, Sqlite>,
|
|
||||||
intent_id: &str,
|
|
||||||
invoice_id: &str,
|
|
||||||
) -> Result<()> {
|
|
||||||
let created_at = chrono::Utc::now().timestamp();
|
|
||||||
|
|
||||||
sqlx::query(
|
/// Set a relay's status (and flag it for re-sync), recording the matching
|
||||||
"INSERT INTO intent (id, invoice_id, created_at)
|
/// activity. Returns the activity so the caller can `publish` it after the
|
||||||
VALUES (?, ?, ?) ON CONFLICT(id) DO NOTHING",
|
/// enclosing transaction commits.
|
||||||
|
async fn set_relay_status_tx(
|
||||||
|
tx: &mut Transaction<'_, Sqlite>,
|
||||||
|
relay: &Relay,
|
||||||
|
status: &str,
|
||||||
|
activity_type: &str,
|
||||||
|
) -> Result<Activity> {
|
||||||
|
sqlx::query("UPDATE relay SET status = ?, synced = 0 WHERE id = ?")
|
||||||
|
.bind(status)
|
||||||
|
.bind(&relay.id)
|
||||||
|
.execute(&mut **tx)
|
||||||
|
.await?;
|
||||||
|
let snapshot = Snapshot::Relay {
|
||||||
|
plan: relay.plan_id.clone(),
|
||||||
|
status: status.to_string(),
|
||||||
|
};
|
||||||
|
insert_activity_tx(tx, activity_type, &relay.id, snapshot).await
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Invoices ---
|
||||||
|
|
||||||
|
async fn insert_invoice_tx(
|
||||||
|
tx: &mut Transaction<'_, Sqlite>,
|
||||||
|
tenant: &Tenant,
|
||||||
|
period: &BillingPeriod,
|
||||||
|
amount: i64,
|
||||||
|
) -> Result<Invoice> {
|
||||||
|
let now = chrono::Utc::now().timestamp();
|
||||||
|
let invoice_id = uuid::Uuid::new_v4().to_string();
|
||||||
|
|
||||||
|
Ok(sqlx::query_as::<_, Invoice>(
|
||||||
|
"INSERT INTO invoice (id, tenant_pubkey, amount, period_start, period_end, created_at)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?) RETURNING *",
|
||||||
)
|
)
|
||||||
.bind(intent_id)
|
|
||||||
.bind(invoice_id)
|
.bind(invoice_id)
|
||||||
.bind(created_at)
|
.bind(&tenant.pubkey)
|
||||||
|
.bind(amount)
|
||||||
|
.bind(period.start)
|
||||||
|
.bind(period.end)
|
||||||
|
.bind(now)
|
||||||
|
.fetch_one(&mut **tx)
|
||||||
|
.await?)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn insert_invoice_item_tx(
|
||||||
|
tx: &mut Transaction<'_, Sqlite>,
|
||||||
|
item: &InvoiceItem,
|
||||||
|
) -> Result<()> {
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO invoice_item
|
||||||
|
(id, invoice_id, activity_id, tenant_pubkey, relay_id, plan_id, amount, description, created_at, voided_at)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
||||||
|
)
|
||||||
|
.bind(&item.id)
|
||||||
|
.bind(&item.invoice_id)
|
||||||
|
.bind(&item.activity_id)
|
||||||
|
.bind(&item.tenant_pubkey)
|
||||||
|
.bind(&item.relay_id)
|
||||||
|
.bind(&item.plan_id)
|
||||||
|
.bind(item.amount)
|
||||||
|
.bind(&item.description)
|
||||||
|
.bind(item.created_at)
|
||||||
|
.bind(item.voided_at)
|
||||||
.execute(&mut **tx)
|
.execute(&mut **tx)
|
||||||
.await?;
|
.await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Mark an invoice paid, but only while it is still open — a late Lightning
|
||||||
|
/// payment never flips a voided/forgiven invoice to paid, and a Stripe-paid
|
||||||
|
/// invoice never has its provenance overwritten by a later bolt11.
|
||||||
|
async fn mark_invoice_paid_tx(
|
||||||
|
tx: &mut Transaction<'_, Sqlite>,
|
||||||
|
invoice_id: &str,
|
||||||
|
method: &str,
|
||||||
|
) -> Result<()> {
|
||||||
|
let paid_at = chrono::Utc::now().timestamp();
|
||||||
|
|
||||||
|
sqlx::query(
|
||||||
|
"UPDATE invoice SET method = ?, paid_at = ?
|
||||||
|
WHERE id = ? AND paid_at IS NULL AND voided_at IS NULL",
|
||||||
|
)
|
||||||
|
.bind(method)
|
||||||
|
.bind(paid_at)
|
||||||
|
.bind(invoice_id)
|
||||||
|
.execute(&mut **tx)
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Void all of a tenant's open invoices and unpaid line items, forgiving the
|
||||||
|
/// balance — used when a tenant churns or re-activates, so old debt never has to
|
||||||
|
/// be collected. Voiding the items too (both outstanding ones and those on the
|
||||||
|
/// just-voided invoices) keeps a credit from bleeding into a future invoice and
|
||||||
|
/// lets a re-billed period start from a clean ledger. Items on a paid invoice are
|
||||||
|
/// left untouched.
|
||||||
|
async fn void_open_invoices_tx(
|
||||||
|
tx: &mut Transaction<'_, Sqlite>,
|
||||||
|
tenant_pubkey: &str,
|
||||||
|
) -> Result<()> {
|
||||||
|
let voided_at = chrono::Utc::now().timestamp();
|
||||||
|
|
||||||
|
sqlx::query(
|
||||||
|
"UPDATE invoice SET voided_at = ?
|
||||||
|
WHERE tenant_pubkey = ? AND paid_at IS NULL AND voided_at IS NULL",
|
||||||
|
)
|
||||||
|
.bind(voided_at)
|
||||||
|
.bind(tenant_pubkey)
|
||||||
|
.execute(&mut **tx)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
// Run after voiding the invoices above, so the `paid_at IS NULL` subquery
|
||||||
|
// catches their now-voided items along with the still-outstanding ones.
|
||||||
|
sqlx::query(
|
||||||
|
"UPDATE invoice_item SET voided_at = ?
|
||||||
|
WHERE tenant_pubkey = ? AND voided_at IS NULL
|
||||||
|
AND (invoice_id IS NULL OR invoice_id IN (
|
||||||
|
SELECT id FROM invoice WHERE paid_at IS NULL
|
||||||
|
))",
|
||||||
|
)
|
||||||
|
.bind(voided_at)
|
||||||
|
.bind(tenant_pubkey)
|
||||||
|
.execute(&mut **tx)
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Bolt11 ---
|
||||||
|
|
||||||
|
/// Stamp a bolt11 as settled but don't overwrite an existing settled_at.
|
||||||
|
async fn mark_bolt11_settled_tx(tx: &mut Transaction<'_, Sqlite>, bolt11_id: &str) -> Result<()> {
|
||||||
|
let settled_at = chrono::Utc::now().timestamp();
|
||||||
|
|
||||||
|
sqlx::query("UPDATE bolt11 SET settled_at = ? WHERE id = ? AND settled_at IS NULL")
|
||||||
|
.bind(settled_at)
|
||||||
|
.bind(bolt11_id)
|
||||||
|
.execute(&mut **tx)
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Checkouts ---
|
||||||
|
|
||||||
|
/// Stamp a checkout as settled but don't overwrite an existing settled_at, so a
|
||||||
|
/// re-reconcile of the same session is a no-op. Keyed by our row id.
|
||||||
|
async fn mark_checkout_settled_tx(
|
||||||
|
tx: &mut Transaction<'_, Sqlite>,
|
||||||
|
checkout_id: &str,
|
||||||
|
) -> Result<()> {
|
||||||
|
let settled_at = chrono::Utc::now().timestamp();
|
||||||
|
|
||||||
|
sqlx::query("UPDATE checkout SET settled_at = ? WHERE id = ? AND settled_at IS NULL")
|
||||||
|
.bind(settled_at)
|
||||||
|
.bind(checkout_id)
|
||||||
|
.execute(&mut **tx)
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Intents ---
|
||||||
|
|
||||||
|
/// Write-ahead an off-session charge attempt before confirming it with Stripe,
|
||||||
|
/// returning the stored [`Intent`]. Records the payment method so a retry after a
|
||||||
|
/// lost settle re-confirms the same (idempotent) PaymentIntent; settled later by
|
||||||
|
/// [`settle_invoice_via_intent`], or dropped by [`delete_intent`] if it declines.
|
||||||
|
///
|
||||||
|
/// Get-or-create, atomically: if the invoice already has an unsettled intent,
|
||||||
|
/// returns it unchanged (keeping its original `payment_method_id`, so the retry
|
||||||
|
/// re-confirms the same charge); otherwise inserts a fresh one. The partial
|
||||||
|
/// unique index on (invoice_id) WHERE settled_at IS NULL makes this race-free —
|
||||||
|
/// concurrent reconciles converge on one intent instead of two.
|
||||||
|
pub async fn ensure_pending_intent(invoice_id: &str, payment_method_id: &str) -> Result<Intent> {
|
||||||
|
let id = uuid::Uuid::new_v4().to_string();
|
||||||
|
let created_at = chrono::Utc::now().timestamp();
|
||||||
|
|
||||||
|
Ok(sqlx::query_as::<_, Intent>(
|
||||||
|
"INSERT INTO intent (id, invoice_id, payment_method_id, created_at)
|
||||||
|
VALUES (?, ?, ?, ?)
|
||||||
|
ON CONFLICT(invoice_id) WHERE settled_at IS NULL
|
||||||
|
DO UPDATE SET payment_method_id = intent.payment_method_id
|
||||||
|
RETURNING *",
|
||||||
|
)
|
||||||
|
.bind(id)
|
||||||
|
.bind(invoice_id)
|
||||||
|
.bind(payment_method_id)
|
||||||
|
.bind(created_at)
|
||||||
|
.fetch_one(pool())
|
||||||
|
.await?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Stamp an off-session intent settled with the Stripe PaymentIntent that
|
||||||
|
/// confirmed it, but don't overwrite an existing settled_at — so reconciling the
|
||||||
|
/// same attempt twice is a no-op.
|
||||||
|
async fn mark_intent_settled_tx(
|
||||||
|
tx: &mut Transaction<'_, Sqlite>,
|
||||||
|
intent_id: &str,
|
||||||
|
payment_intent_id: &str,
|
||||||
|
) -> Result<()> {
|
||||||
|
let settled_at = chrono::Utc::now().timestamp();
|
||||||
|
|
||||||
|
sqlx::query(
|
||||||
|
"UPDATE intent SET settled_at = ?, payment_intent_id = ?
|
||||||
|
WHERE id = ? AND settled_at IS NULL",
|
||||||
|
)
|
||||||
|
.bind(settled_at)
|
||||||
|
.bind(payment_intent_id)
|
||||||
|
.bind(intent_id)
|
||||||
|
.execute(&mut **tx)
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Drop a write-ahead intent whose charge didn't go through, so the next attempt
|
||||||
|
/// starts clean (on the tenant's current method). A charge that confirmed but
|
||||||
|
/// whose settle failed is instead left unsettled, for reconcile to re-confirm.
|
||||||
|
pub async fn delete_intent(intent_id: &str) -> Result<()> {
|
||||||
|
sqlx::query("DELETE FROM intent WHERE id = ?")
|
||||||
|
.bind(intent_id)
|
||||||
|
.execute(pool())
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|||||||
@@ -154,6 +154,10 @@ pub struct InvoiceItem {
|
|||||||
pub amount: i64,
|
pub amount: i64,
|
||||||
pub description: String,
|
pub description: String,
|
||||||
pub created_at: i64,
|
pub created_at: i64,
|
||||||
|
/// Set when the item is forgiven — the tenant churned or reactivated — so it
|
||||||
|
/// is never billed or carried into a later invoice; `None` while live. Applies
|
||||||
|
/// whether or not the item has been claimed onto an invoice.
|
||||||
|
pub voided_at: Option<i64>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
|
#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
|
||||||
@@ -166,3 +170,34 @@ pub struct Bolt11 {
|
|||||||
pub expires_at: i64,
|
pub expires_at: i64,
|
||||||
pub settled_at: Option<i64>,
|
pub settled_at: Option<i64>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A hosted Stripe Checkout session opened to pay an invoice on-session (so a 3D
|
||||||
|
/// Secure challenge can be cleared), shaped like [`Bolt11`]: created pending and
|
||||||
|
/// stamped `settled_at` once paid. `id` is our uuid; `session_id` is the Stripe
|
||||||
|
/// Checkout Session (`cs_…`), used to reconcile and expire it; `url` is the
|
||||||
|
/// hosted page we redirect the tenant to.
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
|
||||||
|
pub struct Checkout {
|
||||||
|
pub id: String,
|
||||||
|
pub invoice_id: String,
|
||||||
|
pub session_id: String,
|
||||||
|
pub url: String,
|
||||||
|
pub created_at: i64,
|
||||||
|
pub expires_at: i64,
|
||||||
|
pub settled_at: Option<i64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A write-ahead record of an off-session card charge: inserted before the Stripe
|
||||||
|
/// call and stamped `settled_at` once the charge confirms and the invoice is paid.
|
||||||
|
/// `payment_method_id` is the method it charges, so a retry after a lost settle
|
||||||
|
/// re-confirms the same (idempotent) PaymentIntent rather than charging a second
|
||||||
|
/// one; `payment_intent_id` is the Stripe `pi_…` that settled it.
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
|
||||||
|
pub struct Intent {
|
||||||
|
pub id: String,
|
||||||
|
pub invoice_id: String,
|
||||||
|
pub payment_method_id: String,
|
||||||
|
pub payment_intent_id: Option<String>,
|
||||||
|
pub created_at: i64,
|
||||||
|
pub settled_at: Option<i64>,
|
||||||
|
}
|
||||||
|
|||||||
+29
-3
@@ -1,7 +1,7 @@
|
|||||||
use anyhow::{Result, anyhow};
|
use anyhow::{Result, anyhow};
|
||||||
|
|
||||||
use crate::db::pool;
|
use crate::db::pool;
|
||||||
use crate::models::{Activity, Bolt11, Invoice, InvoiceItem, Plan, Relay, Tenant};
|
use crate::models::{Activity, Bolt11, Checkout, Invoice, InvoiceItem, Plan, Relay, Tenant};
|
||||||
|
|
||||||
fn select_tenant(tail: &str) -> String {
|
fn select_tenant(tail: &str) -> String {
|
||||||
format!("SELECT * FROM tenant {tail}")
|
format!("SELECT * FROM tenant {tail}")
|
||||||
@@ -165,7 +165,7 @@ pub async fn list_invoice_items_for_invoice(invoice_id: &str) -> Result<Vec<Invo
|
|||||||
pub async fn list_unbilled_invoice_items(tenant_pubkey: &str) -> Result<Vec<InvoiceItem>> {
|
pub async fn list_unbilled_invoice_items(tenant_pubkey: &str) -> Result<Vec<InvoiceItem>> {
|
||||||
Ok(sqlx::query_as::<_, InvoiceItem>(
|
Ok(sqlx::query_as::<_, InvoiceItem>(
|
||||||
"SELECT * FROM invoice_item
|
"SELECT * FROM invoice_item
|
||||||
WHERE tenant_pubkey = ? AND invoice_id IS NULL
|
WHERE tenant_pubkey = ? AND invoice_id IS NULL AND voided_at IS NULL
|
||||||
ORDER BY created_at ASC",
|
ORDER BY created_at ASC",
|
||||||
)
|
)
|
||||||
.bind(tenant_pubkey)
|
.bind(tenant_pubkey)
|
||||||
@@ -197,6 +197,31 @@ pub async fn get_bolt11_for_invoice(invoice_id: &str) -> Result<Option<Bolt11>>
|
|||||||
.await?)
|
.await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- Checkouts ---
|
||||||
|
|
||||||
|
/// The most recent Checkout session for an invoice, regardless of `settled_at`,
|
||||||
|
/// so a session can still be expired on Stripe after we've locally marked it
|
||||||
|
/// settled. Mirrors [`get_bolt11_for_invoice`]; callers gate on `settled_at`.
|
||||||
|
pub async fn get_checkout_for_invoice(invoice_id: &str) -> Result<Option<Checkout>> {
|
||||||
|
Ok(sqlx::query_as::<_, Checkout>(
|
||||||
|
"SELECT * FROM checkout WHERE invoice_id = ? ORDER BY created_at DESC LIMIT 1",
|
||||||
|
)
|
||||||
|
.bind(invoice_id)
|
||||||
|
.fetch_optional(pool())
|
||||||
|
.await?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every still-pending (unsettled) Checkout session for an invoice — the ones to
|
||||||
|
/// expire on Stripe once the invoice has been paid another way.
|
||||||
|
pub async fn list_pending_checkouts_for_invoice(invoice_id: &str) -> Result<Vec<Checkout>> {
|
||||||
|
Ok(sqlx::query_as::<_, Checkout>(
|
||||||
|
"SELECT * FROM checkout WHERE invoice_id = ? AND settled_at IS NULL ORDER BY created_at DESC",
|
||||||
|
)
|
||||||
|
.bind(invoice_id)
|
||||||
|
.fetch_all(pool())
|
||||||
|
.await?)
|
||||||
|
}
|
||||||
|
|
||||||
// --- Activity ---
|
// --- Activity ---
|
||||||
|
|
||||||
/// Billable activity for a tenant not yet folded into an invoice. The
|
/// Billable activity for a tenant not yet folded into an invoice. The
|
||||||
@@ -208,7 +233,8 @@ pub async fn list_billable_activity(tenant_pubkey: &str) -> Result<Vec<Activity>
|
|||||||
"WHERE tenant_pubkey = ?
|
"WHERE tenant_pubkey = ?
|
||||||
AND billed_at IS NULL
|
AND billed_at IS NULL
|
||||||
AND activity_type IN (
|
AND activity_type IN (
|
||||||
'create_relay', 'update_relay', 'activate_relay', 'deactivate_relay'
|
'create_relay', 'update_relay', 'activate_relay', 'deactivate_relay',
|
||||||
|
'unmark_relay_delinquent'
|
||||||
)
|
)
|
||||||
ORDER BY created_at ASC",
|
ORDER BY created_at ASC",
|
||||||
))
|
))
|
||||||
|
|||||||
@@ -57,7 +57,7 @@ pub async fn reconcile_invoice(
|
|||||||
.map_err(internal)?;
|
.map_err(internal)?;
|
||||||
|
|
||||||
api.billing
|
api.billing
|
||||||
.attempt_payment(&tenant, &invoice, false)
|
.reconcile_payments(&tenant, &invoice, true, false)
|
||||||
.await
|
.await
|
||||||
.map_err(internal)?;
|
.map_err(internal)?;
|
||||||
|
|
||||||
@@ -92,6 +92,33 @@ pub async fn ensure_invoice_bolt11(
|
|||||||
ok(bolt11)
|
ok(bolt11)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Open a hosted Stripe Checkout session to pay a single open invoice by card,
|
||||||
|
/// returning the URL to redirect the tenant to. Unlike the off-session card
|
||||||
|
/// charge, Checkout can satisfy a 3D Secure authentication challenge; the
|
||||||
|
/// resulting payment is reconciled by `reconcile_invoice` (or the dunning poll).
|
||||||
|
pub async fn ensure_invoice_checkout(
|
||||||
|
State(api): State<Arc<Api>>,
|
||||||
|
AuthedPubkey(auth): AuthedPubkey,
|
||||||
|
Path(id): Path<String>,
|
||||||
|
) -> ApiResult {
|
||||||
|
let invoice = query::get_invoice(&id)
|
||||||
|
.await
|
||||||
|
.map_err(internal)?
|
||||||
|
.ok_or_else(|| not_found("invoice not found"))?;
|
||||||
|
|
||||||
|
api.require_admin_or_tenant(&auth, &invoice.tenant_pubkey)?;
|
||||||
|
|
||||||
|
let tenant = api.get_tenant_or_404(&invoice.tenant_pubkey).await?;
|
||||||
|
|
||||||
|
let checkout = api
|
||||||
|
.billing
|
||||||
|
.ensure_checkout_for_invoice(&tenant, &invoice)
|
||||||
|
.await
|
||||||
|
.map_err(internal)?;
|
||||||
|
|
||||||
|
ok(serde_json::json!({ "url": checkout.url }))
|
||||||
|
}
|
||||||
|
|
||||||
/// The line items billed on an invoice
|
/// The line items billed on an invoice
|
||||||
pub async fn list_invoice_items(
|
pub async fn list_invoice_items(
|
||||||
State(api): State<Arc<Api>>,
|
State(api): State<Arc<Api>>,
|
||||||
|
|||||||
@@ -128,6 +128,7 @@ impl Stripe {
|
|||||||
("currency", currency),
|
("currency", currency),
|
||||||
("customer", customer_id),
|
("customer", customer_id),
|
||||||
("payment_method", payment_method_id),
|
("payment_method", payment_method_id),
|
||||||
|
("metadata[invoice_id]", invoice_id),
|
||||||
("off_session", "true"),
|
("off_session", "true"),
|
||||||
("confirm", "true"),
|
("confirm", "true"),
|
||||||
])
|
])
|
||||||
@@ -148,6 +149,77 @@ impl Stripe {
|
|||||||
.ok_or_else(|| anyhow!("missing payment intent id"))
|
.ok_or_else(|| anyhow!("missing payment intent id"))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- Checkout ---
|
||||||
|
|
||||||
|
/// Open a hosted Stripe Checkout session that charges `amount` (in the
|
||||||
|
/// currency's minor units) for a single invoice on-session, so the customer
|
||||||
|
/// can satisfy a 3D Secure authentication that an off-session saved-card
|
||||||
|
/// charge can't. Returns the session id, its hosted URL, and its expiry. The
|
||||||
|
/// session and the PaymentIntent it creates both carry `invoice_id` in
|
||||||
|
/// metadata so the charge is traceable back to our ledger.
|
||||||
|
pub async fn create_checkout_session(
|
||||||
|
&self,
|
||||||
|
customer_id: &str,
|
||||||
|
invoice_id: &str,
|
||||||
|
amount: i64,
|
||||||
|
currency: &str,
|
||||||
|
success_url: &str,
|
||||||
|
cancel_url: &str,
|
||||||
|
) -> Result<(String, String, i64)> {
|
||||||
|
let amount = amount.to_string();
|
||||||
|
let body = self
|
||||||
|
.post("/checkout/sessions")
|
||||||
|
.form(&[
|
||||||
|
("mode", "payment"),
|
||||||
|
("customer", customer_id),
|
||||||
|
("success_url", success_url),
|
||||||
|
("cancel_url", cancel_url),
|
||||||
|
("line_items[0][quantity]", "1"),
|
||||||
|
("line_items[0][price_data][currency]", currency),
|
||||||
|
("line_items[0][price_data][unit_amount]", amount.as_str()),
|
||||||
|
(
|
||||||
|
"line_items[0][price_data][product_data][name]",
|
||||||
|
"Relay subscription",
|
||||||
|
),
|
||||||
|
("payment_intent_data[metadata][invoice_id]", invoice_id),
|
||||||
|
("metadata[invoice_id]", invoice_id),
|
||||||
|
])
|
||||||
|
.send_json()
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let session_id = body["id"]
|
||||||
|
.as_str()
|
||||||
|
.ok_or_else(|| anyhow!("missing checkout session id"))?;
|
||||||
|
let url = body["url"]
|
||||||
|
.as_str()
|
||||||
|
.ok_or_else(|| anyhow!("missing checkout session url"))?;
|
||||||
|
let expires_at = body["expires_at"]
|
||||||
|
.as_i64()
|
||||||
|
.ok_or_else(|| anyhow!("missing checkout session expiry"))?;
|
||||||
|
Ok((session_id.to_string(), url.to_string(), expires_at))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether a Checkout session has been paid. Used to reconcile an invoice
|
||||||
|
/// once the customer returns from (or later completes) the hosted page.
|
||||||
|
pub async fn is_checkout_paid(&self, session_id: &str) -> Result<bool> {
|
||||||
|
let body = self
|
||||||
|
.get(&format!("/checkout/sessions/{session_id}"))
|
||||||
|
.send_json()
|
||||||
|
.await?;
|
||||||
|
Ok(body["payment_status"].as_str() == Some("paid"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Expire a Checkout session so it can no longer be completed. Used to close
|
||||||
|
/// out a still-open session once its invoice has been paid another way,
|
||||||
|
/// preventing a double charge. Errors if the session isn't open (already
|
||||||
|
/// completed or expired), which the caller treats as best-effort.
|
||||||
|
pub async fn expire_checkout_session(&self, session_id: &str) -> Result<()> {
|
||||||
|
self.post(&format!("/checkout/sessions/{session_id}/expire"))
|
||||||
|
.send_ok()
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
// --- Portal ---
|
// --- Portal ---
|
||||||
|
|
||||||
/// Open a Stripe billing-portal session for the customer, returning the URL
|
/// Open a Stripe billing-portal session for the customer, returning the URL
|
||||||
|
|||||||
@@ -2,12 +2,11 @@ import { createEffect, createResource, createSignal, Show } from "solid-js"
|
|||||||
import QRCode from "qrcode"
|
import QRCode from "qrcode"
|
||||||
import Modal from "@/components/Modal"
|
import Modal from "@/components/Modal"
|
||||||
import PaymentSetup from "@/components/PaymentSetup"
|
import PaymentSetup from "@/components/PaymentSetup"
|
||||||
import { CardSetupBody } from "@/components/PaymentSetupShell"
|
|
||||||
import InvoiceItemsList from "@/components/payment/InvoiceItemsList"
|
import InvoiceItemsList from "@/components/payment/InvoiceItemsList"
|
||||||
import LightningPayBody from "@/components/payment/LightningPayBody"
|
import LightningPayBody from "@/components/payment/LightningPayBody"
|
||||||
import { setToastMessage } from "@/lib/state"
|
import { setToastMessage } from "@/lib/state"
|
||||||
import { copyToClipboard } from "@/lib/clipboard"
|
import { copyToClipboard } from "@/lib/clipboard"
|
||||||
import { useCardPortal } from "@/lib/usePaymentSetup"
|
import { useInvoiceCheckout } from "@/lib/usePaymentSetup"
|
||||||
import { ensureInvoiceBolt11, listInvoiceItems, reconcileInvoice, type Invoice } from "@/lib/api"
|
import { ensureInvoiceBolt11, listInvoiceItems, reconcileInvoice, type Invoice } from "@/lib/api"
|
||||||
import { autopayConfigured } from "@/lib/paymentMethod"
|
import { autopayConfigured } from "@/lib/paymentMethod"
|
||||||
import { billingTenant } from "@/lib/state"
|
import { billingTenant } from "@/lib/state"
|
||||||
@@ -40,9 +39,11 @@ export default function PaymentDialog(props: PaymentDialogProps) {
|
|||||||
listInvoiceItems,
|
listInvoiceItems,
|
||||||
)
|
)
|
||||||
|
|
||||||
// Card payment is a redirect to the Stripe billing portal; once a card is on
|
// Paying by card opens a Stripe Checkout session scoped to this invoice (which
|
||||||
// file we retry collection on this invoice automatically.
|
// can clear a 3D Secure challenge the off-session charge can't), then returns
|
||||||
const card = useCardPortal()
|
// here where the payment is reconciled. Distinct from PaymentSetup, which
|
||||||
|
// manages the recurring card on file via the billing portal.
|
||||||
|
const checkout = useInvoiceCheckout(() => props.invoice.id)
|
||||||
|
|
||||||
const hasAutopay = () => {
|
const hasAutopay = () => {
|
||||||
const t = billingTenant()
|
const t = billingTenant()
|
||||||
@@ -72,10 +73,10 @@ export default function PaymentDialog(props: PaymentDialogProps) {
|
|||||||
void loadBolt11()
|
void loadBolt11()
|
||||||
})
|
})
|
||||||
|
|
||||||
// The card portal lives in a shared hook, so surface its failures here by
|
// The checkout redirect lives in a shared hook, so surface its failures here
|
||||||
// mirroring its error signal into the toast.
|
// by mirroring its error signal into the toast.
|
||||||
createEffect(() => {
|
createEffect(() => {
|
||||||
const err = card.error()
|
const err = checkout.error()
|
||||||
if (err) setToastMessage(err)
|
if (err) setToastMessage(err)
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -106,7 +107,7 @@ export default function PaymentDialog(props: PaymentDialogProps) {
|
|||||||
setBolt11("")
|
setBolt11("")
|
||||||
setQrDataUrl("")
|
setQrDataUrl("")
|
||||||
setPayMethod("lightning")
|
setPayMethod("lightning")
|
||||||
card.reset()
|
checkout.reset()
|
||||||
props.onClose()
|
props.onClose()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -186,9 +187,27 @@ export default function PaymentDialog(props: PaymentDialogProps) {
|
|||||||
/>
|
/>
|
||||||
</Show>
|
</Show>
|
||||||
|
|
||||||
{/* Card: redirect to the Stripe billing portal */}
|
{/* Card: redirect to a Stripe Checkout session for this invoice */}
|
||||||
<Show when={payMethod() === "card"}>
|
<Show when={payMethod() === "card"}>
|
||||||
<CardSetupBody card={card} />
|
<div class="text-center space-y-4">
|
||||||
|
<div class="mx-auto flex h-12 w-12 items-center justify-center rounded-full bg-gray-100">
|
||||||
|
<svg class="w-6 h-6 text-gray-400" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||||
|
<rect x="1" y="4" width="22" height="16" rx="2" ry="2" />
|
||||||
|
<line x1="1" y1="10" x2="23" y2="10" />
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
<p class="text-sm text-gray-600">
|
||||||
|
Pay this invoice on Stripe's secure checkout. You'll be redirected and brought back here once it's done.
|
||||||
|
</p>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={checkout.openCheckout}
|
||||||
|
disabled={checkout.redirecting()}
|
||||||
|
class="w-full py-2 px-4 bg-blue-600 text-white text-sm font-medium rounded-lg hover:bg-blue-700 disabled:opacity-50 transition-colors"
|
||||||
|
>
|
||||||
|
{checkout.redirecting() ? "Redirecting..." : `Pay ${amountLabel()} by card`}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
</Show>
|
</Show>
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -133,6 +133,7 @@ export type InvoiceItem = {
|
|||||||
amount: number
|
amount: number
|
||||||
description: string
|
description: string
|
||||||
created_at: number
|
created_at: number
|
||||||
|
voided_at: number | null
|
||||||
}
|
}
|
||||||
|
|
||||||
export type Bolt11 = {
|
export type Bolt11 = {
|
||||||
@@ -335,6 +336,15 @@ export function ensureInvoiceBolt11(invoiceId: string) {
|
|||||||
return callApi<undefined, Bolt11>("POST", `/invoices/${invoiceId}/bolt11`)
|
return callApi<undefined, Bolt11>("POST", `/invoices/${invoiceId}/bolt11`)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Open a hosted Stripe Checkout session to pay a single invoice by card,
|
||||||
|
// reusing a valid pending one. Unlike the off-session charge, Checkout can
|
||||||
|
// satisfy a 3D Secure challenge. Returns the URL to redirect to; the payment is
|
||||||
|
// reconciled by reconcileInvoice once the tenant returns (or by the poll). The
|
||||||
|
// return URL is fixed to the account page server-side.
|
||||||
|
export function createInvoiceCheckout(invoiceId: string) {
|
||||||
|
return callApi<undefined, { url: string }>("POST", `/invoices/${invoiceId}/checkout`)
|
||||||
|
}
|
||||||
|
|
||||||
// Reconcile and collect an open invoice: ensure a payable bolt11 exists, then
|
// Reconcile and collect an open invoice: ensure a payable bolt11 exists, then
|
||||||
// run the payment cascade (NWC, then an out-of-band Lightning settle, then a
|
// run the payment cascade (NWC, then an out-of-band Lightning settle, then a
|
||||||
// saved card). Caller-initiated, so no dunning DM and no churn. Returns the
|
// saved card). Caller-initiated, so no dunning DM and no churn. Returns the
|
||||||
|
|||||||
@@ -18,7 +18,10 @@ export function nwcState(t: Pick<Tenant, "nwc_is_set" | "nwc_error">): PaymentMe
|
|||||||
|
|
||||||
export function cardState(t: Pick<Tenant, "stripe_payment_method_id" | "stripe_error">): PaymentMethodState {
|
export function cardState(t: Pick<Tenant, "stripe_payment_method_id" | "stripe_error">): PaymentMethodState {
|
||||||
if (!t.stripe_payment_method_id) return { kind: "not_set_up" }
|
if (!t.stripe_payment_method_id) return { kind: "not_set_up" }
|
||||||
if (t.stripe_error) return { kind: "error", message: t.stripe_error }
|
// Don't surface Stripe's raw decline/error text to the tenant (it can be noisy
|
||||||
|
// or sensitive); show a generic message. The detail stays on the tenant record
|
||||||
|
// for admins (see AdminTenantDetail).
|
||||||
|
if (t.stripe_error) return { kind: "error", message: "Payment failed" }
|
||||||
return { kind: "ok" }
|
return { kind: "ok" }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import { createSignal } from "solid-js"
|
import { createSignal } from "solid-js"
|
||||||
import QRCode from "qrcode"
|
|
||||||
import { ensureInvoiceBolt11, invoiceStatus, listInvoiceItems, type Invoice, type InvoiceItem } from "@/lib/api"
|
import { ensureInvoiceBolt11, invoiceStatus, listInvoiceItems, type Invoice, type InvoiceItem } from "@/lib/api"
|
||||||
import { methodLabel } from "@/lib/paymentMethod"
|
import { methodLabel } from "@/lib/paymentMethod"
|
||||||
import { formatUsd } from "@/lib/format"
|
import { formatUsd } from "@/lib/format"
|
||||||
@@ -33,20 +32,16 @@ export function useInvoicePdf() {
|
|||||||
})
|
})
|
||||||
|
|
||||||
let sats: number | undefined
|
let sats: number | undefined
|
||||||
let qrDataUrl: string | undefined
|
|
||||||
if (invoice.method !== "stripe" && invoice.voided_at == null) {
|
if (invoice.method !== "stripe" && invoice.voided_at == null) {
|
||||||
try {
|
try {
|
||||||
const bolt11 = await ensureInvoiceBolt11(invoice.id)
|
const bolt11 = await ensureInvoiceBolt11(invoice.id)
|
||||||
sats = Math.round(bolt11.msats / 1000)
|
sats = Math.round(bolt11.msats / 1000)
|
||||||
if (invoice.paid_at == null) {
|
|
||||||
qrDataUrl = await QRCode.toDataURL(bolt11.lnbc, { width: 180, margin: 1 })
|
|
||||||
}
|
|
||||||
} catch {
|
} catch {
|
||||||
// no bolt11 available — omit the bitcoin line
|
// no bolt11 available — omit the bitcoin line
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
printHtml(buildHtml({ invoice, items, sats, qrDataUrl }))
|
printHtml(buildHtml({ invoice, items, sats }))
|
||||||
} finally {
|
} finally {
|
||||||
setPrinting(false)
|
setPrinting(false)
|
||||||
}
|
}
|
||||||
@@ -55,8 +50,8 @@ export function useInvoicePdf() {
|
|||||||
return { printInvoice, printing }
|
return { printInvoice, printing }
|
||||||
}
|
}
|
||||||
|
|
||||||
function buildHtml(opts: { invoice: Invoice; items: InvoiceItem[]; sats?: number; qrDataUrl?: string }): string {
|
function buildHtml(opts: { invoice: Invoice; items: InvoiceItem[]; sats?: number }): string {
|
||||||
const { invoice, items, sats, qrDataUrl } = opts
|
const { invoice, items, sats } = opts
|
||||||
// The draft invoice carries the sentinel id and no lifecycle timestamps, so
|
// The draft invoice carries the sentinel id and no lifecycle timestamps, so
|
||||||
// invoiceStatus would read it as "open" — label it "draft" explicitly.
|
// invoiceStatus would read it as "open" — label it "draft" explicitly.
|
||||||
const status = invoice.id === "draft" ? "draft" : invoiceStatus(invoice)
|
const status = invoice.id === "draft" ? "draft" : invoiceStatus(invoice)
|
||||||
@@ -69,9 +64,6 @@ function buildHtml(opts: { invoice: Invoice; items: InvoiceItem[]; sats?: number
|
|||||||
|
|
||||||
const satsRow = sats != null ? `<tr><td>Bitcoin equivalent</td><td class="amt">${sats.toLocaleString()} sats</td></tr>` : ""
|
const satsRow = sats != null ? `<tr><td>Bitcoin equivalent</td><td class="amt">${sats.toLocaleString()} sats</td></tr>` : ""
|
||||||
const methodLine = invoice.method ? `<div>Paid via ${escapeHtml(methodLabel(invoice.method))}</div>` : ""
|
const methodLine = invoice.method ? `<div>Paid via ${escapeHtml(methodLabel(invoice.method))}</div>` : ""
|
||||||
const qr = qrDataUrl
|
|
||||||
? `<div class="qr"><img src="${qrDataUrl}" alt="Lightning invoice QR"/><div class="muted">Scan to pay by Lightning</div></div>`
|
|
||||||
: ""
|
|
||||||
|
|
||||||
return `<!doctype html><html><head><meta charset="utf-8"><title>Invoice ${escapeHtml(invoice.id)}</title>
|
return `<!doctype html><html><head><meta charset="utf-8"><title>Invoice ${escapeHtml(invoice.id)}</title>
|
||||||
<style>
|
<style>
|
||||||
@@ -86,7 +78,6 @@ function buildHtml(opts: { invoice: Invoice; items: InvoiceItem[]; sats?: number
|
|||||||
th, td { text-align: left; padding: 8px 0; border-bottom: 1px solid #e5e7eb; font-size: 14px; }
|
th, td { text-align: left; padding: 8px 0; border-bottom: 1px solid #e5e7eb; font-size: 14px; }
|
||||||
.amt { text-align: right; white-space: nowrap; }
|
.amt { text-align: right; white-space: nowrap; }
|
||||||
tfoot td { font-weight: 600; border-bottom: none; border-top: 2px solid #111827; }
|
tfoot td { font-weight: 600; border-bottom: none; border-top: 2px solid #111827; }
|
||||||
.qr { margin-top: 28px; text-align: center; }
|
|
||||||
</style></head>
|
</style></head>
|
||||||
<body>
|
<body>
|
||||||
<div class="head">
|
<div class="head">
|
||||||
@@ -105,7 +96,6 @@ function buildHtml(opts: { invoice: Invoice; items: InvoiceItem[]; sats?: number
|
|||||||
<tbody>${rows}${satsRow}</tbody>
|
<tbody>${rows}${satsRow}</tbody>
|
||||||
<tfoot><tr><td>Total</td><td class="amt">${formatUsd(invoice.amount)}</td></tr></tfoot>
|
<tfoot><tr><td>Total</td><td class="amt">${formatUsd(invoice.amount)}</td></tr></tfoot>
|
||||||
</table>
|
</table>
|
||||||
${qr}
|
|
||||||
</body></html>`
|
</body></html>`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -133,7 +123,7 @@ function printHtml(html: string) {
|
|||||||
const cleanup = () => window.setTimeout(() => iframe.remove(), 1000)
|
const cleanup = () => window.setTimeout(() => iframe.remove(), 1000)
|
||||||
win.onafterprint = cleanup
|
win.onafterprint = cleanup
|
||||||
|
|
||||||
// Let the iframe lay out (and decode the QR image) before printing.
|
// Let the iframe lay out before printing.
|
||||||
window.setTimeout(() => {
|
window.setTimeout(() => {
|
||||||
win.focus()
|
win.focus()
|
||||||
win.print()
|
win.print()
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { createSignal } from "solid-js"
|
import { createSignal } from "solid-js"
|
||||||
import { updateActiveTenant } from "@/lib/hooks"
|
import { updateActiveTenant } from "@/lib/hooks"
|
||||||
import { createPortalSession } from "@/lib/api"
|
import { createInvoiceCheckout, createPortalSession } from "@/lib/api"
|
||||||
import { account } from "@/lib/state"
|
import { account } from "@/lib/state"
|
||||||
|
|
||||||
// Lightning/NWC save state machine, shared by the combined and focused setup
|
// Lightning/NWC save state machine, shared by the combined and focused setup
|
||||||
@@ -65,3 +65,33 @@ export function useCardPortal() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export type CardPortal = ReturnType<typeof useCardPortal>
|
export type CardPortal = ReturnType<typeof useCardPortal>
|
||||||
|
|
||||||
|
// Paying one specific invoice by card is a full-page redirect to a Stripe
|
||||||
|
// Checkout session scoped to that invoice (so a 3D Secure challenge can be
|
||||||
|
// completed) — distinct from the billing-portal redirect that manages the
|
||||||
|
// recurring card on file. Like the portal, there's no local "saved" state, only
|
||||||
|
// the in-flight redirect and any failure to open the session.
|
||||||
|
export function useInvoiceCheckout(invoiceId: () => string) {
|
||||||
|
const [redirecting, setRedirecting] = createSignal(false)
|
||||||
|
const [error, setError] = createSignal("")
|
||||||
|
|
||||||
|
async function openCheckout() {
|
||||||
|
setRedirecting(true)
|
||||||
|
setError("")
|
||||||
|
try {
|
||||||
|
const { url } = await createInvoiceCheckout(invoiceId())
|
||||||
|
window.location.href = url
|
||||||
|
} catch (e) {
|
||||||
|
setError(e instanceof Error ? e.message : "Failed to open checkout")
|
||||||
|
setRedirecting(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function reset() {
|
||||||
|
setError("")
|
||||||
|
}
|
||||||
|
|
||||||
|
return { redirecting, error, openCheckout, reset }
|
||||||
|
}
|
||||||
|
|
||||||
|
export type InvoiceCheckout = ReturnType<typeof useInvoiceCheckout>
|
||||||
|
|||||||
@@ -46,6 +46,10 @@ export default function Account() {
|
|||||||
// composite: reconcile the subscription, sync a card just added in the portal,
|
// composite: reconcile the subscription, sync a card just added in the portal,
|
||||||
// and collect the open invoice if a method is now on file — then refresh. This
|
// and collect the open invoice if a method is now on file — then refresh. This
|
||||||
// is what pays the outstanding invoice after the user adds a card and returns.
|
// is what pays the outstanding invoice after the user adds a card and returns.
|
||||||
|
// Reconciles on landing (including after returning from a Stripe Checkout or
|
||||||
|
// the billing portal): reconcile_tenant settles any out-of-band payment — a
|
||||||
|
// completed Checkout or a bolt11 paid elsewhere — and collects when a method
|
||||||
|
// is on file, then refreshes. No per-invoice return marker needed.
|
||||||
createEffect(() => {
|
createEffect(() => {
|
||||||
const pubkey = account()?.pubkey
|
const pubkey = account()?.pubkey
|
||||||
if (pubkey) void billing.autopay(pubkey)
|
if (pubkey) void billing.autopay(pubkey)
|
||||||
|
|||||||
Reference in New Issue
Block a user