forked from coracle/caravel
Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 0775f867e8 | |||
| dbe25c372f | |||
| 80a86452d0 | |||
| b1e3747ddb | |||
| 29f657635c |
@@ -28,5 +28,6 @@ LIVEKIT_API_SECRET=
|
||||
|
||||
# Billing
|
||||
NWC_URL= # Nostr Wallet Connect URL for generating Lightning invoices
|
||||
ENCRYPTION_SECRET= # Nostr secret key (hex or nsec) used to encrypt tenant NWC URLs at rest
|
||||
STRIPE_SECRET_KEY= # Required Stripe API secret key (sk_...)
|
||||
STRIPE_WEBHOOK_SECRET=whsec_test_00000000000000000000000000 # Webhook signing secret (use real value in production)
|
||||
|
||||
@@ -44,6 +44,7 @@ Environment variables:
|
||||
| `LIVEKIT_API_KEY` | LiveKit API key sent to zooid | _optional_ |
|
||||
| `LIVEKIT_API_SECRET` | LiveKit API secret sent to zooid | _optional_ |
|
||||
| `NWC_URL` | Platform NWC URL used to generate BOLT11 invoices | _required for invoice generation_ |
|
||||
| `ENCRYPTION_SECRET` | Nostr secret key (hex or nsec) used to encrypt tenant NWC URLs at rest | _required_ |
|
||||
| `STRIPE_SECRET_KEY` | Stripe API secret key used for billing API operations | _required_ |
|
||||
| `STRIPE_WEBHOOK_SECRET` | Stripe webhook signing secret used to verify `Stripe-Signature` headers | _required_ |
|
||||
| `ROBOT_SECRET` | Robot Nostr secret key | _required_ |
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
CREATE TABLE IF NOT EXISTS invoice_manual_lightning_payment (
|
||||
invoice_id TEXT PRIMARY KEY,
|
||||
tenant_pubkey TEXT NOT NULL,
|
||||
bolt11 TEXT NOT NULL,
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL,
|
||||
FOREIGN KEY (tenant_pubkey) REFERENCES tenant(pubkey)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_invoice_manual_lightning_payment_tenant_pubkey
|
||||
ON invoice_manual_lightning_payment (tenant_pubkey);
|
||||
+5
-4
@@ -57,7 +57,7 @@ Notes:
|
||||
|
||||
- Serves `GET /tenants`
|
||||
- Authorizes admin only
|
||||
- Return `data` is a list of tenant structs from `query.list_tenants`
|
||||
- Return `data` is a list of `TenantResponse` structs (contains `nwc_is_set: bool` instead of `nwc_url`)
|
||||
|
||||
## `async fn create_tenant(...) -> Response`
|
||||
|
||||
@@ -69,20 +69,21 @@ Notes:
|
||||
- On unique-constraint race (`pubkey-exists`), re-fetch and return the existing tenant
|
||||
- If Stripe customer creation fails, return `code=stripe-customer-create-failed`
|
||||
- Always returns `200` (create-or-get is uniform)
|
||||
- Return `data` is a single `Tenant` struct
|
||||
- Return `data` is a single `TenantResponse` struct (contains `nwc_is_set: bool` instead of `nwc_url`)
|
||||
|
||||
## `async fn get_tenant(...) -> Response`
|
||||
|
||||
- Serves `GET /tenants/:pubkey`
|
||||
- Authorizes admin or matching tenant
|
||||
- Return `data` is a single tenant struct from `query.get_tenant`
|
||||
- Return `data` is a single `TenantResponse` struct (contains `nwc_is_set: bool` instead of `nwc_url`)
|
||||
|
||||
## `async fn update_tenant(...) -> Response`
|
||||
|
||||
- Serves `PUT /tenants/:pubkey`
|
||||
- Authorizes admin or matching tenant
|
||||
- Accepts `nwc_url` in the request body; encrypts it before storage using `cipher::encrypt`
|
||||
- Updates tenant using `command.update_tenant`
|
||||
- Return `data` is the updated tenant struct
|
||||
- Return `data` is the updated `TenantResponse` struct (contains `nwc_is_set: bool` instead of `nwc_url`)
|
||||
|
||||
## `async fn list_tenant_relays(...) -> Response`
|
||||
|
||||
|
||||
@@ -52,7 +52,7 @@ There are three plans available:
|
||||
Tenants are customers of the service, identified by a nostr `pubkey`. Public metadata like name etc are pulled from the nostr network. They also have associated billing information.
|
||||
|
||||
- `pubkey` is the nostr public key identifying the tenant
|
||||
- `nwc_url` (private) a nostr wallet connect URL used for **paying** invoices generated by the system on the tenant's behalf
|
||||
- `nwc_url` (private) a nostr wallet connect URL used for **paying** invoices generated by the system on the tenant's behalf; stored encrypted at rest using NIP-44 via `ENCRYPTION_SECRET`; never serialized to API responses — tenant API endpoints expose `nwc_is_set: bool` instead
|
||||
- `nwc_error` (private) a string indicating the most recent NWC payment error, if any. Cleared on successful NWC payment.
|
||||
- `created_at` unix timestamp identifying tenant creation time
|
||||
- `stripe_customer_id` a string identifying the associated stripe customer
|
||||
@@ -63,9 +63,9 @@ Tenants are customers of the service, identified by a nostr `pubkey`. Public met
|
||||
|
||||
A relay is a nostr relay owned by a `tenant` and hosted by the attached zooid instance. Relay subdomains MUST be unique.
|
||||
|
||||
- `id` - a random ID identifying the relay
|
||||
- `id` - calculated based on `subdomain` + 8 random hex chars
|
||||
- `tenant` - the tenant's pubkey
|
||||
- `schema` - the relay's db schema (read_only, calculated based on `subdomain` + `id`)
|
||||
- `schema` - the relay's db schema (read only, same as `id`)
|
||||
- `subdomain` - the relay's subdomain
|
||||
- `plan` - the relay's plan
|
||||
- `stripe_subscription_item_id` (nullable) - the Stripe subscription item id. Only set for relays on paid plans.
|
||||
|
||||
+71
-13
@@ -275,9 +275,6 @@ impl Api {
|
||||
return Err(RelayValidationError::PremiumFeature);
|
||||
}
|
||||
|
||||
if relay.schema.is_empty() {
|
||||
relay.schema = format!("{}_{}", relay.subdomain.replace('-', "_"), relay.id);
|
||||
}
|
||||
if relay.status.is_empty() {
|
||||
relay.status = RELAY_STATUS_ACTIVE.to_string();
|
||||
}
|
||||
@@ -445,6 +442,31 @@ struct IdentityResponse {
|
||||
is_admin: bool,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct TenantResponse {
|
||||
pubkey: String,
|
||||
nwc_is_set: bool,
|
||||
nwc_error: Option<String>,
|
||||
created_at: i64,
|
||||
stripe_customer_id: String,
|
||||
stripe_subscription_id: Option<String>,
|
||||
past_due_at: Option<i64>,
|
||||
}
|
||||
|
||||
impl From<Tenant> for TenantResponse {
|
||||
fn from(t: Tenant) -> Self {
|
||||
TenantResponse {
|
||||
nwc_is_set: !t.nwc_url.is_empty(),
|
||||
pubkey: t.pubkey,
|
||||
nwc_error: t.nwc_error,
|
||||
created_at: t.created_at,
|
||||
stripe_customer_id: t.stripe_customer_id,
|
||||
stripe_subscription_id: t.stripe_subscription_id,
|
||||
past_due_at: t.past_due_at,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct CreateRelayRequest {
|
||||
tenant: String,
|
||||
@@ -486,7 +508,13 @@ async fn list_tenants(
|
||||
state.api.require_admin(&pubkey)?;
|
||||
|
||||
match state.api.query.list_tenants().await {
|
||||
Ok(tenants) => Ok(ok(StatusCode::OK, tenants)),
|
||||
Ok(tenants) => Ok(ok(
|
||||
StatusCode::OK,
|
||||
tenants
|
||||
.into_iter()
|
||||
.map(TenantResponse::from)
|
||||
.collect::<Vec<_>>(),
|
||||
)),
|
||||
Err(e) => Ok(err(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"internal",
|
||||
@@ -515,7 +543,7 @@ async fn create_tenant(
|
||||
let pubkey = state.api.extract_auth_pubkey(&headers)?;
|
||||
|
||||
match state.api.query.get_tenant(&pubkey).await {
|
||||
Ok(Some(t)) => Ok(ok(StatusCode::OK, t)),
|
||||
Ok(Some(t)) => Ok(ok(StatusCode::OK, TenantResponse::from(t))),
|
||||
Ok(None) => {
|
||||
let stripe_customer_id = match state.api.billing.stripe_create_customer(&pubkey).await {
|
||||
Ok(id) => id,
|
||||
@@ -539,10 +567,10 @@ async fn create_tenant(
|
||||
};
|
||||
|
||||
match state.api.command.create_tenant(&tenant).await {
|
||||
Ok(()) => Ok(ok(StatusCode::OK, tenant)),
|
||||
Ok(()) => Ok(ok(StatusCode::OK, TenantResponse::from(tenant))),
|
||||
Err(e) if matches!(map_unique_error(&e), Some("pubkey-exists")) => {
|
||||
match state.api.query.get_tenant(&pubkey).await {
|
||||
Ok(Some(t)) => Ok(ok(StatusCode::OK, t)),
|
||||
Ok(Some(t)) => Ok(ok(StatusCode::OK, TenantResponse::from(t))),
|
||||
Ok(None) => Ok(err(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"internal",
|
||||
@@ -585,7 +613,7 @@ async fn get_tenant(
|
||||
let auth = state.api.extract_auth_pubkey(&headers)?;
|
||||
state.api.require_admin_or_tenant(&auth, &pubkey)?;
|
||||
let tenant = state.api.get_tenant_or_404(&pubkey).await?;
|
||||
Ok(ok(StatusCode::OK, tenant))
|
||||
Ok(ok(StatusCode::OK, TenantResponse::from(tenant)))
|
||||
}
|
||||
|
||||
async fn list_relays(
|
||||
@@ -723,10 +751,16 @@ async fn create_relay(
|
||||
let auth = state.api.extract_auth_pubkey(&headers)?;
|
||||
state.api.require_admin_or_tenant(&auth, &payload.tenant)?;
|
||||
|
||||
let relay_id = format!(
|
||||
"{}_{}",
|
||||
payload.subdomain.replace('-', "_"),
|
||||
&uuid::Uuid::new_v4().simple().to_string()[..8]
|
||||
);
|
||||
|
||||
let mut relay = Relay {
|
||||
id: uuid::Uuid::new_v4().to_string(),
|
||||
id: relay_id.clone(),
|
||||
tenant: payload.tenant,
|
||||
schema: String::new(),
|
||||
schema: relay_id.clone(),
|
||||
subdomain: payload.subdomain,
|
||||
plan: payload.plan,
|
||||
stripe_subscription_item_id: None,
|
||||
@@ -1009,6 +1043,13 @@ async fn get_invoice(
|
||||
.map_err(map_invoice_lookup_error)?;
|
||||
state.api.require_admin_or_tenant(&auth, &tenant.pubkey)?;
|
||||
|
||||
let invoice = state
|
||||
.api
|
||||
.billing
|
||||
.reconcile_manual_lightning_invoice(&id, &invoice)
|
||||
.await
|
||||
.map_err(map_invoice_lookup_error)?;
|
||||
|
||||
Ok(ok(StatusCode::OK, invoice))
|
||||
}
|
||||
|
||||
@@ -1026,6 +1067,13 @@ async fn get_invoice_bolt11(
|
||||
.map_err(map_invoice_lookup_error)?;
|
||||
state.api.require_admin_or_tenant(&auth, &tenant.pubkey)?;
|
||||
|
||||
let invoice = state
|
||||
.api
|
||||
.billing
|
||||
.reconcile_manual_lightning_invoice(&id, &invoice)
|
||||
.await
|
||||
.map_err(map_invoice_lookup_error)?;
|
||||
|
||||
let status = invoice["status"].as_str().unwrap_or_default();
|
||||
if status != "open" {
|
||||
return Ok(err(
|
||||
@@ -1038,7 +1086,12 @@ async fn get_invoice_bolt11(
|
||||
let amount_due = invoice["amount_due"].as_i64().unwrap_or(0);
|
||||
let currency = invoice["currency"].as_str().unwrap_or("usd");
|
||||
|
||||
match state.api.billing.create_bolt11(amount_due, currency).await {
|
||||
match state
|
||||
.api
|
||||
.billing
|
||||
.get_or_create_manual_lightning_bolt11(&id, &tenant.pubkey, amount_due, currency)
|
||||
.await
|
||||
{
|
||||
Ok(bolt11) => Ok(ok(StatusCode::OK, serde_json::json!({ "bolt11": bolt11 }))),
|
||||
Err(e) => Ok(err(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
@@ -1084,7 +1137,12 @@ async fn update_tenant(
|
||||
|
||||
let nwc_previously_empty = tenant.nwc_url.is_empty();
|
||||
if let Some(nwc_url) = payload.nwc_url {
|
||||
tenant.nwc_url = nwc_url;
|
||||
if nwc_url.is_empty() {
|
||||
tenant.nwc_url = String::new();
|
||||
} else {
|
||||
tenant.nwc_url =
|
||||
crate::cipher::encrypt(&nwc_url).map_err(|e| ApiError::Internal(e.to_string()))?;
|
||||
}
|
||||
}
|
||||
|
||||
match state.api.command.update_tenant(&tenant).await {
|
||||
@@ -1103,7 +1161,7 @@ async fn update_tenant(
|
||||
}
|
||||
});
|
||||
}
|
||||
Ok(ok(StatusCode::OK, tenant))
|
||||
Ok(ok(StatusCode::OK, TenantResponse::from(tenant)))
|
||||
}
|
||||
Err(e) => Ok(err(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
|
||||
+117
-3
@@ -1,7 +1,8 @@
|
||||
use anyhow::{Result, anyhow};
|
||||
use hmac::{Hmac, Mac};
|
||||
use nwc::prelude::{
|
||||
MakeInvoiceRequest, NWC, NostrWalletConnectURI, PayInvoiceRequest as NwcPayInvoiceRequest,
|
||||
LookupInvoiceRequest, LookupInvoiceResponse, MakeInvoiceRequest, NWC, NostrWalletConnectURI,
|
||||
PayInvoiceRequest as NwcPayInvoiceRequest, TransactionState,
|
||||
};
|
||||
use sha2::Sha256;
|
||||
|
||||
@@ -421,13 +422,14 @@ impl Billing {
|
||||
|
||||
// 1. NWC auto-pay: if the tenant has a nwc_url
|
||||
if !tenant.nwc_url.is_empty() {
|
||||
let plain_nwc_url = crate::cipher::decrypt(&tenant.nwc_url)?;
|
||||
match self
|
||||
.nwc_pay_invoice(
|
||||
invoice_id,
|
||||
&tenant.pubkey,
|
||||
amount_due,
|
||||
currency,
|
||||
&tenant.nwc_url,
|
||||
&plain_nwc_url,
|
||||
)
|
||||
.await?
|
||||
{
|
||||
@@ -718,6 +720,50 @@ impl Billing {
|
||||
Ok((invoice, tenant))
|
||||
}
|
||||
|
||||
pub async fn reconcile_manual_lightning_invoice(
|
||||
&self,
|
||||
invoice_id: &str,
|
||||
invoice: &serde_json::Value,
|
||||
) -> std::result::Result<serde_json::Value, InvoiceLookupError> {
|
||||
self.reconcile_manual_lightning_invoice_if_settled(invoice_id, invoice)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn get_or_create_manual_lightning_bolt11(
|
||||
&self,
|
||||
invoice_id: &str,
|
||||
tenant_pubkey: &str,
|
||||
amount_due_minor: i64,
|
||||
currency: &str,
|
||||
) -> Result<String> {
|
||||
if let Some(existing_bolt11) = self
|
||||
.query
|
||||
.get_invoice_manual_lightning_bolt11(invoice_id)
|
||||
.await?
|
||||
{
|
||||
return Ok(existing_bolt11);
|
||||
}
|
||||
|
||||
let bolt11 = self.create_bolt11(amount_due_minor, currency).await?;
|
||||
|
||||
if self
|
||||
.command
|
||||
.insert_manual_lightning_invoice_payment(invoice_id, tenant_pubkey, &bolt11)
|
||||
.await?
|
||||
{
|
||||
return Ok(bolt11);
|
||||
}
|
||||
|
||||
self.query
|
||||
.get_invoice_manual_lightning_bolt11(invoice_id)
|
||||
.await?
|
||||
.ok_or_else(|| {
|
||||
anyhow!(
|
||||
"manual lightning payment row missing after insert race for invoice {invoice_id}"
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn stripe_create_customer(&self, tenant_pubkey: &str) -> Result<String> {
|
||||
let short_pubkey: String = tenant_pubkey.chars().take(12).collect();
|
||||
let display_name = format!("Caravel tenant {short_pubkey}");
|
||||
@@ -812,6 +858,8 @@ impl Billing {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let plain_nwc_url = crate::cipher::decrypt(&tenant.nwc_url)?;
|
||||
|
||||
let invoices = self
|
||||
.stripe_list_invoices(&tenant.stripe_customer_id)
|
||||
.await?;
|
||||
@@ -833,7 +881,7 @@ impl Billing {
|
||||
&tenant.pubkey,
|
||||
amount_due,
|
||||
currency,
|
||||
&tenant.nwc_url,
|
||||
&plain_nwc_url,
|
||||
)
|
||||
.await?
|
||||
{
|
||||
@@ -1138,6 +1186,72 @@ impl Billing {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn reconcile_manual_lightning_invoice_if_settled(
|
||||
&self,
|
||||
invoice_id: &str,
|
||||
invoice: &serde_json::Value,
|
||||
) -> std::result::Result<serde_json::Value, InvoiceLookupError> {
|
||||
if invoice["status"].as_str().unwrap_or_default() != "open" {
|
||||
return Ok(invoice.clone());
|
||||
}
|
||||
|
||||
let Some(bolt11) = self
|
||||
.query
|
||||
.get_invoice_manual_lightning_bolt11(invoice_id)
|
||||
.await?
|
||||
else {
|
||||
return Ok(invoice.clone());
|
||||
};
|
||||
|
||||
let settled = match self.is_manual_lightning_invoice_settled(&bolt11).await {
|
||||
Ok(settled) => settled,
|
||||
Err(error) => {
|
||||
tracing::warn!(
|
||||
error = %error,
|
||||
invoice_id,
|
||||
"failed to lookup manual lightning invoice settlement"
|
||||
);
|
||||
return Ok(invoice.clone());
|
||||
}
|
||||
};
|
||||
|
||||
if !settled {
|
||||
return Ok(invoice.clone());
|
||||
}
|
||||
|
||||
if let Err(error) = self.stripe_pay_invoice_out_of_band(invoice_id).await {
|
||||
tracing::warn!(
|
||||
error = %error,
|
||||
invoice_id,
|
||||
"failed to mark settled manual lightning invoice as paid_out_of_band"
|
||||
);
|
||||
}
|
||||
|
||||
self.stripe_get_invoice(invoice_id).await
|
||||
}
|
||||
|
||||
async fn is_manual_lightning_invoice_settled(&self, bolt11: &str) -> Result<bool> {
|
||||
let system_uri = Self::parse_nwc_uri(&self.nwc_url, "system")?;
|
||||
let system_nwc = NWC::new(system_uri);
|
||||
|
||||
let lookup_req = LookupInvoiceRequest {
|
||||
payment_hash: None,
|
||||
invoice: Some(bolt11.to_string()),
|
||||
};
|
||||
|
||||
let lookup_result = system_nwc.lookup_invoice(lookup_req).await;
|
||||
system_nwc.shutdown().await;
|
||||
|
||||
let lookup_response =
|
||||
lookup_result.map_err(|error| anyhow!("failed to lookup invoice: {error}"))?;
|
||||
|
||||
Ok(Self::lookup_invoice_response_is_settled(&lookup_response))
|
||||
}
|
||||
|
||||
fn lookup_invoice_response_is_settled(response: &LookupInvoiceResponse) -> bool {
|
||||
response.state == Some(TransactionState::Settled) || response.settled_at.is_some()
|
||||
}
|
||||
|
||||
fn parse_nwc_uri(nwc_url: &str, role: &str) -> Result<NostrWalletConnectURI> {
|
||||
nwc_url
|
||||
.parse::<NostrWalletConnectURI>()
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
use anyhow::{Result, anyhow};
|
||||
use nostr_sdk::prelude::*;
|
||||
|
||||
pub fn encrypt(plaintext: &str) -> Result<String> {
|
||||
let keys = load_key()?;
|
||||
nip44::encrypt(
|
||||
keys.secret_key(),
|
||||
&keys.public_key(),
|
||||
plaintext,
|
||||
nip44::Version::V2,
|
||||
)
|
||||
.map_err(|e| anyhow!("encryption failed: {e}"))
|
||||
}
|
||||
|
||||
pub fn decrypt(ciphertext: &str) -> Result<String> {
|
||||
let keys = load_key()?;
|
||||
nip44::decrypt(keys.secret_key(), &keys.public_key(), ciphertext)
|
||||
.map_err(|e| anyhow!("decryption failed: {e}"))
|
||||
}
|
||||
|
||||
fn load_key() -> Result<Keys> {
|
||||
let secret = std::env::var("ENCRYPTION_SECRET")
|
||||
.map_err(|_| anyhow!("missing ENCRYPTION_SECRET environment variable"))?;
|
||||
if secret.trim().is_empty() {
|
||||
return Err(anyhow!("ENCRYPTION_SECRET is empty"));
|
||||
}
|
||||
Keys::parse(&secret).map_err(|e| anyhow!("invalid ENCRYPTION_SECRET: {e}"))
|
||||
}
|
||||
@@ -353,6 +353,30 @@ impl Command {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn insert_manual_lightning_invoice_payment(
|
||||
&self,
|
||||
invoice_id: &str,
|
||||
tenant_pubkey: &str,
|
||||
bolt11: &str,
|
||||
) -> Result<bool> {
|
||||
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",
|
||||
)
|
||||
.bind(invoice_id)
|
||||
.bind(tenant_pubkey)
|
||||
.bind(bolt11)
|
||||
.bind(now)
|
||||
.bind(now)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
|
||||
Ok(result.rows_affected() > 0)
|
||||
}
|
||||
|
||||
pub async fn set_tenant_past_due(&self, pubkey: &str) -> Result<()> {
|
||||
let now = chrono::Utc::now().timestamp();
|
||||
sqlx::query("UPDATE tenant SET past_due_at = ? WHERE pubkey = ?")
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
pub mod api;
|
||||
pub mod billing;
|
||||
pub mod cipher;
|
||||
pub mod command;
|
||||
pub mod infra;
|
||||
pub mod models;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
mod api;
|
||||
mod billing;
|
||||
mod cipher;
|
||||
mod command;
|
||||
mod infra;
|
||||
mod models;
|
||||
|
||||
@@ -171,6 +171,19 @@ impl Query {
|
||||
Ok(state)
|
||||
}
|
||||
|
||||
pub async fn get_invoice_manual_lightning_bolt11(
|
||||
&self,
|
||||
invoice_id: &str,
|
||||
) -> Result<Option<String>> {
|
||||
let bolt11 = sqlx::query_scalar::<_, String>(
|
||||
"SELECT bolt11 FROM invoice_manual_lightning_payment WHERE invoice_id = ?",
|
||||
)
|
||||
.bind(invoice_id)
|
||||
.fetch_optional(&self.pool)
|
||||
.await?;
|
||||
Ok(bolt11)
|
||||
}
|
||||
|
||||
pub async fn has_active_paid_relays(&self, tenant_id: &str) -> Result<bool> {
|
||||
let plans = sqlx::query_scalar::<_, String>(
|
||||
"SELECT plan FROM relay WHERE tenant = ? AND status = 'active'",
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { createSignal } from "solid-js"
|
||||
import { updateRelayById, deactivateRelayById, reactivateRelayById, getLatestOpenInvoice, type Relay } from "@/lib/hooks"
|
||||
import { updateRelayById, deactivateRelayById, reactivateRelayById, getLatestOpenInvoice, tenantNeedsPaymentSetup, type Relay } from "@/lib/hooks"
|
||||
import { setToastMessage } from "@/components/Toast"
|
||||
import type { Invoice, PlanId } from "@/lib/api"
|
||||
|
||||
@@ -31,6 +31,7 @@ export default function useRelayToggles(
|
||||
) {
|
||||
const [busy, setBusy] = createSignal(false)
|
||||
const [pendingInvoice, setPendingInvoice] = createSignal<Invoice | undefined>()
|
||||
const [pendingPaymentSetup, setPendingPaymentSetup] = createSignal(false)
|
||||
|
||||
async function updateRelay(next: Relay, previous: Relay) {
|
||||
mutate(next)
|
||||
@@ -101,8 +102,12 @@ export default function useRelayToggles(
|
||||
}
|
||||
|
||||
if (plan !== "free") {
|
||||
const invoice = await getLatestOpenInvoice()
|
||||
if (invoice) setPendingInvoice(invoice)
|
||||
const needsSetup = await tenantNeedsPaymentSetup()
|
||||
if (needsSetup) {
|
||||
const invoice = await getLatestOpenInvoice()
|
||||
if (invoice) setPendingInvoice(invoice)
|
||||
setPendingPaymentSetup(true)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -116,5 +121,5 @@ export default function useRelayToggles(
|
||||
onToggleLivekitSupport: () => toggle("livekit_enabled", relay()?.plan !== "free"),
|
||||
}
|
||||
|
||||
return { busy, handleDeactivate, handleReactivate, handleUpdatePlan, pendingInvoice, clearPendingInvoice: () => setPendingInvoice(undefined), toggles }
|
||||
return { busy, handleDeactivate, handleReactivate, handleUpdatePlan, pendingInvoice, clearPendingInvoice: () => setPendingInvoice(undefined), pendingPaymentSetup, clearPendingPaymentSetup: () => setPendingPaymentSetup(false), toggles }
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useParams } from "@solidjs/router"
|
||||
import { createMemo, createResource, createSignal, Show } from "solid-js"
|
||||
import { createEffect, createMemo, createResource, createSignal, Show } from "solid-js"
|
||||
import BackLink from "@/components/BackLink"
|
||||
import PageContainer from "@/components/PageContainer"
|
||||
import PaymentDialog from "@/components/PaymentDialog"
|
||||
@@ -28,13 +28,20 @@ export default function RelayDetail() {
|
||||
})
|
||||
const loading = useMinLoading(() => relay.loading && !relay())
|
||||
const [activity] = useRelayActivity(relayId)
|
||||
const { busy, handleDeactivate, handleReactivate, handleUpdatePlan, pendingInvoice, clearPendingInvoice, toggles } = useRelayToggles(relayId, relay, { refetch, mutate })
|
||||
const { busy, handleDeactivate, handleReactivate, handleUpdatePlan, pendingInvoice, clearPendingInvoice, pendingPaymentSetup, clearPendingPaymentSetup, toggles } = useRelayToggles(relayId, relay, { refetch, mutate })
|
||||
|
||||
const [tenant, { refetch: refetchTenant }] = useTenant()
|
||||
const [paymentSetupOpen, setPaymentSetupOpen] = createSignal(false)
|
||||
const [invoiceDialogOpen, setInvoiceDialogOpen] = createSignal(false)
|
||||
const [paymentBannerDismissed, setPaymentBannerDismissed] = createSignal(false)
|
||||
|
||||
createEffect(() => {
|
||||
if (pendingPaymentSetup() && !pendingInvoice()) {
|
||||
setPaymentSetupOpen(true)
|
||||
clearPendingPaymentSetup()
|
||||
}
|
||||
})
|
||||
|
||||
const isPaidRelay = createMemo(() => {
|
||||
const r = relay()
|
||||
if (!r) return false
|
||||
|
||||
@@ -3,13 +3,15 @@ import { useNavigate } from "@solidjs/router"
|
||||
import BackLink from "@/components/BackLink"
|
||||
import PageContainer from "@/components/PageContainer"
|
||||
import PaymentDialog from "@/components/PaymentDialog"
|
||||
import PaymentSetup from "@/components/PaymentSetup"
|
||||
import RelayForm, { type RelayFormValues } from "@/components/RelayForm"
|
||||
import { createRelayForActiveTenant, getLatestOpenInvoice } from "@/lib/hooks"
|
||||
import { createRelayForActiveTenant, getLatestOpenInvoice, tenantNeedsPaymentSetup } from "@/lib/hooks"
|
||||
import type { Invoice } from "@/lib/api"
|
||||
|
||||
export default function RelayNew() {
|
||||
const navigate = useNavigate()
|
||||
const [pendingInvoice, setPendingInvoice] = createSignal<Invoice | undefined>()
|
||||
const [paymentSetupOpen, setPaymentSetupOpen] = createSignal(false)
|
||||
let createdRelayId = ""
|
||||
|
||||
async function handleSubmit(values: RelayFormValues) {
|
||||
@@ -17,9 +19,14 @@ export default function RelayNew() {
|
||||
createdRelayId = relay.id
|
||||
|
||||
if (values.plan !== "free") {
|
||||
const invoice = await getLatestOpenInvoice()
|
||||
if (invoice) {
|
||||
setPendingInvoice(invoice)
|
||||
const needsSetup = await tenantNeedsPaymentSetup()
|
||||
if (needsSetup) {
|
||||
const invoice = await getLatestOpenInvoice()
|
||||
if (invoice) {
|
||||
setPendingInvoice(invoice)
|
||||
return
|
||||
}
|
||||
setPaymentSetupOpen(true)
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -27,8 +34,13 @@ export default function RelayNew() {
|
||||
navigate(`/relays/${relay.id}`)
|
||||
}
|
||||
|
||||
function handleDialogClose() {
|
||||
function handleInvoiceClose() {
|
||||
setPendingInvoice(undefined)
|
||||
setPaymentSetupOpen(true)
|
||||
}
|
||||
|
||||
function handleSetupClose() {
|
||||
setPaymentSetupOpen(false)
|
||||
navigate(`/relays/${createdRelayId}`)
|
||||
}
|
||||
|
||||
@@ -47,10 +59,14 @@ export default function RelayNew() {
|
||||
<PaymentDialog
|
||||
invoice={inv()}
|
||||
open={true}
|
||||
onClose={handleDialogClose}
|
||||
onClose={handleInvoiceClose}
|
||||
/>
|
||||
)}
|
||||
</Show>
|
||||
<PaymentSetup
|
||||
open={paymentSetupOpen()}
|
||||
onClose={handleSetupClose}
|
||||
/>
|
||||
</PageContainer>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -5,6 +5,9 @@ dev:
|
||||
cd frontend && bun dev &
|
||||
wait
|
||||
|
||||
dev-backend:
|
||||
cd backend && onchange src -ik -- bash -c 'RUST_LOG=backend=info cargo run'
|
||||
|
||||
dev-frontend:
|
||||
cd frontend && bun run dev
|
||||
|
||||
@@ -27,7 +30,7 @@ build-backend:
|
||||
cd backend && cargo build
|
||||
|
||||
build-frontend:
|
||||
cd frontend && bun run build
|
||||
cd frontend && bun i && bun run build
|
||||
|
||||
fmt: fmt-backend
|
||||
|
||||
|
||||
Reference in New Issue
Block a user