GitHub Actions commited on
Commit ·
78d1678
1
Parent(s): fffaeb4
Deploy from GitHub main
Browse files- .env.example +2 -1
- app/ai/tool_schemas.py +35 -0
- app/api/routes.py +28 -1
- app/config.py +53 -2
- app/database/supabase.py +107 -7
- app/services/container.py +2 -1
- app/services/conversation_service.py +15 -7
- app/services/group_message_service.py +9 -8
- app/tools/handlers.py +55 -0
- app/whatsapp/outbox.py +180 -43
- prompts/falzh_info.md +4 -0
- prompts/system.md +3 -0
- prompts/system_driver.md +1 -1
- prompts/system_new_user.md +1 -1
- supabase/migrations/202610150001_tiered_whatsapp_outbox.sql +16 -0
- supabase/migrations/202610170001_group_invite_submissions.sql +24 -0
- supabase/migrations/public_schema.sql +41 -1
- tests/conftest.py +20 -0
- tests/test_tool_schemas.py +2 -1
.env.example
CHANGED
|
@@ -28,6 +28,7 @@ WHATSAPP_VERIFY_TOKEN=choose-a-webhook-verify-token
|
|
| 28 |
WHATSAPP_APP_SECRET=your-meta-app-secret
|
| 29 |
WHATSAPP_ACCESS_TOKEN=your-whatsapp-cloud-api-token
|
| 30 |
WHATSAPP_PHONE_NUMBER_ID=your-phone-number-id
|
| 31 |
-
|
|
|
|
| 32 |
|
| 33 |
ADMIN_API_KEY=choose-a-long-random-admin-key
|
|
|
|
| 28 |
WHATSAPP_APP_SECRET=your-meta-app-secret
|
| 29 |
WHATSAPP_ACCESS_TOKEN=your-whatsapp-cloud-api-token
|
| 30 |
WHATSAPP_PHONE_NUMBER_ID=your-phone-number-id
|
| 31 |
+
WHATSAPP_BRIDGE_SECRET=choose-a-separate-random-bridge-secret
|
| 32 |
+
WHATSAPP_OUTBOX_LEVELS='[{"max_age_seconds":120,"retry_interval_seconds":10,"order":"oldest"},{"max_age_seconds":36000,"retry_interval_seconds":60,"order":"newest"},{"max_age_seconds":null,"retry_interval_seconds":null,"order":"discard"}]'
|
| 33 |
|
| 34 |
ADMIN_API_KEY=choose-a-long-random-admin-key
|
app/ai/tool_schemas.py
CHANGED
|
@@ -29,6 +29,37 @@ _ABOUT_FALZH = {
|
|
| 29 |
},
|
| 30 |
}
|
| 31 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
_SEARCH_TRIPS = {
|
| 33 |
"type": "function",
|
| 34 |
"function": {
|
|
@@ -357,6 +388,7 @@ _SWITCH_TO_PASSENGER = {
|
|
| 357 |
|
| 358 |
_TOOL_SCHEMAS: dict[str, dict[str, Any]] = {
|
| 359 |
"about_falzh": _ABOUT_FALZH,
|
|
|
|
| 360 |
"search_trips": _SEARCH_TRIPS,
|
| 361 |
"select_trip": _SELECT_TRIP,
|
| 362 |
"create_driver_account": _CREATE_DRIVER_ACCOUNT,
|
|
@@ -373,12 +405,14 @@ _TOOL_SCHEMAS: dict[str, dict[str, Any]] = {
|
|
| 373 |
_TOOLS_BY_MODE: dict[UserMode, list[str]] = {
|
| 374 |
"new_user": [
|
| 375 |
"about_falzh",
|
|
|
|
| 376 |
"create_driver_account",
|
| 377 |
"switch_to_driver",
|
| 378 |
"switch_to_passenger",
|
| 379 |
],
|
| 380 |
"driver": [
|
| 381 |
"about_falzh",
|
|
|
|
| 382 |
"check_driver_info",
|
| 383 |
"check_driver_trips",
|
| 384 |
"add_driver_car",
|
|
@@ -389,6 +423,7 @@ _TOOLS_BY_MODE: dict[UserMode, list[str]] = {
|
|
| 389 |
],
|
| 390 |
"passenger": [
|
| 391 |
"about_falzh",
|
|
|
|
| 392 |
"search_trips",
|
| 393 |
"select_trip",
|
| 394 |
"create_driver_account",
|
|
|
|
| 29 |
},
|
| 30 |
}
|
| 31 |
|
| 32 |
+
_SUBMIT_GROUP_INVITE = {
|
| 33 |
+
"type": "function",
|
| 34 |
+
"function": {
|
| 35 |
+
"name": "submit_group_invite",
|
| 36 |
+
"description": (
|
| 37 |
+
"Store a WhatsApp transportation-group invitation for manual review. Use only "
|
| 38 |
+
"when the sender explicitly asks FALZH to review or join the group and provides "
|
| 39 |
+
"its invite link. Merely sharing a link is not enough; ignore incidental links, "
|
| 40 |
+
"unrelated URLs, and links inside trip advertisements."
|
| 41 |
+
),
|
| 42 |
+
"parameters": {
|
| 43 |
+
"type": "object",
|
| 44 |
+
"properties": {
|
| 45 |
+
"invite_link": {
|
| 46 |
+
"type": "string",
|
| 47 |
+
"description": "The exact WhatsApp group invitation URL shared by the sender.",
|
| 48 |
+
},
|
| 49 |
+
"description": {
|
| 50 |
+
"type": "string",
|
| 51 |
+
"description": (
|
| 52 |
+
"Brief description based only on what the sender says about the group; "
|
| 53 |
+
"use an empty string if they provide no description."
|
| 54 |
+
),
|
| 55 |
+
},
|
| 56 |
+
},
|
| 57 |
+
"required": ["invite_link", "description"],
|
| 58 |
+
"additionalProperties": False,
|
| 59 |
+
},
|
| 60 |
+
},
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
_SEARCH_TRIPS = {
|
| 64 |
"type": "function",
|
| 65 |
"function": {
|
|
|
|
| 388 |
|
| 389 |
_TOOL_SCHEMAS: dict[str, dict[str, Any]] = {
|
| 390 |
"about_falzh": _ABOUT_FALZH,
|
| 391 |
+
"submit_group_invite": _SUBMIT_GROUP_INVITE,
|
| 392 |
"search_trips": _SEARCH_TRIPS,
|
| 393 |
"select_trip": _SELECT_TRIP,
|
| 394 |
"create_driver_account": _CREATE_DRIVER_ACCOUNT,
|
|
|
|
| 405 |
_TOOLS_BY_MODE: dict[UserMode, list[str]] = {
|
| 406 |
"new_user": [
|
| 407 |
"about_falzh",
|
| 408 |
+
"submit_group_invite",
|
| 409 |
"create_driver_account",
|
| 410 |
"switch_to_driver",
|
| 411 |
"switch_to_passenger",
|
| 412 |
],
|
| 413 |
"driver": [
|
| 414 |
"about_falzh",
|
| 415 |
+
"submit_group_invite",
|
| 416 |
"check_driver_info",
|
| 417 |
"check_driver_trips",
|
| 418 |
"add_driver_car",
|
|
|
|
| 423 |
],
|
| 424 |
"passenger": [
|
| 425 |
"about_falzh",
|
| 426 |
+
"submit_group_invite",
|
| 427 |
"search_trips",
|
| 428 |
"select_trip",
|
| 429 |
"create_driver_account",
|
app/api/routes.py
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
|
|
|
|
|
| 1 |
from typing import Annotated, Any
|
| 2 |
|
| 3 |
from fastapi import (
|
| 4 |
APIRouter,
|
| 5 |
BackgroundTasks,
|
| 6 |
Depends,
|
|
|
|
| 7 |
HTTPException,
|
| 8 |
Query,
|
| 9 |
Request,
|
|
@@ -28,7 +31,6 @@ from app.services.container import ServiceContainer
|
|
| 28 |
from app.whatsapp.parser import parse_inbound_messages
|
| 29 |
from app.whatsapp.security import verify_meta_signature, verify_webhook_challenge
|
| 30 |
from app.ai.tool_schemas import get_all_tool_schemas
|
| 31 |
-
import json
|
| 32 |
|
| 33 |
router = APIRouter()
|
| 34 |
|
|
@@ -88,6 +90,31 @@ async def receive_whatsapp_webhook(
|
|
| 88 |
return WebhookAcceptedResponse(messages=len(messages))
|
| 89 |
|
| 90 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
@router.post(
|
| 92 |
"/webhooks/whatsapp/debug",
|
| 93 |
response_model=WebhookDebugResponse,
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import secrets
|
| 3 |
from typing import Annotated, Any
|
| 4 |
|
| 5 |
from fastapi import (
|
| 6 |
APIRouter,
|
| 7 |
BackgroundTasks,
|
| 8 |
Depends,
|
| 9 |
+
Header,
|
| 10 |
HTTPException,
|
| 11 |
Query,
|
| 12 |
Request,
|
|
|
|
| 31 |
from app.whatsapp.parser import parse_inbound_messages
|
| 32 |
from app.whatsapp.security import verify_meta_signature, verify_webhook_challenge
|
| 33 |
from app.ai.tool_schemas import get_all_tool_schemas
|
|
|
|
| 34 |
|
| 35 |
router = APIRouter()
|
| 36 |
|
|
|
|
| 90 |
return WebhookAcceptedResponse(messages=len(messages))
|
| 91 |
|
| 92 |
|
| 93 |
+
@router.post("/internal/whatsapp/connected", status_code=status.HTTP_202_ACCEPTED)
|
| 94 |
+
async def whatsapp_bridge_connected(
|
| 95 |
+
background_tasks: BackgroundTasks,
|
| 96 |
+
container: Annotated[ServiceContainer, Depends(get_container)],
|
| 97 |
+
bridge_secret: Annotated[
|
| 98 |
+
str | None,
|
| 99 |
+
Header(alias="X-WhatsApp-Bridge-Secret"),
|
| 100 |
+
] = None,
|
| 101 |
+
) -> dict[str, str]:
|
| 102 |
+
expected_secret = container.settings.whatsapp_bridge_secret
|
| 103 |
+
if expected_secret is None:
|
| 104 |
+
raise HTTPException(
|
| 105 |
+
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
| 106 |
+
detail="WhatsApp bridge notification is not configured",
|
| 107 |
+
)
|
| 108 |
+
if not bridge_secret or not secrets.compare_digest(bridge_secret, expected_secret):
|
| 109 |
+
raise HTTPException(
|
| 110 |
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 111 |
+
detail="Invalid WhatsApp bridge secret",
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
background_tasks.add_task(container.whatsapp.on_connection_restored)
|
| 115 |
+
return {"status": "accepted", "message": "Outbox delivery started"}
|
| 116 |
+
|
| 117 |
+
|
| 118 |
@router.post(
|
| 119 |
"/webhooks/whatsapp/debug",
|
| 120 |
response_model=WebhookDebugResponse,
|
app/config.py
CHANGED
|
@@ -1,13 +1,20 @@
|
|
| 1 |
from functools import lru_cache
|
| 2 |
from pathlib import Path
|
|
|
|
| 3 |
|
| 4 |
-
from pydantic import Field, HttpUrl
|
| 5 |
from pydantic_settings import BaseSettings, SettingsConfigDict
|
| 6 |
|
| 7 |
|
| 8 |
BASE_DIR = Path(__file__).resolve().parent.parent
|
| 9 |
|
| 10 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
class Settings(BaseSettings):
|
| 12 |
model_config = SettingsConfigDict(
|
| 13 |
env_file=BASE_DIR / ".env",
|
|
@@ -48,12 +55,56 @@ class Settings(BaseSettings):
|
|
| 48 |
whatsapp_app_secret: str = Field(min_length=1)
|
| 49 |
whatsapp_access_token: str = Field(min_length=1)
|
| 50 |
whatsapp_phone_number_id: str = Field(min_length=1)
|
| 51 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
|
| 53 |
admin_api_key: str = Field(min_length=1)
|
| 54 |
|
| 55 |
default_country_code: str = "967"
|
| 56 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
|
| 58 |
@lru_cache
|
| 59 |
def get_settings() -> Settings:
|
|
|
|
| 1 |
from functools import lru_cache
|
| 2 |
from pathlib import Path
|
| 3 |
+
from typing import Literal
|
| 4 |
|
| 5 |
+
from pydantic import BaseModel, Field, HttpUrl, model_validator
|
| 6 |
from pydantic_settings import BaseSettings, SettingsConfigDict
|
| 7 |
|
| 8 |
|
| 9 |
BASE_DIR = Path(__file__).resolve().parent.parent
|
| 10 |
|
| 11 |
|
| 12 |
+
class WhatsAppOutboxLevel(BaseModel):
|
| 13 |
+
max_age_seconds: int | None
|
| 14 |
+
retry_interval_seconds: int | None
|
| 15 |
+
order: Literal["oldest", "newest", "discard"]
|
| 16 |
+
|
| 17 |
+
|
| 18 |
class Settings(BaseSettings):
|
| 19 |
model_config = SettingsConfigDict(
|
| 20 |
env_file=BASE_DIR / ".env",
|
|
|
|
| 55 |
whatsapp_app_secret: str = Field(min_length=1)
|
| 56 |
whatsapp_access_token: str = Field(min_length=1)
|
| 57 |
whatsapp_phone_number_id: str = Field(min_length=1)
|
| 58 |
+
whatsapp_bridge_secret: str | None = Field(default=None, min_length=1)
|
| 59 |
+
whatsapp_outbox_levels: list[WhatsAppOutboxLevel] = Field(
|
| 60 |
+
default_factory=lambda: [
|
| 61 |
+
WhatsAppOutboxLevel(
|
| 62 |
+
max_age_seconds=120,
|
| 63 |
+
retry_interval_seconds=10,
|
| 64 |
+
order="oldest",
|
| 65 |
+
),
|
| 66 |
+
WhatsAppOutboxLevel(
|
| 67 |
+
max_age_seconds=36_000,
|
| 68 |
+
retry_interval_seconds=60,
|
| 69 |
+
order="newest",
|
| 70 |
+
),
|
| 71 |
+
WhatsAppOutboxLevel(
|
| 72 |
+
max_age_seconds=None,
|
| 73 |
+
retry_interval_seconds=None,
|
| 74 |
+
order="discard",
|
| 75 |
+
),
|
| 76 |
+
]
|
| 77 |
+
)
|
| 78 |
|
| 79 |
admin_api_key: str = Field(min_length=1)
|
| 80 |
|
| 81 |
default_country_code: str = "967"
|
| 82 |
|
| 83 |
+
@model_validator(mode="after")
|
| 84 |
+
def validate_whatsapp_outbox_levels(self) -> "Settings":
|
| 85 |
+
levels = self.whatsapp_outbox_levels
|
| 86 |
+
if len(levels) < 2:
|
| 87 |
+
raise ValueError("WhatsApp outbox needs at least one retry level and one discard level")
|
| 88 |
+
|
| 89 |
+
previous_max_age = 0
|
| 90 |
+
for level in levels[:-1]:
|
| 91 |
+
if level.max_age_seconds is None or level.max_age_seconds <= previous_max_age:
|
| 92 |
+
raise ValueError("Retry level age limits must be positive and strictly increasing")
|
| 93 |
+
if level.retry_interval_seconds is None or level.retry_interval_seconds <= 0:
|
| 94 |
+
raise ValueError("Retry levels need a positive retry interval")
|
| 95 |
+
if level.order == "discard":
|
| 96 |
+
raise ValueError("Only the final WhatsApp outbox level can discard messages")
|
| 97 |
+
previous_max_age = level.max_age_seconds
|
| 98 |
+
|
| 99 |
+
final_level = levels[-1]
|
| 100 |
+
if (
|
| 101 |
+
final_level.max_age_seconds is not None
|
| 102 |
+
or final_level.retry_interval_seconds is not None
|
| 103 |
+
or final_level.order != "discard"
|
| 104 |
+
):
|
| 105 |
+
raise ValueError("The final WhatsApp outbox level must be an unbounded discard level")
|
| 106 |
+
return self
|
| 107 |
+
|
| 108 |
|
| 109 |
@lru_cache
|
| 110 |
def get_settings() -> Settings:
|
app/database/supabase.py
CHANGED
|
@@ -55,19 +55,61 @@ class SupabaseRepository:
|
|
| 55 |
data = _response_data(response)
|
| 56 |
return data[0] if isinstance(data, list) else data
|
| 57 |
|
| 58 |
-
async def
|
| 59 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
self.client.table("whatsapp_outbox")
|
| 61 |
.select("*")
|
| 62 |
-
.
|
| 63 |
-
|
| 64 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
.limit(1)
|
| 66 |
.execute()
|
| 67 |
)
|
| 68 |
data = _response_data(response) or []
|
| 69 |
return data[0] if data else None
|
| 70 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
async def claim_whatsapp_message(
|
| 72 |
self,
|
| 73 |
message_id: str,
|
|
@@ -167,14 +209,13 @@ class SupabaseRepository:
|
|
| 167 |
message_id: str,
|
| 168 |
*,
|
| 169 |
error: str,
|
| 170 |
-
retryable: bool,
|
| 171 |
retry_at: datetime,
|
| 172 |
) -> None:
|
| 173 |
await (
|
| 174 |
self.client.table("whatsapp_outbox")
|
| 175 |
.update(
|
| 176 |
{
|
| 177 |
-
"status": "pending"
|
| 178 |
"next_attempt_at": retry_at.isoformat(),
|
| 179 |
"locked_at": None,
|
| 180 |
"last_error": error[:4000],
|
|
@@ -184,6 +225,42 @@ class SupabaseRepository:
|
|
| 184 |
.execute()
|
| 185 |
)
|
| 186 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 187 |
async def upsert_customer(
|
| 188 |
self,
|
| 189 |
*,
|
|
@@ -489,6 +566,29 @@ class SupabaseRepository:
|
|
| 489 |
data = _response_data(response)
|
| 490 |
return data[0] if isinstance(data, list) else data
|
| 491 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 492 |
async def get_recent_context_messages(
|
| 493 |
self,
|
| 494 |
*,
|
|
|
|
| 55 |
data = _response_data(response)
|
| 56 |
return data[0] if isinstance(data, list) else data
|
| 57 |
|
| 58 |
+
async def get_pending_whatsapp_message(
|
| 59 |
+
self,
|
| 60 |
+
*,
|
| 61 |
+
newer_than: datetime | None,
|
| 62 |
+
older_than: datetime | None,
|
| 63 |
+
newest_first: bool,
|
| 64 |
+
) -> dict[str, Any] | None:
|
| 65 |
+
query = (
|
| 66 |
self.client.table("whatsapp_outbox")
|
| 67 |
.select("*")
|
| 68 |
+
.eq("status", "pending")
|
| 69 |
+
)
|
| 70 |
+
if newer_than:
|
| 71 |
+
query = query.gte("created_at", newer_than.isoformat())
|
| 72 |
+
if older_than:
|
| 73 |
+
query = query.lt("created_at", older_than.isoformat())
|
| 74 |
+
response = await (
|
| 75 |
+
query.order("created_at", desc=newest_first)
|
| 76 |
+
.order("id", desc=newest_first)
|
| 77 |
.limit(1)
|
| 78 |
.execute()
|
| 79 |
)
|
| 80 |
data = _response_data(response) or []
|
| 81 |
return data[0] if data else None
|
| 82 |
|
| 83 |
+
async def has_sending_whatsapp_message(self) -> bool:
|
| 84 |
+
response = await (
|
| 85 |
+
self.client.table("whatsapp_outbox")
|
| 86 |
+
.select("id")
|
| 87 |
+
.eq("status", "sending")
|
| 88 |
+
.limit(1)
|
| 89 |
+
.execute()
|
| 90 |
+
)
|
| 91 |
+
return bool(_response_data(response))
|
| 92 |
+
|
| 93 |
+
async def discard_expired_whatsapp_messages(self, *, before: datetime) -> int:
|
| 94 |
+
now = datetime.now(UTC).isoformat()
|
| 95 |
+
response = await (
|
| 96 |
+
self.client.table("whatsapp_outbox")
|
| 97 |
+
.update(
|
| 98 |
+
{
|
| 99 |
+
"status": "discarded",
|
| 100 |
+
"discarded_at": now,
|
| 101 |
+
"discard_reason": "Message exceeded the configured maximum age",
|
| 102 |
+
"locked_at": None,
|
| 103 |
+
}
|
| 104 |
+
)
|
| 105 |
+
.eq("status", "pending")
|
| 106 |
+
.lt("created_at", before.isoformat())
|
| 107 |
+
.select("id")
|
| 108 |
+
.execute()
|
| 109 |
+
)
|
| 110 |
+
data = _response_data(response) or []
|
| 111 |
+
return len(data)
|
| 112 |
+
|
| 113 |
async def claim_whatsapp_message(
|
| 114 |
self,
|
| 115 |
message_id: str,
|
|
|
|
| 209 |
message_id: str,
|
| 210 |
*,
|
| 211 |
error: str,
|
|
|
|
| 212 |
retry_at: datetime,
|
| 213 |
) -> None:
|
| 214 |
await (
|
| 215 |
self.client.table("whatsapp_outbox")
|
| 216 |
.update(
|
| 217 |
{
|
| 218 |
+
"status": "pending",
|
| 219 |
"next_attempt_at": retry_at.isoformat(),
|
| 220 |
"locked_at": None,
|
| 221 |
"last_error": error[:4000],
|
|
|
|
| 225 |
.execute()
|
| 226 |
)
|
| 227 |
|
| 228 |
+
async def schedule_whatsapp_retry(
|
| 229 |
+
self,
|
| 230 |
+
message_id: str,
|
| 231 |
+
*,
|
| 232 |
+
retry_at: datetime,
|
| 233 |
+
) -> None:
|
| 234 |
+
await (
|
| 235 |
+
self.client.table("whatsapp_outbox")
|
| 236 |
+
.update({"next_attempt_at": retry_at.isoformat()})
|
| 237 |
+
.eq("id", message_id)
|
| 238 |
+
.eq("status", "pending")
|
| 239 |
+
.execute()
|
| 240 |
+
)
|
| 241 |
+
|
| 242 |
+
async def discard_whatsapp_message(
|
| 243 |
+
self,
|
| 244 |
+
message_id: str,
|
| 245 |
+
*,
|
| 246 |
+
reason: str,
|
| 247 |
+
error: str | None = None,
|
| 248 |
+
) -> None:
|
| 249 |
+
await (
|
| 250 |
+
self.client.table("whatsapp_outbox")
|
| 251 |
+
.update(
|
| 252 |
+
{
|
| 253 |
+
"status": "discarded",
|
| 254 |
+
"discarded_at": datetime.now(UTC).isoformat(),
|
| 255 |
+
"discard_reason": reason,
|
| 256 |
+
"last_error": error[:4000] if error else None,
|
| 257 |
+
"locked_at": None,
|
| 258 |
+
}
|
| 259 |
+
)
|
| 260 |
+
.eq("id", message_id)
|
| 261 |
+
.execute()
|
| 262 |
+
)
|
| 263 |
+
|
| 264 |
async def upsert_customer(
|
| 265 |
self,
|
| 266 |
*,
|
|
|
|
| 566 |
data = _response_data(response)
|
| 567 |
return data[0] if isinstance(data, list) else data
|
| 568 |
|
| 569 |
+
async def create_group_invite_submission(
|
| 570 |
+
self,
|
| 571 |
+
*,
|
| 572 |
+
invite_link: str,
|
| 573 |
+
description: str | None,
|
| 574 |
+
submitted_by_customer_id: str,
|
| 575 |
+
source_message_id: str | None,
|
| 576 |
+
) -> dict[str, Any]:
|
| 577 |
+
payload = {
|
| 578 |
+
"invite_link": invite_link,
|
| 579 |
+
"description": description,
|
| 580 |
+
"submitted_by_customer_id": submitted_by_customer_id,
|
| 581 |
+
"source_message_id": source_message_id,
|
| 582 |
+
}
|
| 583 |
+
response = await (
|
| 584 |
+
self.client.table("group_invite_submissions")
|
| 585 |
+
.insert(payload)
|
| 586 |
+
.select("id,status,created_at")
|
| 587 |
+
.execute()
|
| 588 |
+
)
|
| 589 |
+
data = _response_data(response)
|
| 590 |
+
return data[0] if isinstance(data, list) else data
|
| 591 |
+
|
| 592 |
async def get_recent_context_messages(
|
| 593 |
self,
|
| 594 |
*,
|
app/services/container.py
CHANGED
|
@@ -30,7 +30,8 @@ class ServiceContainer:
|
|
| 30 |
whatsapp = WhatsAppOutbox(
|
| 31 |
repository=repository,
|
| 32 |
client=WhatsAppClient(settings),
|
| 33 |
-
|
|
|
|
| 34 |
)
|
| 35 |
|
| 36 |
ai = LiteLLMOrchestration(
|
|
|
|
| 30 |
whatsapp = WhatsAppOutbox(
|
| 31 |
repository=repository,
|
| 32 |
client=WhatsAppClient(settings),
|
| 33 |
+
levels=settings.whatsapp_outbox_levels,
|
| 34 |
+
request_timeout_seconds=settings.request_timeout_seconds,
|
| 35 |
)
|
| 36 |
|
| 37 |
ai = LiteLLMOrchestration(
|
app/services/conversation_service.py
CHANGED
|
@@ -13,7 +13,7 @@ from app.services.trip_indexing import unindex_trip
|
|
| 13 |
from app.tools.handlers import FalzhToolHandlers, _trip_summary
|
| 14 |
from app.tools.registry import ToolRegistry
|
| 15 |
from app.utils.time import now_in_timezone
|
| 16 |
-
from app.whatsapp.client import
|
| 17 |
|
| 18 |
|
| 19 |
logger = logging.getLogger(__name__)
|
|
@@ -30,7 +30,7 @@ class ConversationService:
|
|
| 30 |
*,
|
| 31 |
repository: SupabaseRepository,
|
| 32 |
embeddings: JinaEmbeddingService,
|
| 33 |
-
whatsapp:
|
| 34 |
ai: AIOrchestrator | LiteLLMOrchestration,
|
| 35 |
settings: Settings,
|
| 36 |
system_prompt_path: Path | None = None,
|
|
@@ -201,9 +201,9 @@ class ConversationService:
|
|
| 201 |
system_note = (
|
| 202 |
f"SYSTEM: This is the first message from driver \"{driver_name}\". "
|
| 203 |
"They were previously tracked from WhatsApp group trip posts. "
|
| 204 |
-
"
|
| 205 |
"in the groups and we are impressed. Explain that we have registered them in "
|
| 206 |
-
"FALZH so they can now send trips directly here
|
| 207 |
"Show them how: just send the trip details (route, date, time) in chat. "
|
| 208 |
"Tell them they may write each trip ad in their own preferred style/format, "
|
| 209 |
"and FALZH will extract the trip details automatically. Tell them personal "
|
|
@@ -211,10 +211,18 @@ class ConversationService:
|
|
| 211 |
"shared only after a passenger selects the trip and wants to contact them. "
|
| 212 |
"Explain the benefits: passengers find their trips via AI search, they get "
|
| 213 |
"notified immediately when a passenger selects their trip, and registered "
|
| 214 |
-
"drivers get priority visibility in search results.
|
| 215 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 216 |
"Keep it warm, personal, and exciting. Use emojis. Write in Arabic. "
|
| 217 |
-
"8-10 lines max.
|
|
|
|
| 218 |
)
|
| 219 |
messages = self._ai_messages(context, user_mode=user_mode)
|
| 220 |
messages.append({"role": "system", "content": system_note})
|
|
|
|
| 13 |
from app.tools.handlers import FalzhToolHandlers, _trip_summary
|
| 14 |
from app.tools.registry import ToolRegistry
|
| 15 |
from app.utils.time import now_in_timezone
|
| 16 |
+
from app.whatsapp.client import WhatsAppSender
|
| 17 |
|
| 18 |
|
| 19 |
logger = logging.getLogger(__name__)
|
|
|
|
| 30 |
*,
|
| 31 |
repository: SupabaseRepository,
|
| 32 |
embeddings: JinaEmbeddingService,
|
| 33 |
+
whatsapp: WhatsAppSender,
|
| 34 |
ai: AIOrchestrator | LiteLLMOrchestration,
|
| 35 |
settings: Settings,
|
| 36 |
system_prompt_path: Path | None = None,
|
|
|
|
| 201 |
system_note = (
|
| 202 |
f"SYSTEM: This is the first message from driver \"{driver_name}\". "
|
| 203 |
"They were previously tracked from WhatsApp group trip posts. "
|
| 204 |
+
"If their message is only a greeting, welcome them warmly by name. Tell them we have been following their trips "
|
| 205 |
"in the groups and we are impressed. Explain that we have registered them in "
|
| 206 |
+
"FALZH so they can now send trips directly here. "
|
| 207 |
"Show them how: just send the trip details (route, date, time) in chat. "
|
| 208 |
"Tell them they may write each trip ad in their own preferred style/format, "
|
| 209 |
"and FALZH will extract the trip details automatically. Tell them personal "
|
|
|
|
| 211 |
"shared only after a passenger selects the trip and wants to contact them. "
|
| 212 |
"Explain the benefits: passengers find their trips via AI search, they get "
|
| 213 |
"notified immediately when a passenger selects their trip, and registered "
|
| 214 |
+
"drivers get priority visibility in search results. Also tell them they can "
|
| 215 |
+
"invite this number to a transportation group so suitable trip ads from the "
|
| 216 |
+
"group can be added to FALZH. Ignore links and URLs unless they explicitly ask "
|
| 217 |
+
"about them or ask FALZH to use them. A link by itself is not a request or "
|
| 218 |
+
"invitation. Call submit_group_invite only when they explicitly ask FALZH to "
|
| 219 |
+
"review or join a transportation group and provide its WhatsApp invite link; "
|
| 220 |
+
"then explain that the group will be reviewed before acceptance. If a link is "
|
| 221 |
+
"embedded in a trip ad, ignore the link and process the trip normally. Handle "
|
| 222 |
+
"other actionable requests with the appropriate driver tools. "
|
| 223 |
"Keep it warm, personal, and exciting. Use emojis. Write in Arabic. "
|
| 224 |
+
"8-10 lines max. For a simple greeting, do not call tools; otherwise use tools "
|
| 225 |
+
"when needed for the request."
|
| 226 |
)
|
| 227 |
messages = self._ai_messages(context, user_mode=user_mode)
|
| 228 |
messages.append({"role": "system", "content": system_note})
|
app/services/group_message_service.py
CHANGED
|
@@ -86,16 +86,17 @@ class GroupMessageService:
|
|
| 86 |
|
| 87 |
existing_customer = await self.repository.get_customer_by_phone_number(phone)
|
| 88 |
if existing_customer:
|
|
|
|
| 89 |
if existing_customer.get("registered"):
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
|
|
|
| 97 |
|
| 98 |
-
driver = await self.repository.get_driver_by_phone_number(phone)
|
| 99 |
if driver:
|
| 100 |
existing_trip = await self.repository.get_driver_trip_by_datetime(
|
| 101 |
driver_id=str(driver["id"]),
|
|
|
|
| 86 |
|
| 87 |
existing_customer = await self.repository.get_customer_by_phone_number(phone)
|
| 88 |
if existing_customer:
|
| 89 |
+
driver = await self.repository.get_driver_by_phone_number(phone)
|
| 90 |
if existing_customer.get("registered"):
|
| 91 |
+
if not driver:
|
| 92 |
+
logger.info(
|
| 93 |
+
"Phone %s belongs to a registered non-driver customer; "
|
| 94 |
+
"discarding group message %s",
|
| 95 |
+
phone,
|
| 96 |
+
inbound.message_id,
|
| 97 |
+
)
|
| 98 |
+
return
|
| 99 |
|
|
|
|
| 100 |
if driver:
|
| 101 |
existing_trip = await self.repository.get_driver_trip_by_datetime(
|
| 102 |
driver_id=str(driver["id"]),
|
app/tools/handlers.py
CHANGED
|
@@ -1,6 +1,7 @@
|
|
| 1 |
import logging
|
| 2 |
from decimal import Decimal, InvalidOperation
|
| 3 |
from typing import Any
|
|
|
|
| 4 |
|
| 5 |
logger = logging.getLogger(__name__)
|
| 6 |
|
|
@@ -101,6 +102,34 @@ class FalzhToolHandlers:
|
|
| 101 |
},
|
| 102 |
)
|
| 103 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
async def search_trips(self, arguments: dict[str, Any]) -> ToolResult:
|
| 105 |
departure = _optional_string(arguments.get("departure"))
|
| 106 |
destination = _optional_string(arguments.get("destination"))
|
|
@@ -933,6 +962,32 @@ def _optional_string(value: Any) -> str | None:
|
|
| 933 |
return text or None
|
| 934 |
|
| 935 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 936 |
def _optional_int(value: Any) -> int | None:
|
| 937 |
if value is None or value == "":
|
| 938 |
return None
|
|
|
|
| 1 |
import logging
|
| 2 |
from decimal import Decimal, InvalidOperation
|
| 3 |
from typing import Any
|
| 4 |
+
from urllib.parse import urlsplit
|
| 5 |
|
| 6 |
logger = logging.getLogger(__name__)
|
| 7 |
|
|
|
|
| 102 |
},
|
| 103 |
)
|
| 104 |
|
| 105 |
+
async def submit_group_invite(self, arguments: dict[str, Any]) -> ToolResult:
|
| 106 |
+
invite_link = _normalize_group_invite_link(arguments.get("invite_link"))
|
| 107 |
+
if not invite_link:
|
| 108 |
+
return ToolResult(
|
| 109 |
+
ok=False,
|
| 110 |
+
data={},
|
| 111 |
+
error="invite_link must be a valid chat.whatsapp.com invitation URL",
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
source_message_id = (self.current_message or {}).get("id")
|
| 115 |
+
submission = await self.repository.create_group_invite_submission(
|
| 116 |
+
invite_link=invite_link,
|
| 117 |
+
description=_optional_string(arguments.get("description")),
|
| 118 |
+
submitted_by_customer_id=str(self.customer["id"]),
|
| 119 |
+
source_message_id=(str(source_message_id) if source_message_id else None),
|
| 120 |
+
)
|
| 121 |
+
return ToolResult(
|
| 122 |
+
ok=True,
|
| 123 |
+
data={
|
| 124 |
+
"status": submission.get("status", "pending_review"),
|
| 125 |
+
"reply_instruction": (
|
| 126 |
+
"Confirm that the group invitation was saved for review. Say the group "
|
| 127 |
+
"will be checked before any invitation is accepted. Do not say FALZH has "
|
| 128 |
+
"joined or accepted the invitation yet."
|
| 129 |
+
),
|
| 130 |
+
},
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
async def search_trips(self, arguments: dict[str, Any]) -> ToolResult:
|
| 134 |
departure = _optional_string(arguments.get("departure"))
|
| 135 |
destination = _optional_string(arguments.get("destination"))
|
|
|
|
| 962 |
return text or None
|
| 963 |
|
| 964 |
|
| 965 |
+
def _normalize_group_invite_link(value: Any) -> str | None:
|
| 966 |
+
raw = _optional_string(value)
|
| 967 |
+
if not raw:
|
| 968 |
+
return None
|
| 969 |
+
|
| 970 |
+
raw = raw.strip("<>()[]{}«»\"'").rstrip(".,;:!?")
|
| 971 |
+
candidate = raw if "://" in raw else f"https://{raw.lstrip('/')}"
|
| 972 |
+
try:
|
| 973 |
+
parsed = urlsplit(candidate)
|
| 974 |
+
port = parsed.port
|
| 975 |
+
except ValueError:
|
| 976 |
+
return None
|
| 977 |
+
|
| 978 |
+
if (
|
| 979 |
+
parsed.scheme not in {"http", "https"}
|
| 980 |
+
or parsed.hostname != "chat.whatsapp.com"
|
| 981 |
+
or parsed.username is not None
|
| 982 |
+
or parsed.password is not None
|
| 983 |
+
or port not in {None, 80, 443}
|
| 984 |
+
or not parsed.path.strip("/")
|
| 985 |
+
or any(character.isspace() for character in candidate)
|
| 986 |
+
):
|
| 987 |
+
return None
|
| 988 |
+
return candidate
|
| 989 |
+
|
| 990 |
+
|
| 991 |
def _optional_int(value: Any) -> int | None:
|
| 992 |
if value is None or value == "":
|
| 993 |
return None
|
app/whatsapp/outbox.py
CHANGED
|
@@ -3,6 +3,7 @@ import logging
|
|
| 3 |
from datetime import UTC, datetime, timedelta
|
| 4 |
from typing import Any
|
| 5 |
|
|
|
|
| 6 |
from app.database.supabase import SupabaseRepository
|
| 7 |
from app.whatsapp.client import WhatsAppClient, WhatsAppClientError
|
| 8 |
|
|
@@ -15,11 +16,19 @@ class WhatsAppOutbox:
|
|
| 15 |
*,
|
| 16 |
repository: SupabaseRepository,
|
| 17 |
client: WhatsAppClient,
|
| 18 |
-
|
|
|
|
| 19 |
) -> None:
|
| 20 |
self.repository = repository
|
| 21 |
self.client = client
|
| 22 |
-
self.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
|
| 24 |
async def send_text(self, remoteJid: str, text: str) -> dict[str, Any]:
|
| 25 |
payload = self.client.build_text_payload(remoteJid, text)
|
|
@@ -42,54 +51,84 @@ class WhatsAppOutbox:
|
|
| 42 |
recipient=recipient,
|
| 43 |
payload=payload,
|
| 44 |
)
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
return _queued_response(row)
|
| 52 |
|
| 53 |
-
|
| 54 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
async def run_retry_worker(self) -> None:
|
| 57 |
while True:
|
| 58 |
-
await asyncio.sleep(self.
|
| 59 |
try:
|
| 60 |
await self.retry_pending_messages()
|
| 61 |
except Exception:
|
| 62 |
logger.exception("WhatsApp outbox retry pass failed")
|
| 63 |
|
| 64 |
async def retry_pending_messages(self) -> int:
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
|
|
|
| 68 |
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
|
|
|
| 74 |
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
return sent
|
| 84 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
while True:
|
| 86 |
-
|
| 87 |
-
if
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
break
|
| 89 |
|
| 90 |
claimed = await self.repository.claim_whatsapp_message(
|
| 91 |
-
str(
|
| 92 |
-
ignore_retry_time=
|
| 93 |
)
|
| 94 |
if not claimed:
|
| 95 |
break
|
|
@@ -98,21 +137,113 @@ class WhatsAppOutbox:
|
|
| 98 |
sent += int(result["sent"])
|
| 99 |
if result["retryable"]:
|
| 100 |
break
|
| 101 |
-
|
| 102 |
return sent
|
| 103 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
async def _deliver_claimed(self, row: dict[str, Any]) -> dict[str, Any]:
|
| 105 |
try:
|
| 106 |
response = await self.client.send_payload(row["payload"])
|
| 107 |
except Exception as exc: # noqa: BLE001
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
logger.warning(
|
| 117 |
"WhatsApp delivery failed for outbox message %s (retryable=%s): %s",
|
| 118 |
row["id"],
|
|
@@ -153,9 +284,15 @@ def _is_future(value: Any) -> bool:
|
|
| 153 |
if not value:
|
| 154 |
return False
|
| 155 |
try:
|
| 156 |
-
scheduled =
|
| 157 |
-
except ValueError:
|
| 158 |
return False
|
| 159 |
-
if scheduled.tzinfo is None:
|
| 160 |
-
scheduled = scheduled.replace(tzinfo=UTC)
|
| 161 |
return scheduled > datetime.now(UTC)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
from datetime import UTC, datetime, timedelta
|
| 4 |
from typing import Any
|
| 5 |
|
| 6 |
+
from app.config import WhatsAppOutboxLevel
|
| 7 |
from app.database.supabase import SupabaseRepository
|
| 8 |
from app.whatsapp.client import WhatsAppClient, WhatsAppClientError
|
| 9 |
|
|
|
|
| 16 |
*,
|
| 17 |
repository: SupabaseRepository,
|
| 18 |
client: WhatsAppClient,
|
| 19 |
+
levels: list[WhatsAppOutboxLevel],
|
| 20 |
+
request_timeout_seconds: float,
|
| 21 |
) -> None:
|
| 22 |
self.repository = repository
|
| 23 |
self.client = client
|
| 24 |
+
self.levels = levels
|
| 25 |
+
self.request_timeout_seconds = request_timeout_seconds
|
| 26 |
+
self.poll_interval_seconds = min(
|
| 27 |
+
level.retry_interval_seconds
|
| 28 |
+
for level in levels
|
| 29 |
+
if level.retry_interval_seconds is not None
|
| 30 |
+
)
|
| 31 |
+
self._send_lock = asyncio.Lock()
|
| 32 |
|
| 33 |
async def send_text(self, remoteJid: str, text: str) -> dict[str, Any]:
|
| 34 |
payload = self.client.build_text_payload(remoteJid, text)
|
|
|
|
| 51 |
recipient=recipient,
|
| 52 |
payload=payload,
|
| 53 |
)
|
| 54 |
+
async with self._send_lock:
|
| 55 |
+
await self._recover_and_discard_expired()
|
| 56 |
+
if await self.repository.has_sending_whatsapp_message():
|
| 57 |
+
return _queued_response(row)
|
| 58 |
+
|
| 59 |
+
candidate, _ = await self._next_pending_message(datetime.now(UTC))
|
| 60 |
+
if not candidate or candidate.get("id") != row.get("id"):
|
| 61 |
+
return _queued_response(row)
|
| 62 |
|
| 63 |
+
if _is_future(candidate.get("next_attempt_at")):
|
| 64 |
+
return _queued_response(row)
|
|
|
|
| 65 |
|
| 66 |
+
claimed = await self.repository.claim_whatsapp_message(str(row["id"]))
|
| 67 |
+
if not claimed:
|
| 68 |
+
return _queued_response(row)
|
| 69 |
+
|
| 70 |
+
result = await self._deliver_claimed(claimed)
|
| 71 |
+
if not result["retryable"]:
|
| 72 |
+
await self._drain_ready_messages(force=True)
|
| 73 |
+
return result.get("response") or _queued_response(row)
|
| 74 |
|
| 75 |
async def run_retry_worker(self) -> None:
|
| 76 |
while True:
|
| 77 |
+
await asyncio.sleep(self.poll_interval_seconds)
|
| 78 |
try:
|
| 79 |
await self.retry_pending_messages()
|
| 80 |
except Exception:
|
| 81 |
logger.exception("WhatsApp outbox retry pass failed")
|
| 82 |
|
| 83 |
async def retry_pending_messages(self) -> int:
|
| 84 |
+
async with self._send_lock:
|
| 85 |
+
await self._recover_and_discard_expired()
|
| 86 |
+
if await self.repository.has_sending_whatsapp_message():
|
| 87 |
+
return 0
|
| 88 |
|
| 89 |
+
candidate, level = await self._next_pending_message(datetime.now(UTC))
|
| 90 |
+
if not candidate or level is None:
|
| 91 |
+
return 0
|
| 92 |
+
await self._align_retry_schedule(candidate, level)
|
| 93 |
+
if _is_future(candidate.get("next_attempt_at")):
|
| 94 |
+
return 0
|
| 95 |
|
| 96 |
+
claimed = await self.repository.claim_whatsapp_message(str(candidate["id"]))
|
| 97 |
+
if not claimed:
|
| 98 |
+
return 0
|
| 99 |
|
| 100 |
+
result = await self._deliver_claimed(claimed)
|
| 101 |
+
sent = int(result["sent"])
|
| 102 |
+
if result["retryable"]:
|
| 103 |
+
return sent
|
| 104 |
+
|
| 105 |
+
# A successful probe means the API is reachable. Drain in priority order,
|
| 106 |
+
# bypassing per-message retry times for this recovery pass.
|
| 107 |
+
sent += await self._drain_ready_messages(force=True)
|
| 108 |
return sent
|
| 109 |
|
| 110 |
+
async def on_connection_restored(self) -> int:
|
| 111 |
+
async with self._send_lock:
|
| 112 |
+
await self._recover_and_discard_expired()
|
| 113 |
+
if await self.repository.has_sending_whatsapp_message():
|
| 114 |
+
return 0
|
| 115 |
+
return await self._drain_ready_messages(force=True)
|
| 116 |
+
|
| 117 |
+
async def _drain_ready_messages(self, *, force: bool = False) -> int:
|
| 118 |
+
sent = 0
|
| 119 |
while True:
|
| 120 |
+
await self._discard_expired_messages()
|
| 121 |
+
if await self.repository.has_sending_whatsapp_message():
|
| 122 |
+
break
|
| 123 |
+
candidate, _ = await self._next_pending_message(datetime.now(UTC))
|
| 124 |
+
if not candidate:
|
| 125 |
+
break
|
| 126 |
+
if not force and _is_future(candidate.get("next_attempt_at")):
|
| 127 |
break
|
| 128 |
|
| 129 |
claimed = await self.repository.claim_whatsapp_message(
|
| 130 |
+
str(candidate["id"]),
|
| 131 |
+
ignore_retry_time=force,
|
| 132 |
)
|
| 133 |
if not claimed:
|
| 134 |
break
|
|
|
|
| 137 |
sent += int(result["sent"])
|
| 138 |
if result["retryable"]:
|
| 139 |
break
|
| 140 |
+
force = True
|
| 141 |
return sent
|
| 142 |
|
| 143 |
+
async def _next_pending_message(
|
| 144 |
+
self,
|
| 145 |
+
now: datetime,
|
| 146 |
+
) -> tuple[dict[str, Any] | None, WhatsAppOutboxLevel | None]:
|
| 147 |
+
previous_max_age = 0
|
| 148 |
+
for level in self.levels:
|
| 149 |
+
if level.order == "discard":
|
| 150 |
+
break
|
| 151 |
+
|
| 152 |
+
newer_than = now - timedelta(seconds=level.max_age_seconds or 0)
|
| 153 |
+
older_than = (
|
| 154 |
+
now - timedelta(seconds=previous_max_age)
|
| 155 |
+
if previous_max_age > 0
|
| 156 |
+
else None
|
| 157 |
+
)
|
| 158 |
+
row = await self.repository.get_pending_whatsapp_message(
|
| 159 |
+
newer_than=newer_than,
|
| 160 |
+
older_than=older_than,
|
| 161 |
+
newest_first=level.order == "newest",
|
| 162 |
+
)
|
| 163 |
+
if row:
|
| 164 |
+
return row, level
|
| 165 |
+
previous_max_age = level.max_age_seconds or previous_max_age
|
| 166 |
+
return None, None
|
| 167 |
+
|
| 168 |
+
async def _recover_and_discard_expired(self) -> None:
|
| 169 |
+
lease_seconds = max(
|
| 170 |
+
self.poll_interval_seconds * 3,
|
| 171 |
+
int(self.request_timeout_seconds) + 10,
|
| 172 |
+
)
|
| 173 |
+
await self.repository.recover_stale_whatsapp_messages(
|
| 174 |
+
stale_before=datetime.now(UTC) - timedelta(seconds=lease_seconds),
|
| 175 |
+
)
|
| 176 |
+
await self._discard_expired_messages()
|
| 177 |
+
|
| 178 |
+
async def _discard_expired_messages(self) -> None:
|
| 179 |
+
final_retry_level = self.levels[-2]
|
| 180 |
+
cutoff = datetime.now(UTC) - timedelta(
|
| 181 |
+
seconds=final_retry_level.max_age_seconds or 0
|
| 182 |
+
)
|
| 183 |
+
await self.repository.discard_expired_whatsapp_messages(before=cutoff)
|
| 184 |
+
|
| 185 |
+
async def _align_retry_schedule(
|
| 186 |
+
self,
|
| 187 |
+
row: dict[str, Any],
|
| 188 |
+
level: WhatsAppOutboxLevel,
|
| 189 |
+
) -> None:
|
| 190 |
+
if not row.get("last_attempt_at") or not level.retry_interval_seconds:
|
| 191 |
+
return
|
| 192 |
+
last_attempt = _as_datetime(row["last_attempt_at"])
|
| 193 |
+
expected_next_attempt = last_attempt + timedelta(
|
| 194 |
+
seconds=level.retry_interval_seconds
|
| 195 |
+
)
|
| 196 |
+
if row.get("next_attempt_at"):
|
| 197 |
+
try:
|
| 198 |
+
if _as_datetime(row["next_attempt_at"]) == expected_next_attempt:
|
| 199 |
+
return
|
| 200 |
+
except (TypeError, ValueError):
|
| 201 |
+
pass
|
| 202 |
+
await self.repository.schedule_whatsapp_retry(
|
| 203 |
+
str(row["id"]),
|
| 204 |
+
retry_at=expected_next_attempt,
|
| 205 |
+
)
|
| 206 |
+
row["next_attempt_at"] = expected_next_attempt.isoformat()
|
| 207 |
+
|
| 208 |
+
def _level_for_message(self, row: dict[str, Any]) -> WhatsAppOutboxLevel:
|
| 209 |
+
created_at = _as_datetime(row.get("created_at"))
|
| 210 |
+
age_seconds = max(0, (datetime.now(UTC) - created_at).total_seconds())
|
| 211 |
+
for level in self.levels:
|
| 212 |
+
if level.max_age_seconds is None or age_seconds <= level.max_age_seconds:
|
| 213 |
+
return level
|
| 214 |
+
return self.levels[-1]
|
| 215 |
+
|
| 216 |
async def _deliver_claimed(self, row: dict[str, Any]) -> dict[str, Any]:
|
| 217 |
try:
|
| 218 |
response = await self.client.send_payload(row["payload"])
|
| 219 |
except Exception as exc: # noqa: BLE001
|
| 220 |
+
if isinstance(exc, WhatsAppClientError) and not exc.retryable:
|
| 221 |
+
await self.repository.discard_whatsapp_message(
|
| 222 |
+
str(row["id"]),
|
| 223 |
+
reason="WhatsApp API rejected the message permanently",
|
| 224 |
+
error=str(exc),
|
| 225 |
+
)
|
| 226 |
+
retryable = False
|
| 227 |
+
else:
|
| 228 |
+
level = self._level_for_message(row)
|
| 229 |
+
if level.order == "discard" or level.retry_interval_seconds is None:
|
| 230 |
+
await self.repository.discard_whatsapp_message(
|
| 231 |
+
str(row["id"]),
|
| 232 |
+
reason="Message exceeded the configured maximum age",
|
| 233 |
+
error=str(exc),
|
| 234 |
+
)
|
| 235 |
+
retryable = False
|
| 236 |
+
else:
|
| 237 |
+
retry_at = datetime.now(UTC) + timedelta(
|
| 238 |
+
seconds=level.retry_interval_seconds
|
| 239 |
+
)
|
| 240 |
+
await self.repository.fail_whatsapp_message(
|
| 241 |
+
str(row["id"]),
|
| 242 |
+
error=str(exc),
|
| 243 |
+
retry_at=retry_at,
|
| 244 |
+
)
|
| 245 |
+
retryable = True
|
| 246 |
+
|
| 247 |
logger.warning(
|
| 248 |
"WhatsApp delivery failed for outbox message %s (retryable=%s): %s",
|
| 249 |
row["id"],
|
|
|
|
| 284 |
if not value:
|
| 285 |
return False
|
| 286 |
try:
|
| 287 |
+
scheduled = _as_datetime(value)
|
| 288 |
+
except (TypeError, ValueError):
|
| 289 |
return False
|
|
|
|
|
|
|
| 290 |
return scheduled > datetime.now(UTC)
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
def _as_datetime(value: Any) -> datetime:
|
| 294 |
+
if isinstance(value, datetime):
|
| 295 |
+
parsed = value
|
| 296 |
+
else:
|
| 297 |
+
parsed = datetime.fromisoformat(str(value).replace("Z", "+00:00"))
|
| 298 |
+
return parsed.replace(tzinfo=UTC) if parsed.tzinfo is None else parsed
|
prompts/falzh_info.md
CHANGED
|
@@ -26,6 +26,9 @@
|
|
| 26 |
## خدمات السائقين
|
| 27 |
تسجيل حساب سائق: يحتاج الاسم الكامل. تربط فلزة حسابك برقم واتسابك. إضافة مركبة: اسم المركبة مطلوب، رقم اللوحة وعدد المقاعد اختياري. نشر رحلة: يلزم المدينة (من وإلى)، التاريخ، الفترة (صباح/ظهر/ليل). يقدر السائق يكتب إعلان الرحلة بصيغته الخاصة وبأسلوبه المعتاد، وفلزة تستخرج تفاصيل الرحلة تلقائياً. عدد المقاعد والسعر تُملأ تلقائياً من آخر رحلة أو مركبتك المسجلة. تعديل رحلة: تقدر تغير الوجهة، الوقت، السيارة، المقاعد، أو السعر. تاريخ الرحلة لا يمكن تغييره — لازم تنشئ رحلة جديدة. حذف رحلة: تلغي الرحلة وترفعها من البحث. ممنوع يكون عندك رحلتين في نفس التاريخ والفترة.
|
| 28 |
|
|
|
|
|
|
|
|
|
|
| 29 |
## السياسات
|
| 30 |
فلزة لا تحجز رحلات ولا تؤكد حجوزات. اختيار الرحلة يعني تسجيل اهتمام فقط. فلزة لا تتعامل في المدفوعات نهائياً. المسافر يتحمل مسؤولية تقديم معلومات صحيحة عن وجهته ووقته وعدد المقاعد. فلزة فقط تقدم معلومات عن خدماتها — ترفض الإجابة عن أي موضوع خارج السفر.
|
| 31 |
|
|
@@ -45,6 +48,7 @@
|
|
| 45 |
س: هل تنبهوني إذا توفرت رحلة بحثت عنها؟ ج: لا توجد تنبيهات تلقائية عند إضافة رحلة جديدة حالياً. تقدر تبحث مرة ثانية لاحقاً.
|
| 46 |
س: كيف أضيف رحلة كسائق؟ ج: قول "أبي أضيف رحلة من عدن إلى الحديدة الجمعة الصباح" أو اكتب إعلانك بتنسيقك الخاص. فلزة تستخرج التفاصيل وتزيل الرقم والبيانات الشخصية من بطاقة العرض.
|
| 47 |
س: كيف أعدل أو ألغي رحلة؟ ج: قول "أبي أعدل رحلة" أو "أبي ألغي رحلة". فلزة ترسل لك قائمة رحلاتك — ترد على اللي تبيه.
|
|
|
|
| 48 |
س: هل فيه رحلات بين كل المدن؟ ج: فلزة تعرض الرحلات اللي ينشرها السائقين. إذا ما لقيت رحلتك، اسأل مرة ثانية أو تواصل مع الدعم.
|
| 49 |
س: هل الخدمة مجانية؟ ج: استخدام فلزة مجاني. السعر للسفر تتفق فيه مع السائق.
|
| 50 |
|
|
|
|
| 26 |
## خدمات السائقين
|
| 27 |
تسجيل حساب سائق: يحتاج الاسم الكامل. تربط فلزة حسابك برقم واتسابك. إضافة مركبة: اسم المركبة مطلوب، رقم اللوحة وعدد المقاعد اختياري. نشر رحلة: يلزم المدينة (من وإلى)، التاريخ، الفترة (صباح/ظهر/ليل). يقدر السائق يكتب إعلان الرحلة بصيغته الخاصة وبأسلوبه المعتاد، وفلزة تستخرج تفاصيل الرحلة تلقائياً. عدد المقاعد والسعر تُملأ تلقائياً من آخر رحلة أو مركبتك المسجلة. تعديل رحلة: تقدر تغير الوجهة، الوقت، السيارة، المقاعد، أو السعر. تاريخ الرحلة لا يمكن تغييره — لازم تنشئ رحلة جديدة. حذف رحلة: تلغي الرحلة وترفعها من البحث. ممنوع يكون عندك رحلتين في نفس التاريخ والفترة.
|
| 28 |
|
| 29 |
+
## مجموعات النقل
|
| 30 |
+
يقدر السائق يدعو رقم فلزة إلى مجموعة واتساب للنقل حتى نضيف إعلانات الرحلات المناسبة المنشورة فيها إلى النظام. إذا طلب المستخدم بوضوح مراجعة المجموعة أو الانضمام إليها وأرسل رابط الدعوة، نحفظ الرابط ووصفه للمراجعة أولاً. لا نعتبر إرسال الرابط وحده طلباً أو دعوة، ولا يعني حفظ الرابط قبول الدعوة أو الانضمام الفوري.
|
| 31 |
+
|
| 32 |
## السياسات
|
| 33 |
فلزة لا تحجز رحلات ولا تؤكد حجوزات. اختيار الرحلة يعني تسجيل اهتمام فقط. فلزة لا تتعامل في المدفوعات نهائياً. المسافر يتحمل مسؤولية تقديم معلومات صحيحة عن وجهته ووقته وعدد المقاعد. فلزة فقط تقدم معلومات عن خدماتها — ترفض الإجابة عن أي موضوع خارج السفر.
|
| 34 |
|
|
|
|
| 48 |
س: هل تنبهوني إذا توفرت رحلة بحثت عنها؟ ج: لا توجد تنبيهات تلقائية عند إضافة رحلة جديدة حالياً. تقدر تبحث مرة ثانية لاحقاً.
|
| 49 |
س: كيف أضيف رحلة كسائق؟ ج: قول "أبي أضيف رحلة من عدن إلى الحديدة الجمعة الصباح" أو اكتب إعلانك بتنسيقك الخاص. فلزة تستخرج التفاصيل وتزيل الرقم والبيانات الشخصية من بطاقة العرض.
|
| 50 |
س: كيف أعدل أو ألغي رحلة؟ ج: قول "أبي أعدل رحلة" أو "أبي ألغي رحلة". فلزة ترسل لك قائمة رحلاتك — ترد على اللي تبيه.
|
| 51 |
+
س: كيف أضيف رحلات مجموعة نقل إلى فلزة؟ ج: أضف رقم فلزة إلى المجموعة، أو اطلب بوضوح مراجعة المجموعة وأرسل رابط الدعوة. نحفظ الرابط للمراجعة قبل قبول الدعوة، وبعد الانضمام نضيف إعلانات الرحلات المناسبة. إرسال الرابط وحده لا يكفي لاعتباره دعوة.
|
| 52 |
س: هل فيه رحلات بين كل المدن؟ ج: فلزة تعرض الرحلات اللي ينشرها السائقين. إذا ما لقيت رحلتك، اسأل مرة ثانية أو تواصل مع الدعم.
|
| 53 |
س: هل الخدمة مجانية؟ ج: استخدام فلزة مجاني. السعر للسفر تتفق فيه مع السائق.
|
| 54 |
|
prompts/system.md
CHANGED
|
@@ -6,6 +6,9 @@ Rules:
|
|
| 6 |
- Never send tables or use `|` pipe/column formatting (WhatsApp does not render them). Use short bullet points (`•`) or plain sentences instead.
|
| 7 |
- When writing in Arabic, the brand name must always be spelled exactly "فلزة" (ف-ل-ز-ا). Never use "فلسا", "فلظ", "فلظة", "فلز", or any other variant.
|
| 8 |
- For new users: be extra warm and welcoming. Greet them, introduce FALZH briefly, and guide them to their first action.
|
|
|
|
|
|
|
|
|
|
| 9 |
- Use `about_falzh` for company/FAQ/policy/pricing/support, and for any feature,
|
| 10 |
capability, or FALZH request you are unsure about. Answer only from the returned
|
| 11 |
context. If it does not clearly answer the question, apologize briefly and say
|
|
|
|
| 6 |
- Never send tables or use `|` pipe/column formatting (WhatsApp does not render them). Use short bullet points (`•`) or plain sentences instead.
|
| 7 |
- When writing in Arabic, the brand name must always be spelled exactly "فلزة" (ف-ل-ز-ا). Never use "فلسا", "فلظ", "فلظة", "فلز", or any other variant.
|
| 8 |
- For new users: be extra warm and welcoming. Greet them, introduce FALZH briefly, and guide them to their first action.
|
| 9 |
+
- Ignore links and URLs by default and focus on what the user says and wants. Do not interpret, explain, store, or act on a link unless the user explicitly asks about it or asks FALZH to use it. A link by itself is not a request or invitation; if there is no other message to respond to, ask what they need help with without analyzing the link.
|
| 10 |
+
- Call `submit_group_invite` only when the user explicitly asks FALZH to review or join a transportation group and provides its WhatsApp invite link. Only confirm saving if the tool succeeds. After saving, say the group will be reviewed before accepting; never say it has already been accepted or joined.
|
| 11 |
+
- The group-invitation process described above is confirmed behavior; answer group-invitation questions from these instructions without calling `about_falzh`.
|
| 12 |
- Use `about_falzh` for company/FAQ/policy/pricing/support, and for any feature,
|
| 13 |
capability, or FALZH request you are unsure about. Answer only from the returned
|
| 14 |
context. If it does not clearly answer the question, apologize briefly and say
|
prompts/system_driver.md
CHANGED
|
@@ -12,7 +12,7 @@
|
|
| 12 |
- For delete/modify: initiate_trip_action (sends numbered list). Driver replies with number.
|
| 13 |
- delete_trip_by_number(trip_number) / modify_trip_by_number(trip_number, field, value). No trip_id.
|
| 14 |
- To search/book as traveler: switch_to_passenger (name optional).
|
| 15 |
-
|
| 16 |
Driver message cleanup:
|
| 17 |
- When the driver's message is a custom trip ad they likely want passengers to see,
|
| 18 |
set `driver_message` in add_trip_by_driver after cleaning it. For plain commands
|
|
|
|
| 12 |
- For delete/modify: initiate_trip_action (sends numbered list). Driver replies with number.
|
| 13 |
- delete_trip_by_number(trip_number) / modify_trip_by_number(trip_number, field, value). No trip_id.
|
| 14 |
- To search/book as traveler: switch_to_passenger (name optional).
|
| 15 |
+
- When welcoming a driver for the first time, tell them they can invite this number to a transportation group so suitable trip ads from the group can be added to FALZH.
|
| 16 |
Driver message cleanup:
|
| 17 |
- When the driver's message is a custom trip ad they likely want passengers to see,
|
| 18 |
set `driver_message` in add_trip_by_driver after cleaning it. For plain commands
|
prompts/system_new_user.md
CHANGED
|
@@ -4,7 +4,7 @@ It is the sender's first message. Welcome them warmly and introduce FALZH with a
|
|
| 4 |
2. Explain what FALZH is in 1 sentence: a WhatsApp travel service powered by AI — no app to install.
|
| 5 |
3. Give a quick how-to guide showing both paths clearly:
|
| 6 |
- المسافر: اكتب وجهتك (مثلاً "من صنعاء إلى عدن بكرة الصباح") ← فلزة تبحث ← رد على البطاقة ← تتواصل مع السائق. Do NOT ask for name.
|
| 7 |
-
- السائق:
|
| 8 |
4. Use emojis (🚗, 🚚, etc.) and friendly tone. Be warm, not robotic.
|
| 9 |
5. Keep it short — 4-5 lines max. Do not over-explain.
|
| 10 |
6. Never ask for name of a passenger. Only ask for name if they want to become a driver.
|
|
|
|
| 4 |
2. Explain what FALZH is in 1 sentence: a WhatsApp travel service powered by AI — no app to install.
|
| 5 |
3. Give a quick how-to guide showing both paths clearly:
|
| 6 |
- المسافر: اكتب وجهتك (مثلاً "من صنعاء إلى عدن بكرة الصباح") ← فلزة تبحث ← رد على البطاقة ← تتواصل مع السائق. Do NOT ask for name.
|
| 7 |
+
- السائق: اجمع اسمه الكامل ثم create_driver_account(name) -> switch_to_driver. بعدها يرسل إعلانه بتنسيقه؛ فلزة تستخرج التفاصيل وتحذف الرقم والبيانات الشخصية. ويمكنه إضافة هذا الرقم لمجموعة نقل لتصلنا الإعلانات المناسبة.
|
| 8 |
4. Use emojis (🚗, 🚚, etc.) and friendly tone. Be warm, not robotic.
|
| 9 |
5. Keep it short — 4-5 lines max. Do not over-explain.
|
| 10 |
6. Never ask for name of a passenger. Only ask for name if they want to become a driver.
|
supabase/migrations/202610150001_tiered_whatsapp_outbox.sql
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
alter table public.whatsapp_outbox
|
| 2 |
+
add column if not exists discarded_at timestamptz,
|
| 3 |
+
add column if not exists discard_reason text;
|
| 4 |
+
|
| 5 |
+
alter table public.whatsapp_outbox
|
| 6 |
+
drop constraint if exists whatsapp_outbox_status_check;
|
| 7 |
+
|
| 8 |
+
alter table public.whatsapp_outbox
|
| 9 |
+
add constraint whatsapp_outbox_status_check
|
| 10 |
+
check (status in ('pending', 'sending', 'sent', 'failed', 'discarded'));
|
| 11 |
+
|
| 12 |
+
update public.whatsapp_outbox
|
| 13 |
+
set status = 'discarded',
|
| 14 |
+
discarded_at = coalesce(discarded_at, now()),
|
| 15 |
+
discard_reason = coalesce(discard_reason, 'Permanent failure from the previous retry policy')
|
| 16 |
+
where status = 'failed';
|
supabase/migrations/202610170001_group_invite_submissions.sql
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
create table if not exists public.group_invite_submissions (
|
| 2 |
+
id uuid primary key default gen_random_uuid(),
|
| 3 |
+
invite_link text not null,
|
| 4 |
+
description text,
|
| 5 |
+
submitted_by_customer_id uuid not null
|
| 6 |
+
references public.customers(id) on delete cascade,
|
| 7 |
+
source_message_id uuid
|
| 8 |
+
references public.messages(id) on delete set null,
|
| 9 |
+
status text not null default 'pending_review'
|
| 10 |
+
check (status in ('pending_review', 'accepted', 'rejected')),
|
| 11 |
+
reviewed_at timestamptz,
|
| 12 |
+
created_at timestamptz not null default now()
|
| 13 |
+
);
|
| 14 |
+
|
| 15 |
+
create index if not exists idx_group_invite_submissions_review_queue
|
| 16 |
+
on public.group_invite_submissions (status, created_at);
|
| 17 |
+
|
| 18 |
+
create index if not exists idx_group_invite_submissions_customer
|
| 19 |
+
on public.group_invite_submissions (submitted_by_customer_id, created_at desc);
|
| 20 |
+
|
| 21 |
+
alter table public.group_invite_submissions enable row level security;
|
| 22 |
+
|
| 23 |
+
revoke all on table public.group_invite_submissions from public, anon, authenticated;
|
| 24 |
+
grant all on table public.group_invite_submissions to service_role;
|
supabase/migrations/public_schema.sql
CHANGED
|
@@ -349,6 +349,24 @@ CREATE TABLE public.messages (
|
|
| 349 |
);
|
| 350 |
|
| 351 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 352 |
--
|
| 353 |
-- Name: whatsapp_outbox; Type: TABLE; Schema: public; Owner: -
|
| 354 |
--
|
|
@@ -365,8 +383,10 @@ CREATE TABLE public.whatsapp_outbox (
|
|
| 365 |
sent_at timestamp with time zone,
|
| 366 |
last_error text,
|
| 367 |
provider_response jsonb,
|
|
|
|
|
|
|
| 368 |
created_at timestamp with time zone DEFAULT now() NOT NULL,
|
| 369 |
-
CONSTRAINT whatsapp_outbox_status_check CHECK ((status = ANY (ARRAY['pending'::text, 'sending'::text, 'sent'::text, 'failed'::text]))),
|
| 370 |
CONSTRAINT whatsapp_outbox_attempts_check CHECK ((attempts >= 0))
|
| 371 |
);
|
| 372 |
|
|
@@ -582,6 +602,20 @@ CREATE INDEX idx_driver_trip_embeddings_embedding ON public.driver_trip_embeddin
|
|
| 582 |
CREATE INDEX idx_driver_trips_active_route ON public.driver_trips USING btree (status, departure, destination, departure_date, departure_time);
|
| 583 |
|
| 584 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 585 |
--
|
| 586 |
-- Name: idx_falzh_info_chunks_embedding; Type: INDEX; Schema: public; Owner: -
|
| 587 |
--
|
|
@@ -793,6 +827,12 @@ ALTER TABLE public.falzh_info_chunks ENABLE ROW LEVEL SECURITY;
|
|
| 793 |
|
| 794 |
ALTER TABLE public.messages ENABLE ROW LEVEL SECURITY;
|
| 795 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 796 |
--
|
| 797 |
-- Name: whatsapp_outbox; Type: ROW SECURITY; Schema: public; Owner: -
|
| 798 |
--
|
|
|
|
| 349 |
);
|
| 350 |
|
| 351 |
|
| 352 |
+
--
|
| 353 |
+
-- Name: group_invite_submissions; Type: TABLE; Schema: public; Owner: -
|
| 354 |
+
--
|
| 355 |
+
|
| 356 |
+
CREATE TABLE public.group_invite_submissions (
|
| 357 |
+
id uuid DEFAULT gen_random_uuid() NOT NULL,
|
| 358 |
+
invite_link text NOT NULL,
|
| 359 |
+
description text,
|
| 360 |
+
submitted_by_customer_id uuid NOT NULL REFERENCES public.customers(id) ON DELETE CASCADE,
|
| 361 |
+
source_message_id uuid REFERENCES public.messages(id) ON DELETE SET NULL,
|
| 362 |
+
status text DEFAULT 'pending_review'::text NOT NULL,
|
| 363 |
+
reviewed_at timestamp with time zone,
|
| 364 |
+
created_at timestamp with time zone DEFAULT now() NOT NULL,
|
| 365 |
+
CONSTRAINT group_invite_submissions_pkey PRIMARY KEY (id),
|
| 366 |
+
CONSTRAINT group_invite_submissions_status_check CHECK ((status = ANY (ARRAY['pending_review'::text, 'accepted'::text, 'rejected'::text])))
|
| 367 |
+
);
|
| 368 |
+
|
| 369 |
+
|
| 370 |
--
|
| 371 |
-- Name: whatsapp_outbox; Type: TABLE; Schema: public; Owner: -
|
| 372 |
--
|
|
|
|
| 383 |
sent_at timestamp with time zone,
|
| 384 |
last_error text,
|
| 385 |
provider_response jsonb,
|
| 386 |
+
discarded_at timestamp with time zone,
|
| 387 |
+
discard_reason text,
|
| 388 |
created_at timestamp with time zone DEFAULT now() NOT NULL,
|
| 389 |
+
CONSTRAINT whatsapp_outbox_status_check CHECK ((status = ANY (ARRAY['pending'::text, 'sending'::text, 'sent'::text, 'failed'::text, 'discarded'::text]))),
|
| 390 |
CONSTRAINT whatsapp_outbox_attempts_check CHECK ((attempts >= 0))
|
| 391 |
);
|
| 392 |
|
|
|
|
| 602 |
CREATE INDEX idx_driver_trips_active_route ON public.driver_trips USING btree (status, departure, destination, departure_date, departure_time);
|
| 603 |
|
| 604 |
|
| 605 |
+
--
|
| 606 |
+
-- Name: idx_group_invite_submissions_review_queue; Type: INDEX; Schema: public; Owner: -
|
| 607 |
+
--
|
| 608 |
+
|
| 609 |
+
CREATE INDEX idx_group_invite_submissions_review_queue ON public.group_invite_submissions USING btree (status, created_at);
|
| 610 |
+
|
| 611 |
+
|
| 612 |
+
--
|
| 613 |
+
-- Name: idx_group_invite_submissions_customer; Type: INDEX; Schema: public; Owner: -
|
| 614 |
+
--
|
| 615 |
+
|
| 616 |
+
CREATE INDEX idx_group_invite_submissions_customer ON public.group_invite_submissions USING btree (submitted_by_customer_id, created_at DESC);
|
| 617 |
+
|
| 618 |
+
|
| 619 |
--
|
| 620 |
-- Name: idx_falzh_info_chunks_embedding; Type: INDEX; Schema: public; Owner: -
|
| 621 |
--
|
|
|
|
| 827 |
|
| 828 |
ALTER TABLE public.messages ENABLE ROW LEVEL SECURITY;
|
| 829 |
|
| 830 |
+
--
|
| 831 |
+
-- Name: group_invite_submissions; Type: ROW SECURITY; Schema: public; Owner: -
|
| 832 |
+
--
|
| 833 |
+
|
| 834 |
+
ALTER TABLE public.group_invite_submissions ENABLE ROW LEVEL SECURITY;
|
| 835 |
+
|
| 836 |
--
|
| 837 |
-- Name: whatsapp_outbox; Type: ROW SECURITY; Schema: public; Owner: -
|
| 838 |
--
|
tests/conftest.py
CHANGED
|
@@ -108,6 +108,7 @@ class FakeRepository:
|
|
| 108 |
self.trip_embeddings: list[dict[str, Any]] = []
|
| 109 |
self.messages: list[dict[str, Any]] = []
|
| 110 |
self.trip_selections: list[dict[str, Any]] = []
|
|
|
|
| 111 |
self.notification_updates: list[dict[str, Any]] = []
|
| 112 |
self.trips_by_id: dict[str, dict[str, Any]] = {}
|
| 113 |
self.active_search_results: list[dict[str, Any]] = []
|
|
@@ -383,6 +384,25 @@ class FakeRepository:
|
|
| 383 |
self.messages.append(row)
|
| 384 |
return row
|
| 385 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 386 |
async def get_recent_context_messages(
|
| 387 |
self,
|
| 388 |
*,
|
|
|
|
| 108 |
self.trip_embeddings: list[dict[str, Any]] = []
|
| 109 |
self.messages: list[dict[str, Any]] = []
|
| 110 |
self.trip_selections: list[dict[str, Any]] = []
|
| 111 |
+
self.group_invite_submissions: list[dict[str, Any]] = []
|
| 112 |
self.notification_updates: list[dict[str, Any]] = []
|
| 113 |
self.trips_by_id: dict[str, dict[str, Any]] = {}
|
| 114 |
self.active_search_results: list[dict[str, Any]] = []
|
|
|
|
| 384 |
self.messages.append(row)
|
| 385 |
return row
|
| 386 |
|
| 387 |
+
async def create_group_invite_submission(
|
| 388 |
+
self,
|
| 389 |
+
*,
|
| 390 |
+
invite_link: str,
|
| 391 |
+
description: str | None,
|
| 392 |
+
submitted_by_customer_id: str,
|
| 393 |
+
source_message_id: str | None,
|
| 394 |
+
) -> dict[str, Any]:
|
| 395 |
+
row = {
|
| 396 |
+
"id": f"group-invite-{len(self.group_invite_submissions) + 1}",
|
| 397 |
+
"invite_link": invite_link,
|
| 398 |
+
"description": description,
|
| 399 |
+
"submitted_by_customer_id": submitted_by_customer_id,
|
| 400 |
+
"source_message_id": source_message_id,
|
| 401 |
+
"status": "pending_review",
|
| 402 |
+
}
|
| 403 |
+
self.group_invite_submissions.append(row)
|
| 404 |
+
return row
|
| 405 |
+
|
| 406 |
async def get_recent_context_messages(
|
| 407 |
self,
|
| 408 |
*,
|
tests/test_tool_schemas.py
CHANGED
|
@@ -5,6 +5,7 @@ def test_new_user_tools_are_onboarding_only():
|
|
| 5 |
names = {schema["function"]["name"] for schema in get_tool_schemas("new_user")}
|
| 6 |
assert names == {
|
| 7 |
"about_falzh",
|
|
|
|
| 8 |
"create_driver_account",
|
| 9 |
"switch_to_driver",
|
| 10 |
"switch_to_passenger",
|
|
@@ -30,4 +31,4 @@ def test_passenger_tools_exclude_driver_management_tools():
|
|
| 30 |
|
| 31 |
def test_all_tool_schemas_include_every_tool():
|
| 32 |
names = {schema["function"]["name"] for schema in get_all_tool_schemas()}
|
| 33 |
-
assert len(names) ==
|
|
|
|
| 5 |
names = {schema["function"]["name"] for schema in get_tool_schemas("new_user")}
|
| 6 |
assert names == {
|
| 7 |
"about_falzh",
|
| 8 |
+
"submit_group_invite",
|
| 9 |
"create_driver_account",
|
| 10 |
"switch_to_driver",
|
| 11 |
"switch_to_passenger",
|
|
|
|
| 31 |
|
| 32 |
def test_all_tool_schemas_include_every_tool():
|
| 33 |
names = {schema["function"]["name"] for schema in get_all_tool_schemas()}
|
| 34 |
+
assert len(names) == 13
|