diff --git a/API_DOCUMENTATION.md b/API_DOCUMENTATION.md
new file mode 100644
index 0000000..9ad0d5f
--- /dev/null
+++ b/API_DOCUMENTATION.md
@@ -0,0 +1,56 @@
+# Events API Documentation
+
+## Public Events Endpoint
+
+### GET `/api/v1/events/public`
+
+Retrieve all events in the database with read-only access. No authentication required.
+
+**Authentication:** None required (public endpoint)
+
+**Headers:**
+```
+None required
+```
+
+**Query Parameters:**
+- None
+
+**Response:**
+```json
+[
+ {
+ "id": "event_id",
+ "wallet": "wallet_id",
+ "name": "Event Name",
+ "info": "Event description",
+ "closing_date": "2024-12-31",
+ "event_start_date": "2024-12-01",
+ "event_end_date": "2024-12-02",
+ "currency": "sat",
+ "amount_tickets": 100,
+ "price_per_ticket": 1000.0,
+ "time": "2024-01-01T00:00:00Z",
+ "sold": 0,
+ "banner": null
+ }
+]
+```
+
+**Example Usage:**
+```bash
+curl http://your-lnbits-instance/events/api/v1/events/public
+```
+
+**Notes:**
+- This endpoint allows read-only access to all events in the database
+- No authentication required (truly public endpoint)
+- Returns events ordered by creation time (newest first)
+- Suitable for public event listings or read-only integrations
+
+## Comparison with Existing Endpoints
+
+| Endpoint | Authentication | Scope | Use Case |
+|----------|---------------|-------|----------|
+| `/api/v1/events` | Invoice Key | User's wallets only | Private event management |
+| `/api/v1/events/public` | None | All events | Public event browsing |
\ No newline at end of file
diff --git a/README.md b/README.md
index ebd7194..f356ba7 100644
--- a/README.md
+++ b/README.md
@@ -2,9 +2,9 @@
For more about LNBits extension check [this tutorial](https://github.com/lnbits/lnbits/wiki/LNbits-Extensions)
-## Sell tickets for events and use the built-in scanner for registering attendants
+## Sell tickets for events and use the built-in scanner for registering attendees
-Events alows you to make tickets for an event. Each ticket is in the form of a uniqque QR code. After registering, and paying for ticket, the user gets a QR code to present at registration/entrance.
+Events alows you to make tickets for an event. Each ticket is in the form of a unique QR code. After registering, and paying for ticket, the user gets a QR code to present at registration/entrance.
Events includes a shareable ticket scanner, which can be used to register attendees.
diff --git a/crud.py b/crud.py
index 6d19761..8996a2e 100644
--- a/crud.py
+++ b/crud.py
@@ -1,54 +1,147 @@
from datetime import datetime, timedelta, timezone
+from typing import Optional
from lnbits.db import Database
from lnbits.helpers import urlsafe_short_hash
-from .models import CreateEvent, Event, Ticket
+from .models import CreateEvent, Event, Ticket, TicketExtra
db = Database("ext_events")
async def create_ticket(
- payment_hash: str, wallet: str, event: str, name: str, email: str
+ payment_hash: str,
+ wallet: str,
+ event: str,
+ name: Optional[str] = None,
+ email: Optional[str] = None,
+ user_id: Optional[str] = None,
+ extra: Optional[dict] = None,
) -> Ticket:
now = datetime.now(timezone.utc)
- ticket = Ticket(
+
+ # TODO: Check if this empty string workaround is still needed.
+ # This converts None to empty strings for database storage because:
+ # 1. Database may have NOT NULL constraints on name/email columns
+ # 2. When user_id is provided, name/email are not used (mutually exclusive)
+ # 3. The get_ticket() functions convert empty strings back to None when reading
+ # Consider using nullable columns instead of this empty string pattern.
+ if user_id:
+ db_name = ""
+ db_email = ""
+ else:
+ db_name = name or ""
+ db_email = email or ""
+
+ # Create ticket with database-compatible values for insertion
+ # Using db.insert() ensures proper serialization of the extra field (TicketExtra)
+ # across all database backends (SQLite, PostgreSQL, CockroachDB)
+ db_ticket = Ticket(
+ id=payment_hash,
+ wallet=wallet,
+ event=event,
+ name=db_name,
+ email=db_email,
+ user_id=user_id,
+ registered=False,
+ paid=False,
+ reg_timestamp=now,
+ time=now,
+ extra=TicketExtra(**extra) if extra else TicketExtra(),
+ )
+
+ await db.insert("events.ticket", db_ticket)
+
+ # Return ticket with original name/email values (not empty strings)
+ # This maintains consistency with how get_ticket() converts empty strings back to None
+ return Ticket(
id=payment_hash,
wallet=wallet,
event=event,
name=name,
email=email,
+ user_id=user_id,
registered=False,
paid=False,
reg_timestamp=now,
time=now,
+ extra=TicketExtra(**extra) if extra else TicketExtra(),
)
- await db.insert("events.ticket", ticket)
- return ticket
async def update_ticket(ticket: Ticket) -> Ticket:
- await db.update("events.ticket", ticket)
+ # Create a new Ticket object with corrected values for database constraints
+ ticket_dict = ticket.dict()
+
+ # Convert None values to empty strings for database constraints
+ if ticket_dict.get("name") is None:
+ ticket_dict["name"] = ""
+ if ticket_dict.get("email") is None:
+ ticket_dict["email"] = ""
+
+ # Create a new Ticket object with the corrected values
+ corrected_ticket = Ticket(**ticket_dict)
+
+ await db.update("events.ticket", corrected_ticket)
return ticket
-async def get_ticket(payment_hash: str) -> Ticket | None:
- return await db.fetchone(
+async def get_ticket(payment_hash: str) -> Optional[Ticket]:
+ row = await db.fetchone(
"SELECT * FROM events.ticket WHERE id = :id",
{"id": payment_hash},
- Ticket,
)
+ if not row:
+ return None
+
+ # Convert empty strings back to None for the model
+ ticket_data = dict(row)
+ if ticket_data.get("name") == "":
+ ticket_data["name"] = None
+ if ticket_data.get("email") == "":
+ ticket_data["email"] = None
+
+ return Ticket(**ticket_data)
async def get_tickets(wallet_ids: str | list[str]) -> list[Ticket]:
if isinstance(wallet_ids, str):
wallet_ids = [wallet_ids]
q = ",".join([f"'{wallet_id}'" for wallet_id in wallet_ids])
- return await db.fetchall(
- f"SELECT * FROM events.ticket WHERE wallet IN ({q})",
- model=Ticket,
+ rows = await db.fetchall(f"SELECT * FROM events.ticket WHERE wallet IN ({q})")
+
+ tickets = []
+ for row in rows:
+ # Convert empty strings back to None for the model
+ ticket_data = dict(row)
+ if ticket_data.get("name") == "":
+ ticket_data["name"] = None
+ if ticket_data.get("email") == "":
+ ticket_data["email"] = None
+ tickets.append(Ticket(**ticket_data))
+
+ return tickets
+
+
+async def get_tickets_by_user_id(user_id: str) -> list[Ticket]:
+ """Get all tickets for a specific user by their user_id"""
+ rows = await db.fetchall(
+ "SELECT * FROM events.ticket WHERE user_id = :user_id ORDER BY time DESC",
+ {"user_id": user_id}
)
+ tickets = []
+ for row in rows:
+ # Convert empty strings back to None for the model
+ ticket_data = dict(row)
+ if ticket_data.get("name") == "":
+ ticket_data["name"] = None
+ if ticket_data.get("email") == "":
+ ticket_data["email"] = None
+ tickets.append(Ticket(**ticket_data))
+
+ return tickets
+
async def delete_ticket(payment_hash: str) -> None:
await db.execute("DELETE FROM events.ticket WHERE id = :id", {"id": payment_hash})
@@ -101,13 +194,32 @@ async def get_events(wallet_ids: str | list[str]) -> list[Event]:
)
+async def get_all_events() -> list[Event]:
+ """Get all events from the database without wallet filtering."""
+ return await db.fetchall(
+ "SELECT * FROM events.events ORDER BY time DESC",
+ model=Event,
+ )
+
+
async def delete_event(event_id: str) -> None:
await db.execute("DELETE FROM events.events WHERE id = :id", {"id": event_id})
async def get_event_tickets(event_id: str) -> list[Ticket]:
- return await db.fetchall(
+ rows = await db.fetchall(
"SELECT * FROM events.ticket WHERE event = :event",
{"event": event_id},
- Ticket,
)
+
+ tickets = []
+ for row in rows:
+ # Convert empty strings back to None for the model
+ ticket_data = dict(row)
+ if ticket_data.get("name") == "":
+ ticket_data["name"] = None
+ if ticket_data.get("email") == "":
+ ticket_data["email"] = None
+ tickets.append(Ticket(**ticket_data))
+
+ return tickets
diff --git a/migrations.py b/migrations.py
index 87a0dd4..9ed982b 100644
--- a/migrations.py
+++ b/migrations.py
@@ -160,3 +160,34 @@ async def m005_add_image_banner(db):
Add a column to allow an image banner for the event
"""
await db.execute("ALTER TABLE events.events ADD COLUMN banner TEXT;")
+
+
+async def m006_add_user_id_support(db):
+ """
+ Add user_id column to tickets table to support LNbits user-id as identifier
+ Make name and email optional when user_id is provided
+ """
+ await db.execute("ALTER TABLE events.ticket ADD COLUMN user_id TEXT;")
+
+ # Since SQLite doesn't support changing column constraints directly,
+ # we'll work around this by allowing the application logic to handle
+ # the validation that either (name AND email) OR user_id is provided
+ # The database will continue to expect name and email as NOT NULL
+ # but we'll insert empty strings for user_id tickets
+
+async def m007_add_extra_fields(db):
+ """
+ Add a canceled and 'extra' column to events and ticket tables
+ to support promo codes and ticket metadata.
+ """
+ # Add canceled and 'extra' columns to events table
+ # SQLite requires separate ALTER TABLE statements for each column
+ await db.execute(
+ "ALTER TABLE events.events ADD COLUMN canceled BOOLEAN NOT NULL DEFAULT FALSE;"
+ )
+ await db.execute(
+ "ALTER TABLE events.events ADD COLUMN extra TEXT;"
+ )
+
+ # Add 'extra' column to ticket table
+ await db.execute("ALTER TABLE events.ticket ADD COLUMN extra TEXT;")
diff --git a/models.py b/models.py
index f0a52b2..b05a5da 100644
--- a/models.py
+++ b/models.py
@@ -1,7 +1,30 @@
from datetime import datetime
+from typing import Optional
from fastapi import Query
-from pydantic import BaseModel, EmailStr
+from pydantic import BaseModel, EmailStr, Field, root_validator, validator
+
+
+class PromoCode(BaseModel):
+ code: str
+ discount_percent: float = 0.0
+ active: bool = True
+
+ # make the promo code uppercase
+ @validator("code")
+ def uppercase_code(cls, v):
+ return v.upper()
+
+ @validator("discount_percent")
+ def validate_discount_percent(cls, v):
+ assert 0 <= v <= 100, "Discount must be between 0 and 100."
+ return v
+
+
+class EventExtra(BaseModel):
+ promo_codes: list[PromoCode] = Field(default_factory=list)
+ conditional: bool = False
+ min_tickets: int = 1
class CreateEvent(BaseModel):
@@ -14,12 +37,29 @@ class CreateEvent(BaseModel):
currency: str = "sat"
amount_tickets: int = Query(..., ge=0)
price_per_ticket: float = Query(..., ge=0)
- banner: str | None = None
+ banner: Optional[str] = None
+ extra: EventExtra = Field(default_factory=EventExtra)
class CreateTicket(BaseModel):
- name: str
- email: EmailStr
+ name: Optional[str] = None
+ email: Optional[EmailStr] = None
+ user_id: Optional[str] = None
+ promo_code: Optional[str] = None
+ refund_address: Optional[str] = None
+
+ @root_validator
+ def validate_identifiers(cls, values):
+ # Ensure either (name AND email) OR user_id is provided
+ name = values.get('name')
+ email = values.get('email')
+ user_id = values.get('user_id')
+
+ if not user_id and not (name and email):
+ raise ValueError("Either user_id or both name and email must be provided")
+ if user_id and (name or email):
+ raise ValueError("Cannot provide both user_id and name/email")
+ return values
class Event(BaseModel):
@@ -28,6 +68,7 @@ class Event(BaseModel):
name: str
info: str
closing_date: str
+ canceled: bool = False
event_start_date: str
event_end_date: str
currency: str
@@ -36,15 +77,25 @@ class Event(BaseModel):
time: datetime
sold: int = 0
banner: str | None = None
+ extra: EventExtra = Field(default_factory=EventExtra)
+
+
+class TicketExtra(BaseModel):
+ applied_promo_code: str | None = None
+ sats_paid: int | None = None
+ refund_address: str | None = None
+ refunded: bool = False
class Ticket(BaseModel):
id: str
wallet: str
event: str
- name: str
- email: str
+ name: Optional[str] = None
+ email: Optional[str] = None
+ user_id: Optional[str] = None
registered: bool
paid: bool
time: datetime
reg_timestamp: datetime
+ extra: TicketExtra = Field(default_factory=TicketExtra)
diff --git a/services.py b/services.py
index 1286534..9099ef0 100644
--- a/services.py
+++ b/services.py
@@ -1,4 +1,13 @@
-from .crud import get_event, update_event, update_ticket
+from lnurl import execute
+from loguru import logger
+
+from .crud import (
+ get_event,
+ get_event_tickets,
+ purge_unpaid_tickets,
+ update_event,
+ update_ticket,
+)
from .models import Ticket
@@ -16,3 +25,30 @@ async def set_ticket_paid(ticket: Ticket) -> Ticket:
await update_event(event)
return ticket
+
+
+async def refund_tickets(event_id: str):
+ """
+ Refund tickets for an event that has not met the minimum ticket requirement.
+ This function should be called when the event is closed and the minimum ticket
+ condition is not met.
+ """
+ await purge_unpaid_tickets(event_id)
+ tickets = await get_event_tickets(event_id)
+
+ if not tickets:
+ return
+
+ for ticket in tickets:
+ if ticket.extra.refunded:
+ continue
+ if ticket.paid and ticket.extra.refund_address and ticket.extra.sats_paid:
+ try:
+ res = await execute(
+ ticket.extra.refund_address, str(ticket.extra.sats_paid)
+ )
+ if res:
+ ticket.extra.refunded = True
+ await update_ticket(ticket)
+ except Exception as e:
+ logger.error(f"Error refunding ticket {ticket.id}: {e}")
diff --git a/static/js/display.js b/static/js/display.js
index 4884751..6098e5a 100644
--- a/static/js/display.js
+++ b/static/js/display.js
@@ -9,7 +9,8 @@ window.app = Vue.createApp({
show: false,
data: {
name: '',
- email: ''
+ email: '',
+ refund: ''
}
},
ticketLink: {
@@ -29,7 +30,8 @@ window.app = Vue.createApp({
this.info = event_info
this.info = this.info.substring(1, this.info.length - 1)
this.banner = event_banner
- await this.purgeUnpaidTickets()
+ this.extra = event_extra
+ this.hasPromoCodes = has_promoCodes
},
computed: {
formatDescription() {
@@ -41,6 +43,7 @@ window.app = Vue.createApp({
e.preventDefault()
this.formDialog.data.name = ''
this.formDialog.data.email = ''
+ this.formDialog.data.refund = ''
},
closeReceiveDialog() {
@@ -60,12 +63,12 @@ window.app = Vue.createApp({
const regex = /^[\w\.-]+@[a-zA-Z\d\.-]+\.[a-zA-Z]{2,}$/
return regex.test(val) || 'Please enter valid email.'
},
-
Invoice() {
axios
.post(`/events/api/v1/tickets/${event_id}`, {
name: this.formDialog.data.name,
- email: this.formDialog.data.email
+ email: this.formDialog.data.email,
+ promo_code: this.formDialog.data.promo_code || null
})
.then(response => {
this.paymentReq = response.data.payment_request
@@ -122,13 +125,6 @@ window.app = Vue.createApp({
}, 2000)
})
.catch(LNbits.utils.notifyApiError)
- },
- async purgeUnpaidTickets() {
- try {
- await LNbits.api.request('GET', `/events/api/v1/purge/${event_id}`)
- } catch (error) {
- LNbits.utils.notifyApiError(error)
- }
}
}
})
diff --git a/static/js/index.js b/static/js/index.js
index cccbe82..d26133c 100644
--- a/static/js/index.js
+++ b/static/js/index.js
@@ -1,9 +1,6 @@
const mapEvents = function (obj) {
- obj.date = Quasar.date.formatDate(
- new Date(obj.time * 1000),
- 'YYYY-MM-DD HH:mm'
- )
- obj.fsat = new Intl.NumberFormat(LOCALE).format(obj.price_per_ticket)
+ obj.date = LNbits.utils.formatTimestamp(obj.time)
+ obj.fsat = new Intl.NumberFormat(window.g.locale).format(obj.price_per_ticket)
obj.displayUrl = ['/events/', obj.id].join('')
return obj
}
@@ -20,8 +17,6 @@ window.app = Vue.createApp({
columns: [
{name: 'id', align: 'left', label: 'ID', field: 'id'},
{name: 'name', align: 'left', label: 'Name', field: 'name'},
- {name: 'info', align: 'left', label: 'Info', field: 'info'},
- {name: 'banner', align: 'left', label: 'Banner', field: 'banner'},
{
name: 'event_start_date',
align: 'left',
@@ -40,6 +35,17 @@ window.app = Vue.createApp({
label: 'Ticket close',
field: 'closing_date'
},
+ {
+ name: 'canceled',
+ align: 'left',
+ label: 'Canceled',
+ field: row => {
+ if (row.extra.conditional && row.canceled) {
+ return 'Yes'
+ }
+ return 'No'
+ }
+ },
{
name: 'price_per_ticket',
align: 'left',
@@ -65,7 +71,9 @@ window.app = Vue.createApp({
align: 'left',
label: 'Sold',
field: 'sold'
- }
+ },
+ {name: 'info', align: 'left', label: 'Info', field: 'info'},
+ {name: 'banner', align: 'left', label: 'Banner', field: 'banner'}
],
pagination: {
rowsPerPage: 10
@@ -73,7 +81,6 @@ window.app = Vue.createApp({
},
ticketsTable: {
columns: [
- {name: 'id', align: 'left', label: 'ID', field: 'id'},
{name: 'event', align: 'left', label: 'Event', field: 'event'},
{name: 'name', align: 'left', label: 'Name', field: 'name'},
{name: 'email', align: 'left', label: 'Email', field: 'email'},
@@ -82,7 +89,14 @@ window.app = Vue.createApp({
align: 'left',
label: 'Registered',
field: 'registered'
- }
+ },
+ {
+ name: 'promo_code',
+ align: 'left',
+ label: 'Promo Code',
+ field: row => row.extra.applied_promo_code || ''
+ },
+ {name: 'id', align: 'left', label: 'ID', field: 'id'}
],
pagination: {
rowsPerPage: 10
@@ -90,7 +104,11 @@ window.app = Vue.createApp({
},
formDialog: {
show: false,
- data: {}
+ data: {
+ extra: {
+ promo_codes: []
+ }
+ }
}
}
},
@@ -143,9 +161,10 @@ window.app = Vue.createApp({
this.g.user.wallets[0].inkey
)
.then(response => {
- this.events = response.data.map(function (obj) {
+ this.events = response.data.map(obj => {
return mapEvents(obj)
})
+ this.checkCanceledEvents()
})
},
sendEventData() {
@@ -153,6 +172,11 @@ window.app = Vue.createApp({
id: this.formDialog.data.wallet
})
const data = this.formDialog.data
+ if (data.extra && !data.extra.promo_codes) {
+ data.extra.promo_codes = data.extra.promo_codes
+ .filter(code => code.trim() !== '')
+ .map(code => code.trim().toUpperCase())
+ }
if (data.id) {
this.updateEvent(wallet, data)
@@ -161,20 +185,41 @@ window.app = Vue.createApp({
}
},
+ openEventDialog(data = false) {
+ if (data && data.id) {
+ this.formDialog.data = {...data}
+ } else {
+ this.formDialog.data = {
+ extra: {
+ conditional: false,
+ min_tickets: 1,
+ promo_codes: []
+ }
+ }
+ }
+ this.formDialog.show = true
+ },
+ resetEventDialog() {
+ this.formDialog.show = false
+ this.formDialog.data = {
+ extra: {
+ promo_codes: []
+ }
+ }
+ },
+
createEvent(wallet, data) {
LNbits.api
.request('POST', '/events/api/v1/events', wallet.adminkey, data)
.then(response => {
this.events.push(mapEvents(response.data))
- this.formDialog.show = false
- this.formDialog.data = {}
+ this.resetEventDialog()
})
.catch(LNbits.utils.notifyApiError)
},
updateformDialog(formId) {
const link = _.findWhere(this.events, {id: formId})
- this.formDialog.data = {...link}
- this.formDialog.show = true
+ this.openEventDialog(link)
},
updateEvent(wallet, data) {
LNbits.api
@@ -189,8 +234,7 @@ window.app = Vue.createApp({
return obj.id == data.id
})
this.events.push(mapEvents(response.data))
- this.formDialog.show = false
- this.formDialog.data = {}
+ this.resetEventDialog()
})
.catch(LNbits.utils.notifyApiError)
},
@@ -216,6 +260,30 @@ window.app = Vue.createApp({
},
exporteventsCSV() {
LNbits.utils.exportCSV(this.eventsTable.columns, this.events)
+ },
+ async checkCanceledEvents() {
+ const events = this.events
+ .filter(event => event.extra.conditional)
+ .filter(e => !e.canceled)
+ if (!events.length) return
+ const now = new Date()
+ events.forEach(async ev => {
+ if (new Date(ev.closing_date) < now && ev.sold < ev.extra.min_tickets) {
+ const {data} = await LNbits.api.request(
+ 'PUT',
+ '/events/api/v1/events/' + ev.id + '/cancel',
+ _.findWhere(this.g.user.wallets, {id: ev.wallet}).adminkey
+ )
+ Quasar.Notify.create({
+ type: 'warning',
+ message: `Event ${ev.name} has been canceled and refunds have been issued.`,
+ icon: null
+ })
+ this.events = this.events.map(e =>
+ e.id === ev.id ? mapEvents(data) : e
+ )
+ }
+ })
}
},
async created() {
diff --git a/tasks.py b/tasks.py
index f7300bb..67d5d45 100644
--- a/tasks.py
+++ b/tasks.py
@@ -21,8 +21,12 @@ async def on_invoice_paid(payment: Payment) -> None:
if not payment.extra or "events" != payment.extra.get("tag"):
return
- if not payment.extra.get("name") or not payment.extra.get("email"):
- logger.warning(f"Ticket {payment.payment_hash} missing name or email.")
+ # Check if ticket has either name/email or user_id
+ has_name_email = payment.extra.get("name") and payment.extra.get("email")
+ has_user_id = payment.extra.get("user_id")
+
+ if not has_name_email and not has_user_id:
+ logger.warning(f"Ticket {payment.payment_hash} missing name/email or user_id.")
return
ticket = await get_ticket(payment.payment_hash)
diff --git a/templates/events/display.html b/templates/events/display.html
index 24a64e4..73d279d 100644
--- a/templates/events/display.html
+++ b/templates/events/display.html
@@ -6,7 +6,7 @@
{{ event_name }}
-
+