Created a listener for wix-form to do push actions with but unsure how to best handle it

This commit is contained in:
Jonas Linter
2025-10-01 16:32:15 +02:00
parent ea9b6c72e4
commit 36c32c44d8
4 changed files with 110 additions and 8 deletions

View File

@@ -613,18 +613,35 @@ class NotifReportReadAction(AlpineBitsAction):
await dbsession.commit()
return AlpineBitsResponse(
response_xml, HttpStatusCode.OK
)
class PushAction(AlpineBitsAction):
"""Creates the necessary xml for OTA_HotelResNotif:GuestRequests"""
def __init__(self, config: Dict = {}):
self.name = AlpineBitsActionName.OTA_HOTEL_RES_NOTIF_GUEST_REQUESTS
self.version = [Version.V2024_10, Version.V2022_10]
self.config = config
async def handle(
self,
action: str,
request_xml: str,
version: Version,
client_info: AlpineBitsClientInfo,
dbsession=None,
server_capabilities=None,
) -> AlpineBitsResponse:
"""Create push request XML."""
pass
class AlpineBitsServer:
"""

View File

@@ -36,6 +36,8 @@ import xml.etree.ElementTree as ET
from .alpinebits_server import AlpineBitsClientInfo, AlpineBitsServer, Version
import urllib.parse
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
from functools import partial
import httpx
from .db import (
Base,
@@ -52,9 +54,46 @@ _LOGGER = logging.getLogger(__name__)
# HTTP Basic auth for AlpineBits
security_basic = HTTPBasic()
from collections import defaultdict
# --- Simple event dispatcher ---
class EventDispatcher:
def __init__(self):
self.listeners = defaultdict(list)
def register(self, event_name, func):
self.listeners[event_name].append(func)
async def dispatch(self, event_name, *args, **kwargs):
for func in self.listeners[event_name]:
await func(*args, **kwargs)
event_dispatcher = EventDispatcher()
# Load config at startup
async def push_listener(customer, reservation, hotel, push):
server: AlpineBitsServer = app.state.alpine_bits_server
hotel_id = hotel['hotel_id']
headers = {"Authorization": f"Bearer {push.get('token','')}"} if push.get('token') else {}
try:
async with httpx.AsyncClient() as client:
resp = await client.post(push["url"], json=payload, headers=headers, timeout=10)
_LOGGER.info(f"Push event fired to {push['url']} for hotel {hotel['hotel_id']}, status: {resp.status_code}")
except Exception as e:
_LOGGER.error(f"Push event failed for hotel {hotel['hotel_id']}: {e}")
@asynccontextmanager
async def lifespan(app: FastAPI):
# Setup DB
@@ -68,10 +107,19 @@ async def lifespan(app: FastAPI):
DATABASE_URL = get_database_url(config)
engine = create_async_engine(DATABASE_URL, echo=True)
AsyncSessionLocal = async_sessionmaker(engine, expire_on_commit=False)
app.state.engine = engine
app.state.async_sessionmaker = AsyncSessionLocal
app.state.config = config
app.state.alpine_bits_server = AlpineBitsServer(config)
app.state.event_dispatcher = event_dispatcher
# Register push listeners for hotels with push_endpoint
for hotel in config.get("alpine_bits_auth", []):
push = hotel.get("push_endpoint")
if push:
event_dispatcher.register("form_processed", partial(push_listener, hotel=hotel, push=push))
# Create tables
async with engine.begin() as conn:
@@ -341,6 +389,12 @@ async def process_wix_form_submission(request: Request, data: Dict[str, Any], db
db.add(db_reservation)
await db.commit()
await db.refresh(db_reservation)
# Fire event for listeners (push, etc.)
dispatcher = getattr(request.app.state, "event_dispatcher", None)
if dispatcher:
await dispatcher.dispatch("form_processed", db_customer, db_reservation)
return {
"status": "success",