+ Re-emit every approved event so connected clients pick
+ up the latest tag set. Useful after the extension
+ publisher changes (e.g. new tickets_* tags) so existing
+ events don't need a per-event edit.
+
+
+
+
+
+
- New Event
+
+ New Event
+
+
+
+ Re-emit your approved events to Nostr relays. Useful after
+ a publisher upgrade or if a relay dropped your events.
+
+ Send the paid ticket link automatically by email or Nostr DM.
+
+
+
+
+
+
+
Ticket
+
Bookmark, print or screenshot this page,
and present it for registration!
-
+
+
+
+
-
- Print
+
+ Print
+
diff --git a/tasks.py b/tasks.py
index 651994e..1641a75 100644
--- a/tasks.py
+++ b/tasks.py
@@ -4,9 +4,9 @@ from lnbits.core.models import Payment
from lnbits.tasks import register_invoice_listener
from loguru import logger
-from .crud import get_ticket
+from .crud import get_ticket, get_tickets_by_payment_hash
from .models import Ticket
-from .services import set_ticket_paid
+from .services import send_ticket_notification_in_background, set_ticket_paid
payment_listeners: dict[str, list[asyncio.Queue[Ticket]]] = {}
@@ -37,12 +37,32 @@ async def on_invoice_paid(payment: Payment) -> None:
if not payment.extra or "events" != payment.extra.get("tag"):
return
- ticket = await get_ticket(payment.payment_hash)
- if not ticket:
- logger.warning(f"Ticket for payment {payment.payment_hash} not found.")
+ # Multi-ticket purchases land as N rows sharing this payment_hash;
+ # each one needs to be marked paid + counted against capacity, and
+ # each gets its own buyer notification (mostly a no-op when all
+ # rows are owned by the same buyer, but cheap and consistent).
+ tickets = await get_tickets_by_payment_hash(payment.payment_hash)
+ if not tickets:
+ # Backstop for any legacy row created before the payment_hash
+ # column was populated by the migration backfill.
+ legacy = await get_ticket(payment.payment_hash)
+ if legacy:
+ tickets = [legacy]
+
+ if not tickets:
+ logger.warning(f"No tickets for payment {payment.payment_hash}.")
return
- ticket = await set_ticket_paid(ticket)
+ paid_tickets: list[Ticket] = []
+ for ticket in tickets:
+ paid_tickets.append(await set_ticket_paid(ticket))
+
+ for paid_ticket in paid_tickets:
+ send_ticket_notification_in_background(paid_ticket)
+
+ # Wake up the WebSocket / poll listeners. Forward the first paid
+ # ticket so the existing single-ticket subscribers still work; the
+ # webapp re-fetches all ids via the polling endpoint anyway.
if payment_listeners.get(payment.payment_hash):
for paid_ticket_queue in payment_listeners[payment.payment_hash]:
- paid_ticket_queue.put_nowait(ticket)
+ paid_ticket_queue.put_nowait(paid_tickets[0])
diff --git a/tests/test_nostr_timestamp.py b/tests/test_nostr_timestamp.py
new file mode 100644
index 0000000..693a997
--- /dev/null
+++ b/tests/test_nostr_timestamp.py
@@ -0,0 +1,32 @@
+from itertools import pairwise
+
+from ..nostr_timestamp import monotonic_created_at
+
+
+def test_no_prior_uses_now():
+ assert monotonic_created_at(None, now=1000) == 1000
+
+
+def test_same_second_bumps_past_prior():
+ # now == last: a naive int(time.time()) would tie and the relay would
+ # drop the update; we must produce a strictly newer stamp.
+ assert monotonic_created_at(1000, now=1000) == 1001
+
+
+def test_tracks_wallclock_once_seconds_elapse():
+ assert monotonic_created_at(1000, now=1005) == 1005
+
+
+def test_steps_past_future_dated_prior():
+ # clock skew / rapid bursts left the stored value ahead of now
+ assert monotonic_created_at(2000, now=1000) == 2001
+
+
+def test_strictly_increasing_same_second_burst():
+ last = None
+ stamps = []
+ for _ in range(5):
+ last = monotonic_created_at(last, now=1000) # clock frozen at 1000
+ stamps.append(last)
+ assert stamps == [1000, 1001, 1002, 1003, 1004]
+ assert all(b > a for a, b in pairwise(stamps))
diff --git a/transport_rpcs.py b/transport_rpcs.py
new file mode 100644
index 0000000..e278f91
--- /dev/null
+++ b/transport_rpcs.py
@@ -0,0 +1,120 @@
+"""
+Nostr-transport RPC handlers for the aiolabs/events extension.
+
+Each handler is registered with `lnbits.core.services.nostr_transport.
+dispatcher.register_rpc` in `events_start()`. The dispatcher resolves
+the caller's Nostr pubkey to an LNbits Account → wallet (`AUTH_WALLET`)
+and passes a `WalletTypeInfo` as the first argument; handlers verify
+event-level ownership on top.
+
+Errors raise `PermissionError` / `ValueError` so the dispatcher maps
+them into `{status: "ERROR", error: }` responses; any other
+exception falls through to a generic "Internal error" reply.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime, timezone
+
+from lnbits.core.crud import get_user
+from lnbits.core.models import WalletTypeInfo
+from lnbits.core.services.nostr_transport.models import NostrRpcRequest
+
+from .crud import get_event, get_ticket, get_tickets_by_event, update_ticket
+
+
+async def handle_events_ticket_register(
+ auth: WalletTypeInfo,
+ request: NostrRpcRequest,
+) -> dict:
+ """Mark a ticket as registered at the door (organizer flow).
+
+ The Nostr-transport dispatcher already verified the caller signed
+ the kind-21000 RPC event and bound them to `auth.wallet`. This
+ handler adds the event-level check: the ticket's event must be
+ owned by one of the caller's wallets.
+
+ Idempotence mirrors the HTTP endpoint: scanning the same ticket
+ twice fails with "Ticket already registered". The buyer-side flow
+ (notifications etc.) reuses whatever the legacy register endpoint
+ does — we just flip the flag + timestamp.
+ """
+ body = request.body or {}
+ event_id = body.get("event_id")
+ ticket_id = body.get("ticket_id")
+ if not event_id or not ticket_id:
+ raise ValueError("event_id and ticket_id are required")
+
+ ticket = await get_ticket(ticket_id)
+ if not ticket or ticket.event != event_id:
+ raise ValueError("Ticket does not exist on this event")
+ if not ticket.paid:
+ raise PermissionError("Ticket not paid for")
+ if ticket.registered:
+ raise PermissionError("Ticket already registered")
+
+ event = await get_event(event_id)
+ if not event:
+ raise ValueError("Event does not exist")
+
+ user = await get_user(auth.wallet.user)
+ owned_wallet_ids = user.wallet_ids if user else [auth.wallet.id]
+ if event.wallet not in owned_wallet_ids:
+ raise PermissionError("You do not own this event")
+
+ ticket.registered = True
+ ticket.reg_timestamp = datetime.now(timezone.utc)
+ await update_ticket(ticket)
+ return ticket.dict()
+
+
+async def handle_events_list_event_tickets(
+ auth: WalletTypeInfo,
+ request: NostrRpcRequest,
+) -> dict:
+ """Return paid + registered counts plus the per-ticket roster for
+ one calendar event, organizer-only.
+
+ Backs the door scanner's counts strip and "All scanned" tab so the
+ UI reads authoritative state from the backend instead of relying
+ on per-device localStorage (which diverges the moment a second
+ organizer scans, or the operator switches devices).
+
+ The roster only includes paid tickets — proposed/unpaid rows are
+ irrelevant at the door.
+ """
+ body = request.body or {}
+ event_id = body.get("event_id")
+ if not event_id:
+ raise ValueError("event_id is required")
+
+ event = await get_event(event_id)
+ if not event:
+ raise ValueError("Event does not exist")
+
+ user = await get_user(auth.wallet.user)
+ owned_wallet_ids = user.wallet_ids if user else [auth.wallet.id]
+ if event.wallet not in owned_wallet_ids:
+ raise PermissionError("You do not own this event")
+
+ tickets = await get_tickets_by_event(event_id)
+ paid_tickets = [t for t in tickets if t.paid]
+ registered_count = sum(1 for t in paid_tickets if t.registered)
+
+ return {
+ "event_id": event_id,
+ "sold": len(paid_tickets),
+ "registered": registered_count,
+ "remaining": len(paid_tickets) - registered_count,
+ "tickets": [
+ {
+ "id": t.id,
+ "name": t.name,
+ "registered": t.registered,
+ "registered_at": (
+ t.reg_timestamp.isoformat() if t.reg_timestamp else None
+ ),
+ }
+ for t in paid_tickets
+ ],
+ }
diff --git a/views_api.py b/views_api.py
index b1d4149..5ced0ef 100644
--- a/views_api.py
+++ b/views_api.py
@@ -8,21 +8,29 @@ from fastapi import (
Depends,
HTTPException,
Query,
+ Request,
WebSocket,
WebSocketDisconnect,
)
from lnbits.core.crud import get_user
-from lnbits.core.models import Account, WalletTypeInfo
-from lnbits.core.services import create_invoice
+from lnbits.core.crud.wallets import get_wallet
+from lnbits.core.models import Account, User, WalletTypeInfo
+from lnbits.core.models.payments import CreateInvoice
+from lnbits.core.services import create_payment_request
+from lnbits.helpers import urlsafe_short_hash
from lnbits.decorators import (
check_admin,
+ check_user_exists,
require_admin_key,
require_invoice_key,
)
+from lnbits.settings import settings
from lnbits.utils.exchange_rates import (
fiat_amount_as_satoshis,
get_fiat_rate_satoshis,
+ satoshis_amount_as_fiat,
)
+from lnbits.utils.nostr import normalize_public_key
from .crud import (
create_event,
@@ -39,6 +47,8 @@ from .crud import (
get_settings,
get_ticket,
get_tickets,
+ get_tickets_by_event,
+ get_tickets_by_payment_hash,
get_tickets_by_user_id,
purge_unpaid_tickets,
update_event,
@@ -56,13 +66,22 @@ from .models import (
TicketPaymentRequest,
)
from .nostr_hooks import publish_or_delete_nostr_event
-from .services import refund_tickets
+from .services import (
+ refund_tickets,
+ resend_ticket_email_notification,
+ send_ticket_notification_in_background,
+ set_ticket_paid,
+)
from .tasks import deregister_payment_listener, register_payment_listener
events_api_router = APIRouter(prefix="/api/v1/events")
tickets_api_router = APIRouter(prefix="/api/v1/tickets")
+def _is_fiat_currency(currency: str | None) -> bool:
+ return str(currency or "").lower() not in {"sat", "sats"}
+
+
# Literal-prefix routes (/public, /all, /pending, /settings) MUST be declared
# before any "/{event_id}" route or FastAPI matches them as a path parameter.
@@ -88,9 +107,22 @@ async def api_events_public() -> list[Event]:
@events_api_router.get("/all")
async def api_events_all(
admin: Account = Depends(check_admin),
-) -> list[Event]:
- """All events across all wallets. LNbits admin only."""
- return await get_all_events()
+) -> list[dict]:
+ """All events across all wallets, with each row's wallet owner
+ resolved to a user_id. LNbits admin only.
+
+ Returns dicts (not strict `Event` rows) so the response can carry
+ the synthetic `wallet_user_id` column the admin UI uses to attribute
+ each cross-tenant event to a user.
+ """
+ events = await get_all_events()
+ enriched: list[dict] = []
+ for event in events:
+ wallet = await get_wallet(event.wallet)
+ row = event.dict()
+ row["wallet_user_id"] = wallet.user if wallet else None
+ enriched.append(row)
+ return enriched
@events_api_router.get("/pending")
@@ -101,6 +133,61 @@ async def api_events_pending(
return await get_pending_events()
+@events_api_router.post("/republish-all")
+async def api_republish_all(
+ admin: Account = Depends(check_admin),
+) -> dict:
+ """Force-republish every approved event to Nostr relays. Admin only.
+
+ Used by the catalog-bump migration that introduced the AIO ticket
+ tags: existing events on a deployed instance were published before
+ the publisher learned the new tag set, so they don't carry
+ tickets_available / tickets_sold / etc. until something triggers
+ a republish. This endpoint walks the approved list and re-emits
+ each calendar event so connected clients see the new metadata
+ without waiting for a per-event edit.
+
+ Errors are swallowed per-event (logged inside the publisher) so
+ one bad event doesn't block the rest. Returns a count summary.
+ """
+ events = await get_all_events()
+ approved = [e for e in events if e.status == "approved" and not e.canceled]
+ for event in approved:
+ await publish_or_delete_nostr_event(event)
+ return {"republished": len(approved), "total": len(events)}
+
+
+@events_api_router.post("/republish-mine")
+async def api_republish_mine(
+ all_wallets: bool = Query(False),
+ key_info: WalletTypeInfo = Depends(require_admin_key),
+) -> dict:
+ """Force-republish the caller's own approved events to Nostr relays.
+
+ Same shape as /republish-all but scoped to events owned by the
+ authenticated wallet (or all wallets belonging to the wallet's
+ user when `?all_wallets=true`). Lets the organizer trigger the
+ same migration the admin uses, without needing instance-admin
+ rights — useful when the AIO publisher gains a new tag set and
+ an organizer wants their published events to carry it.
+
+ Only events with `status == "approved"` are republished; pending
+ and rejected rows aren't on relays in the first place, so a
+ republish for them would be a no-op (or worse, surface a
+ proposed-but-not-approved row to subscribers).
+ """
+ wallet_ids: list[str] = [key_info.wallet.id]
+ if all_wallets:
+ user = await get_user(key_info.wallet.user)
+ wallet_ids = user.wallet_ids if user else []
+
+ events = await get_events(wallet_ids)
+ approved = [e for e in events if e.status == "approved" and not e.canceled]
+ for event in approved:
+ await publish_or_delete_nostr_event(event)
+ return {"republished": len(approved), "total": len(events)}
+
+
@events_api_router.get("/settings")
async def api_get_settings(
admin: Account = Depends(check_admin),
@@ -153,8 +240,9 @@ async def api_get_event(event_id: str) -> Event:
# closing_date is filled in by create_event (defaults to end_date or
# start_date) but the field is typed Optional, so guard for the typechecker.
closing_date = event.closing_date or event.event_end_date or event.event_start_date
- # Accept either YYYY-MM-DD or full ISO 8601 datetime (e.g. event_end_date
- # may carry a time component since v1.3.0-aio.3).
+ # Accept either YYYY-MM-DD or full ISO 8601 datetime (event_end_date
+ # may carry a time component since v1.3.0-aio.3 / our start-end-time
+ # feature).
try:
closing_dt = datetime.fromisoformat(closing_date)
except ValueError:
@@ -253,6 +341,8 @@ async def api_event_update(
data.closing_date = data.event_end_date
# Explicit field list — never copy `status` from the request body.
+ # Includes upstream v1.6.1 fields (allow_fiat, fiat_currency) so an
+ # owner editing a fiat-enabled event keeps the fiat config.
for field in (
"name",
"info",
@@ -260,6 +350,8 @@ async def api_event_update(
"event_start_date",
"event_end_date",
"currency",
+ "allow_fiat",
+ "fiat_currency",
"amount_tickets",
"price_per_ticket",
"banner",
@@ -386,12 +478,23 @@ async def api_tickets(
@tickets_api_router.get("/user/{user_id}")
-async def api_tickets_by_user_id(user_id: str) -> list[Ticket]:
- """Tickets bound to an LNbits user_id (used by external integrations).
+async def api_tickets_by_user(
+ user_id: str,
+ user: User = Depends(check_user_exists),
+) -> list[Ticket]:
+ """All tickets for the authenticated user.
- Declared before /{ticket_id} so FastAPI matches the literal `/user/`
- prefix instead of treating "user" as a ticket id.
+ The `user_id` path param must match the token-bound user so a
+ Bearer-authenticated session can only enumerate its own tickets.
+ Returns full `Ticket` rows (not `PublicTicket`) since the owner
+ needs the payment_hash to render the QR + the `extra` envelope
+ to surface payment/refund state in My Tickets.
"""
+ if user_id != user.id:
+ raise HTTPException(
+ status_code=HTTPStatus.FORBIDDEN,
+ detail="Can only fetch your own tickets.",
+ )
return await get_tickets_by_user_id(user_id)
@@ -410,8 +513,66 @@ async def api_get_ticket(ticket_id: str) -> Ticket:
return ticket
+async def _issue_free_tickets(
+ *,
+ event: Event,
+ quantity: int,
+ name: str | None,
+ email: str | None,
+ user_id: str | None,
+ promo_code: str | None,
+ nostr_identifier: str | None,
+ request: Request,
+) -> TicketPaymentRequest:
+ """Issue `quantity` free tickets without minting an invoice.
+
+ Each row is created then run through `set_ticket_paid` — the exact path
+ `on_invoice_paid` drives for a settled payment: it flips `paid`, bumps
+ the sold / available counters under the per-event lock, and republishes
+ the NIP-52 calendar event so connected clients see the new counts.
+ Notifications fire the same way. No invoice exists, so `sats_paid` is 0
+ and these tickets are naturally skipped by `refund_tickets`.
+
+ All rows in the batch share one synthetic `payment_hash` — the join key
+ the poll / WebSocket / My-Tickets lookups use — mirroring how the paid
+ multi-ticket path shares the real invoice hash.
+ """
+ payment_hash = urlsafe_short_hash()
+ ticket_ids: list[str] = []
+ for _ in range(quantity):
+ row_id = urlsafe_short_hash()
+ ticket = await create_ticket(
+ payment_hash=payment_hash,
+ wallet=event.wallet,
+ event=event.id,
+ name=name,
+ email=email,
+ user_id=user_id,
+ ticket_id=row_id,
+ extra={
+ "applied_promo_code": promo_code,
+ "nostr_identifier": nostr_identifier,
+ "ticket_base_url": str(request.base_url).rstrip("/"),
+ "sats_paid": 0,
+ },
+ )
+ await set_ticket_paid(ticket)
+ send_ticket_notification_in_background(ticket)
+ ticket_ids.append(row_id)
+
+ return TicketPaymentRequest(
+ payment_hash=payment_hash,
+ payment_request=None,
+ is_fiat=False,
+ paid=True,
+ ticket_ids=ticket_ids,
+ )
+
+
@tickets_api_router.post("/{event_id}")
-async def api_ticket_create(event_id: str, data: CreateTicket) -> TicketPaymentRequest:
+async def api_ticket_create(
+ event_id: str, data: CreateTicket, request: Request
+) -> TicketPaymentRequest:
event = await get_event(event_id)
if not event:
raise HTTPException(
@@ -424,91 +585,187 @@ async def api_ticket_create(event_id: str, data: CreateTicket) -> TicketPaymentR
)
if event.canceled:
raise HTTPException(status_code=HTTPStatus.GONE, detail="Event is canceled.")
- if event.amount_tickets > 0 and event.sold >= event.amount_tickets:
- raise HTTPException(status_code=HTTPStatus.GONE, detail="Event is sold out.")
+ quantity = data.quantity
+ if event.amount_tickets > 0:
+ if event.sold >= event.amount_tickets:
+ raise HTTPException(status_code=HTTPStatus.GONE, detail="Event is sold out.")
+ remaining = event.amount_tickets - event.sold
+ if quantity > remaining:
+ raise HTTPException(
+ status_code=HTTPStatus.BAD_REQUEST,
+ detail=f"Only {remaining} ticket(s) remaining for this event.",
+ )
- if data.user_id:
- return await _create_user_id_ticket(event, data.user_id)
- return await _create_named_ticket(event, data)
-
-
-async def _create_named_ticket(
- event: Event, data: CreateTicket
-) -> TicketPaymentRequest:
name = data.name
email = data.email
+ user_id = data.user_id
promo_code = data.promo_code.upper() if data.promo_code else None
refund_address = data.refund_address
- price = event.price_per_ticket
+ nostr_identifier = data.nostr_identifier.strip() if data.nostr_identifier else None
+ payment_method = (data.payment_method or "lightning").lower()
+ if payment_method not in {"lightning", "fiat"}:
+ raise HTTPException(
+ status_code=HTTPStatus.BAD_REQUEST,
+ detail="Unsupported payment method.",
+ )
+ if nostr_identifier and "@" not in nostr_identifier:
+ try:
+ nostr_identifier = normalize_public_key(nostr_identifier)
+ except Exception as exc:
+ raise HTTPException(
+ status_code=HTTPStatus.BAD_REQUEST,
+ detail="Invalid Nostr identifier.",
+ ) from exc
+ unit_price = event.price_per_ticket
extra: dict[str, Any] = {"tag": "events", "name": name, "email": email}
if promo_code:
+ # check if promo_code exists in event.extra.promo_codes
if promo_code not in [pc.code for pc in event.extra.promo_codes]:
raise HTTPException(
status_code=HTTPStatus.BAD_REQUEST, detail="Invalid promo code."
)
+ # get the promocode
promo = next(pc for pc in event.extra.promo_codes if pc.code == promo_code)
extra["promo_code"] = promo.code
- price = event.price_per_ticket * (1 - promo.discount_percent / 100)
+ unit_price = event.price_per_ticket * (1 - promo.discount_percent / 100)
+ # Scale by quantity AFTER the promo applies. One invoice, N tickets.
+ price = unit_price * quantity
- if event.currency != "sats":
+ # Free tickets (final charge 0 — a free event or a 100%-off promo).
+ # Short-circuit before any invoice / fiat-provider logic: no Lightning
+ # invoice can settle for 0, so we issue the rows and mark them paid
+ # directly. payment_method is irrelevant here (nothing is charged).
+ if price <= 0:
+ return await _issue_free_tickets(
+ event=event,
+ quantity=quantity,
+ name=name,
+ email=email,
+ user_id=user_id,
+ promo_code=promo_code,
+ nostr_identifier=nostr_identifier,
+ request=request,
+ )
+
+ if payment_method == "fiat" and not event.allow_fiat:
+ raise HTTPException(
+ status_code=HTTPStatus.BAD_REQUEST,
+ detail="Fiat payments are not enabled for this event.",
+ )
+
+ if _is_fiat_currency(event.currency):
extra["fiat"] = True
extra["currency"] = event.currency
extra["fiatAmount"] = price
extra["rate"] = await get_fiat_rate_satoshis(event.currency)
- price = await fiat_amount_as_satoshis(price, event.currency)
- payment = await create_invoice(
+ if payment_method != "fiat":
+ price = await fiat_amount_as_satoshis(price, event.currency)
+
+ invoice_unit = event.currency
+ fiat_amount = price
+ fiat_provider = None
+ if payment_method == "fiat":
+ if _is_fiat_currency(event.currency):
+ invoice_unit = event.currency
+ else:
+ invoice_unit = event.fiat_currency
+ fiat_amount = await satoshis_amount_as_fiat(price, invoice_unit)
+ extra["fiat"] = True
+ extra["currency"] = invoice_unit
+ extra["fiatAmount"] = fiat_amount
+ extra["rate"] = await get_fiat_rate_satoshis(invoice_unit)
+ wallet = await get_wallet(event.wallet)
+ if not wallet:
+ raise HTTPException(
+ status_code=HTTPStatus.NOT_FOUND,
+ detail="Event wallet does not exist.",
+ )
+ providers = settings.get_fiat_providers_for_user(wallet.user)
+ fiat_provider = data.fiat_provider or (providers[0] if providers else None)
+ if not fiat_provider:
+ raise HTTPException(
+ status_code=HTTPStatus.BAD_REQUEST,
+ detail="No fiat payment provider configured for this event.",
+ )
+ else:
+ invoice_unit = "sat"
+
+ payment = await create_payment_request(
wallet_id=event.wallet,
- amount=price,
- memo=f"{event.id}",
- extra=extra,
- )
- await create_ticket(
- payment_hash=payment.payment_hash,
- wallet=event.wallet,
- event=event.id,
- name=name,
- email=email,
- extra={
- "applied_promo_code": promo_code,
- "refund_address": refund_address,
- "sats_paid": int(price),
- },
+ invoice_data=CreateInvoice(
+ out=False,
+ amount=fiat_amount if payment_method == "fiat" else price,
+ unit=invoice_unit,
+ fiat_provider=fiat_provider,
+ memo=f"{event_id}",
+ extra=extra,
+ ),
)
+ # Each row gets a fresh urlsafe_short_hash id so single- and
+ # multi-ticket purchases stay shape-consistent — every scannable
+ # ticket id is a short hash, never the long bolt11 payment_hash.
+ # The shared `payment_hash` column is the join key for invoice
+ # lookup (poll endpoint, ws notifier, set_ticket_paid loop).
+ ticket_ids: list[str] = []
+ sats_per_ticket = payment.sat // quantity if quantity else payment.sat
+ for _ in range(quantity):
+ row_id = urlsafe_short_hash()
+ await create_ticket(
+ payment_hash=payment.payment_hash,
+ wallet=event.wallet,
+ event=event.id,
+ name=name,
+ email=email,
+ user_id=user_id,
+ ticket_id=row_id,
+ extra={
+ "applied_promo_code": promo_code,
+ "refund_address": refund_address,
+ "nostr_identifier": nostr_identifier,
+ "ticket_base_url": str(request.base_url).rstrip("/"),
+ "sats_paid": sats_per_ticket,
+ },
+ )
+ ticket_ids.append(row_id)
+
return TicketPaymentRequest(
- payment_hash=payment.payment_hash, payment_request=payment.bolt11
- )
-
-
-async def _create_user_id_ticket(event: Event, user_id: str) -> TicketPaymentRequest:
- price = event.price_per_ticket
- extra: dict[str, Any] = {"tag": "events", "user_id": user_id}
-
- if event.currency != "sats":
- price = await fiat_amount_as_satoshis(event.price_per_ticket, event.currency)
- extra["fiat"] = True
- extra["currency"] = event.currency
- extra["fiatAmount"] = event.price_per_ticket
- extra["rate"] = await get_fiat_rate_satoshis(event.currency)
-
- payment = await create_invoice(
- wallet_id=event.wallet,
- amount=price,
- memo=f"{event.id}",
- extra=extra,
- )
- await create_ticket(
payment_hash=payment.payment_hash,
- wallet=event.wallet,
- event=event.id,
- user_id=user_id,
- )
- return TicketPaymentRequest(
- payment_hash=payment.payment_hash, payment_request=payment.bolt11
+ payment_request=getattr(payment, "bolt11", None),
+ fiat_payment_request=getattr(payment, "extra", {}).get("fiat_payment_request"),
+ fiat_provider=getattr(payment, "fiat_provider", None) or fiat_provider,
+ is_fiat=bool(getattr(payment, "fiat_provider", None) or fiat_provider),
+ ticket_ids=ticket_ids,
)
+@tickets_api_router.post("/{event_id}/{payment_hash}")
+async def api_ticket_payment_status(event_id: str, payment_hash: str) -> dict:
+ """Poll-style payment confirmation for a pending ticket purchase.
+
+ The webapp polls this every 2s after presenting the invoice until
+ `paid: true` comes back, then advances to the success state. The
+ companion WebSocket at `/tickets/ws/{payment_hash}` is more
+ efficient for pushes — this endpoint is the fallback.
+
+ Returns `{paid, ticket_ids: [...]}` so multi-ticket buyers get
+ every scannable id back in one response (one for single-ticket
+ purchases). A missing / cross-event purchase returns
+ `paid: false` rather than 404 so the poll doesn't have to
+ special-case the not-yet-created race.
+ """
+ tickets = await get_tickets_by_payment_hash(payment_hash)
+ relevant = [t for t in tickets if t.event == event_id]
+ if not relevant:
+ return {"paid": False}
+ return {
+ "paid": all(t.paid for t in relevant),
+ "ticket_id": relevant[0].id, # back-compat with single-ticket clients
+ "ticket_ids": [t.id for t in relevant],
+ }
+
+
@tickets_api_router.websocket("/ws/{payment_hash}")
async def websocket_endpoint(payment_hash: str, websocket: WebSocket) -> None:
await websocket.accept()
@@ -567,8 +824,57 @@ async def api_ticket_delete(
await delete_ticket(ticket_id)
+@tickets_api_router.post("/{ticket_id}/resend-email")
+async def api_ticket_resend_email(
+ ticket_id: str, wallet: WalletTypeInfo = Depends(require_admin_key)
+) -> Ticket:
+ ticket = await get_ticket(ticket_id)
+ if not ticket:
+ raise HTTPException(
+ status_code=HTTPStatus.NOT_FOUND, detail="Ticket does not exist."
+ )
+
+ if ticket.wallet != wallet.wallet.id:
+ raise HTTPException(status_code=HTTPStatus.FORBIDDEN, detail="Not your ticket.")
+
+ if not ticket.paid:
+ raise HTTPException(
+ status_code=HTTPStatus.FORBIDDEN,
+ detail="Only paid tickets can be resent by email.",
+ )
+
+ try:
+ return await resend_ticket_email_notification(ticket)
+ except ValueError as exc:
+ raise HTTPException(
+ status_code=HTTPStatus.BAD_REQUEST, detail=str(exc)
+ ) from exc
+ except Exception as exc:
+ raise HTTPException(
+ status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
+ detail="Failed to resend ticket email.",
+ ) from exc
+
+
@tickets_api_router.put("/register/{ticket_id}")
-async def api_event_register_ticket(ticket_id) -> Ticket:
+async def api_event_register_ticket(
+ ticket_id: str,
+ key_info: WalletTypeInfo = Depends(require_admin_key),
+) -> Ticket:
+ """Mark a ticket as registered at the door.
+
+ Auth: wallet admin_key. Caller must own the event the ticket
+ belongs to — we check `event.wallet` against the user's full
+ wallet set so an organizer with multiple wallets can scan
+ regardless of which wallet's key they're using.
+
+ Until v1.6.1-aio.3 this endpoint had no auth, which meant any
+ caller who knew a ticket id could register it. The
+ Nostr-transport flow at `events_ticket_register` is now the
+ preferred call site for the webapp; this HTTP path stays for
+ the legacy LNbits Quasar register page which already sends
+ the wallet admin_key through `LNbits.api.request`.
+ """
ticket = await get_ticket(ticket_id)
if not ticket:
@@ -576,6 +882,20 @@ async def api_event_register_ticket(ticket_id) -> Ticket:
status_code=HTTPStatus.NOT_FOUND, detail="Ticket does not exist."
)
+ event = await get_event(ticket.event)
+ if not event:
+ raise HTTPException(
+ status_code=HTTPStatus.NOT_FOUND, detail="Event does not exist."
+ )
+
+ user = await get_user(key_info.wallet.user)
+ owned_wallet_ids = user.wallet_ids if user else [key_info.wallet.id]
+ if event.wallet not in owned_wallet_ids:
+ raise HTTPException(
+ status_code=HTTPStatus.FORBIDDEN,
+ detail="You do not own this event.",
+ )
+
if not ticket.paid:
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN, detail="Ticket not paid for."
@@ -590,3 +910,52 @@ async def api_event_register_ticket(ticket_id) -> Ticket:
ticket.reg_timestamp = datetime.now(timezone.utc)
ticket = await update_ticket(ticket)
return ticket
+
+
+@tickets_api_router.get("/event/{event_id}/stats")
+async def api_event_ticket_stats(
+ event_id: str,
+ key_info: WalletTypeInfo = Depends(require_admin_key),
+) -> dict:
+ """Door-scanner roster + counts for one event, organizer-only.
+
+ Mirrors the `events_list_event_tickets` nostr-transport RPC for
+ callers that don't hold a raw user prvkey (the webapp post-#9, in
+ particular). Auth: wallet admin_key + the event's wallet must be
+ in the caller's wallet set.
+ """
+ event = await get_event(event_id)
+ if not event:
+ raise HTTPException(
+ status_code=HTTPStatus.NOT_FOUND, detail="Event does not exist."
+ )
+
+ user = await get_user(key_info.wallet.user)
+ owned_wallet_ids = user.wallet_ids if user else [key_info.wallet.id]
+ if event.wallet not in owned_wallet_ids:
+ raise HTTPException(
+ status_code=HTTPStatus.FORBIDDEN,
+ detail="You do not own this event.",
+ )
+
+ tickets = await get_tickets_by_event(event_id)
+ paid_tickets = [t for t in tickets if t.paid]
+ registered_count = sum(1 for t in paid_tickets if t.registered)
+
+ return {
+ "event_id": event_id,
+ "sold": len(paid_tickets),
+ "registered": registered_count,
+ "remaining": len(paid_tickets) - registered_count,
+ "tickets": [
+ {
+ "id": t.id,
+ "name": t.name,
+ "registered": t.registered,
+ "registered_at": (
+ t.reg_timestamp.isoformat() if t.reg_timestamp else None
+ ),
+ }
+ for t in paid_tickets
+ ],
+ }