Alembic replaces create_all as the schema authority: async env.py against Base.metadata (CLI and in-app entry paths share it via config.attributes["connection"]), an autogenerated baseline of the create_all-era schema, and init_db now runs upgrade head — stamping the baseline first on a pre-Alembic database so existing deployments adopt cleanly. create_all remains for tests only. Calls are durable from the start: CallManager gains an on_call_created hook (wired to persist_call_on_create) that inserts an in_progress CallRecord the moment a call is created; persist_call_on_end finalizes that same row. A SIGKILL mid-call now leaves an in_progress row instead of erasing the call from history (verified live against the dev database). One transcript representation: ActiveCall.transcript_chunks holds TranscriptEntry (t_offset_ms, speaker, text) — add_transcript stamps real offsets from connect time, receptionist passes speaker instead of encoding it into "caller: ..." strings, persisted chunks carry real seek offsets, and the dead CallRecord.transcript Text column is dropped by migration. Device.is_online migrates String → Boolean (with a USING cast for existing rows). Model de-triplication: CallResponse/CallStatusResponse build via from_call classmethods (one ActiveCall→response mapping); DeviceStatus deleted — can_receive_call is a computed field on Device and the list endpoint returns the domain model; all row↔dict and row↔domain mapping now lives in call_persistence.py (record_summary/record_detail/chunk_to_dict + device row functions). New tests/test_data_layer.py: upgrade-head-matches-models, pre-Alembic adoption, durable in_progress rows, end-without-create fallback, transcript offsets, consolidated response models. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
159 lines
4.6 KiB
Python
159 lines
4.6 KiB
Python
"""
|
|
Call Management API — Place calls, check status, transfer, hold-slay.
|
|
"""
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException
|
|
|
|
from api.deps import get_gateway
|
|
from core.gateway import AIPSTNGateway
|
|
from models.call import (
|
|
CallMode,
|
|
CallRequest,
|
|
CallResponse,
|
|
CallStatusResponse,
|
|
HoldSlayerRequest,
|
|
TransferRequest,
|
|
)
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
@router.post("/outbound", response_model=CallResponse)
|
|
async def make_call(
|
|
request: CallRequest,
|
|
gateway: AIPSTNGateway = Depends(get_gateway),
|
|
):
|
|
"""
|
|
Place an outbound call.
|
|
|
|
Modes:
|
|
- **direct**: Call and connect to your device immediately
|
|
- **hold_slayer**: Navigate IVR, wait on hold, transfer when human detected
|
|
- **ai_assisted**: Connect with noise cancel, transcription, recording
|
|
"""
|
|
try:
|
|
call = await gateway.make_call(
|
|
number=request.number,
|
|
mode=request.mode,
|
|
intent=request.intent,
|
|
device=request.device,
|
|
call_flow_id=request.call_flow_id,
|
|
services=request.services,
|
|
)
|
|
return CallResponse.from_call(call)
|
|
except ValueError as e:
|
|
raise HTTPException(status_code=400, detail=str(e))
|
|
except Exception as e:
|
|
raise HTTPException(status_code=500, detail=str(e))
|
|
|
|
|
|
@router.post("/hold-slayer", response_model=CallResponse)
|
|
async def hold_slayer(
|
|
request: HoldSlayerRequest,
|
|
gateway: AIPSTNGateway = Depends(get_gateway),
|
|
):
|
|
"""
|
|
🗡️ The Hold Slayer endpoint.
|
|
|
|
Give it a number and intent, it calls, navigates the IVR,
|
|
waits on hold, and rings you when a human picks up.
|
|
|
|
Example:
|
|
POST /api/calls/hold-slayer
|
|
{
|
|
"number": "+18005551234",
|
|
"intent": "cancel my credit card",
|
|
"call_flow_id": "chase_bank_main",
|
|
"transfer_to": "sip_phone",
|
|
"notify": ["sms", "push"]
|
|
}
|
|
"""
|
|
try:
|
|
call = await gateway.make_call(
|
|
number=request.number,
|
|
mode=CallMode.HOLD_SLAYER,
|
|
intent=request.intent,
|
|
call_flow_id=request.call_flow_id,
|
|
device=request.transfer_to,
|
|
)
|
|
return CallResponse.from_call(
|
|
call,
|
|
message="Hold Slayer activated. I'll ring you when a human picks up. ☕",
|
|
)
|
|
except ValueError as e:
|
|
raise HTTPException(status_code=400, detail=str(e))
|
|
except Exception as e:
|
|
raise HTTPException(status_code=500, detail=str(e))
|
|
|
|
|
|
@router.get("/active")
|
|
async def list_active_calls(
|
|
gateway: AIPSTNGateway = Depends(get_gateway),
|
|
):
|
|
"""List all active calls with their current status."""
|
|
calls = gateway.call_manager.active_calls
|
|
return [call.summary() for call in calls.values()]
|
|
|
|
|
|
@router.get("/{call_id}", response_model=CallStatusResponse)
|
|
async def get_call(
|
|
call_id: str,
|
|
gateway: AIPSTNGateway = Depends(get_gateway),
|
|
):
|
|
"""Get current call status, transcript so far, classification history."""
|
|
call = gateway.get_call(call_id)
|
|
if not call:
|
|
raise HTTPException(status_code=404, detail=f"Call {call_id} not found")
|
|
|
|
return CallStatusResponse.from_call(call)
|
|
|
|
|
|
@router.post("/{call_id}/transfer")
|
|
async def transfer_call(
|
|
call_id: str,
|
|
request: TransferRequest,
|
|
gateway: AIPSTNGateway = Depends(get_gateway),
|
|
):
|
|
"""Transfer an active call to a device."""
|
|
try:
|
|
await gateway.transfer_call(call_id, request.device)
|
|
return {"status": "transferred", "target": request.device}
|
|
except ValueError as e:
|
|
raise HTTPException(status_code=404, detail=str(e))
|
|
except Exception as e:
|
|
raise HTTPException(status_code=500, detail=str(e))
|
|
|
|
|
|
@router.post("/{call_id}/hangup")
|
|
async def hangup_call(
|
|
call_id: str,
|
|
gateway: AIPSTNGateway = Depends(get_gateway),
|
|
):
|
|
"""Hang up a call."""
|
|
try:
|
|
await gateway.hangup_call(call_id)
|
|
return {"status": "hung_up", "call_id": call_id}
|
|
except ValueError as e:
|
|
raise HTTPException(status_code=404, detail=str(e))
|
|
except Exception as e:
|
|
raise HTTPException(status_code=500, detail=str(e))
|
|
|
|
|
|
@router.post("/{call_id}/dtmf")
|
|
async def send_dtmf(
|
|
call_id: str,
|
|
digits: str,
|
|
gateway: AIPSTNGateway = Depends(get_gateway),
|
|
):
|
|
"""Send DTMF tones on an active call."""
|
|
call = gateway.get_call(call_id)
|
|
if not call:
|
|
raise HTTPException(status_code=404, detail=f"Call {call_id} not found")
|
|
|
|
legs = gateway.call_manager.legs_for_call(call_id)
|
|
if not legs:
|
|
raise HTTPException(status_code=409, detail="No active SIP leg found for this call")
|
|
|
|
await gateway.sip_engine.send_dtmf(legs[0], digits)
|
|
return {"status": "sent", "digits": digits}
|