Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
36 commits
Select commit Hold shift + click to select a range
6f6e844
ci(tenant/com): deploy CoM Hydroponics tenant to test
anjarakvo Aug 18, 2026
631c7ab
ci(tenant/com): point test compose backend image at com-agriconnect
anjarakvo Aug 18, 2026
c2e0ed0
ci(tenant/com): sanitize GITHUB_REF_NAME for docker tag
anjarakvo Aug 18, 2026
fbe2c2f
ci(tenant/com): scope deploy concurrency per branch/tenant
anjarakvo Aug 18, 2026
723ff5a
ci(tenant/com): sanitize composite image tags for slash branch
anjarakvo Aug 18, 2026
3b160eb
mobile(tenant/com): CoM Hydroponics Expo identity
anjarakvo Aug 18, 2026
a22b3b2
[#189] feat(administrative): add FSM administrative dataset and confi…
wayangalihpratama Aug 18, 2026
6d93ce6
Merge branch 'main' into feature/189-mt-003-setup-initial-com-hydropo…
wayangalihpratama Aug 18, 2026
1507fcb
[#189] fix(config): update onboarding location question for FSM admin…
wayangalihpratama Aug 18, 2026
5ec4e9f
Merge pull request #190 from akvo/feature/189-mt-003-setup-initial-co…
wayangalihpratama Aug 18, 2026
5bbc638
[#191] merge(tenant/com): resolve merge conflict in config.template.j…
wayangalihpratama Aug 19, 2026
cf247db
[#189] chore(config): update config.template.json for tenant/com to E…
wayangalihpratama Aug 19, 2026
00e03bb
[#195] merge(tenant/com): sync configurable escalation feature from main
wayangalihpratama Sep 1, 2026
15672ab
Merge pull request #197 from akvo/feature/195-sync-escalation-to-tena…
wayangalihpratama Sep 1, 2026
40f7c71
[#195] chore(config): disable escalation by default for tenant/com in…
wayangalihpratama Sep 1, 2026
a0b9837
[#198] docs: add Facebook Messenger integration technical specification
wayangalihpratama Sep 29, 2026
3639410
[#198] feat(config): add Facebook Messenger environment settings
wayangalihpratama Sep 29, 2026
589b79d
[#198] feat(messenger): add MessengerService Graph API client and sig…
wayangalihpratama Sep 29, 2026
2f9ce44
[#198] feat(messenger): add webhook router, GDPR data deletion, and m…
wayangalihpratama Sep 29, 2026
205352e
[#198] feat(messenger): add facebook messenger webhook integration an…
wayangalihpratama Sep 29, 2026
31ae8e0
[#198] test(messenger): add unit and integration tests for facebook m…
wayangalihpratama Sep 29, 2026
f45035c
[#198] docs(messenger): update facebook messenger integration specifi…
wayangalihpratama Sep 29, 2026
2e01054
[#198] feat(messages): route EO dashboard direct replies to messenger…
wayangalihpratama Sep 29, 2026
5906dd3
[#198] feat(messenger): add escalation quick reply and weather intent…
wayangalihpratama Sep 29, 2026
dbba681
[#198] docs(messenger): update integration spec with multi-channel di…
wayangalihpratama Sep 29, 2026
c090cc8
[#198] feat(config): make follow-up question feature configurable and…
wayangalihpratama Sep 29, 2026
494aeaa
[#198] feat(config): add configurable channel toggles defaulting to w…
wayangalihpratama Sep 29, 2026
6509b4b
[#198] fix(messenger): handle callback delivery errors and chunk long…
wayangalihpratama Sep 29, 2026
b7514fe
[#198] feat(messenger): make typing indicator configurable and non-bl…
wayangalihpratama Sep 29, 2026
601b8d4
Merge branch 'tenant/com' into tenant/mhm-rmi
wayangalihpratama Sep 29, 2026
e54de82
feat(deployment) Update tenant branches to mhm-rmi
wayangalihpratama Sep 29, 2026
9e65f9e
feat(deployment): update tenant/mhm-rmi deployment
wayangalihpratama Sep 30, 2026
0a770c7
[#198] chore(config): update default config template for MHM-RMI tenant
wayangalihpratama Sep 30, 2026
a8816d9
[#198] merge: resolve config template conflicts with tenant/mhm-rmi
wayangalihpratama Sep 30, 2026
d45952e
Merge pull request #201 from akvo/feature/198-facebook-messenger-poc
wayangalihpratama Sep 30, 2026
fcbe86f
[#198] chore(core): restore main baseline and update documentation
wayangalihpratama Sep 30, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 18 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -80,4 +80,21 @@ REDIS_DB=0
# Static token for external applications (e.g., Streamlit dashboards)
# to access the /api/statistic/* endpoints
# Generate with: openssl rand -hex 32
STATISTIC_API_TOKEN=your_statistic_api_token_here
STATISTIC_API_TOKEN=your_statistic_api_token_here

# Facebook Messenger Configuration
# Facebook Page ID: From Facebook Page settings (About -> Page ID) or Meta App Dashboard
MESSENGER_PAGE_ID=your_facebook_page_id_here

# Webhook Verify Token: Custom secret token you enter in Meta App Dashboard (Messenger -> Webhooks)
# Generate with: openssl rand -hex 32
MESSENGER_VERIFY_TOKEN=agriconnect_messenger_verify_token

# Page Access Token: Meta Developer Portal -> App Dashboard -> Messenger -> API Setup -> Generate Token
MESSENGER_PAGE_ACCESS_TOKEN=your_page_access_token_here

# Meta App Secret: Meta Developer Portal -> App Dashboard -> App settings -> Basic -> App secret
MESSENGER_APP_SECRET=your_app_secret_here

# Meta Graph API Version (default: v21.0)
MESSENGER_GRAPH_API_VERSION=v21.0
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,14 @@ Create a `.env` file based on `.env.example` with the following key variables:
- `BROADCAST_BATCH_SIZE` - Recipients per batch (default: 50)
- `BROADCAST_RETRY_INTERVALS` - Retry intervals in minutes (default: 5,15,60)

**Facebook Messenger (Opt-in Channel):**
- `MESSENGER_PAGE_ID` - Facebook Page ID
- `MESSENGER_VERIFY_TOKEN` - Webhook verification token
- `MESSENGER_PAGE_ACCESS_TOKEN` - Meta Page Access Token
- `MESSENGER_APP_SECRET` - Meta App Secret for SHA-256 HMAC signature validation
- `MESSENGER_GRAPH_API_VERSION` - Meta Graph API version (default: `v21.0`)
- Channel toggle in `config.json` under `channels.messenger.enabled` (default: `false`)

**Weather Broadcast:**
- `GOOGLEWEATHER` - Google Weather API key for weather forecasts
- Enable in `config.json`:
Expand All @@ -210,6 +218,7 @@ See `.env.example` for complete configuration options.

Additional documentation is available in the `docs/` directory:

- **[Facebook Messenger Integration](docs/FACEBOOK_MESSENGER_INTEGRATION.md)**: Facebook Messenger webhook ingestion, HMAC validation, channel routing, and configuration guide
- **[Broadcast API Core Implementation](docs/BROADCAST_API_CORE_IMPLEMENTATION.md)**: Broadcast messaging system architecture and implementation guide
- **[Broadcast API Twilio Integration](docs/BROADCAST_API_TWILIO_INTEGRATION.md)**: Twilio WhatsApp integration and Celery task queue setup
- **[Weather Subscription](docs/WEATHER_SUBSCRIPTION.md)**: Weather broadcast feature, subscription flow, and intent detection
Expand Down
28 changes: 27 additions & 1 deletion backend/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,19 @@ class Settings(BaseSettings):
extra="ignore",
)

# Channels configuration
whatsapp_enabled: bool = (
_config.get("channels", {}).get("whatsapp", {}).get("enabled", True)
)
messenger_enabled: bool = (
_config.get("channels", {}).get("messenger", {}).get("enabled", False)
)
messenger_typing_indicator_enabled: bool = (
_config.get("channels", {})
.get("messenger", {})
.get("typing_indicator_enabled", False)
)

# Message limit
message_limit: int = _config.get("message_limit")

Expand Down Expand Up @@ -457,7 +470,20 @@ def admin_delimiter(self) -> str:
"forecast_days", 6
)

# Statistic API Token (for external applications like Streamlit dashboards)
# Facebook Messenger Configuration
messenger_page_id: str = os.getenv("MESSENGER_PAGE_ID", "")
messenger_verify_token: str = os.getenv(
"MESSENGER_VERIFY_TOKEN", "agriconnect_messenger_verify_token"
)
messenger_page_access_token: str = os.getenv(
"MESSENGER_PAGE_ACCESS_TOKEN", ""
)
messenger_app_secret: str = os.getenv("MESSENGER_APP_SECRET", "")
messenger_graph_api_version: str = os.getenv(
"MESSENGER_GRAPH_API_VERSION", "v21.0"
)

# Statistics API Token
statistic_api_token: str = os.getenv("STATISTIC_API_TOKEN", "")

@property
Expand Down
17 changes: 17 additions & 0 deletions backend/config.template.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
{
"message_limit": 10,
"channels": {
"whatsapp": {
"enabled": true,
"description": "WhatsApp messaging channel via Twilio / Meta API"
},
"messenger": {
"enabled": false,
"typing_indicator_enabled": false,
"description": "Facebook Messenger messaging channel (opt-in)"
}
},
"whatsapp": {
"templates": {
"confirmation": {
Expand Down Expand Up @@ -73,6 +84,12 @@
"max_tokens": 500,
"system_prompt": "You are a helpful agricultural assistant helping farmers get started with AgriConnect. Be friendly, concise, and practical."
},
"follow_up": {
"enabled": true,
"temperature": 0.7,
"max_tokens": 150,
"description": "Ask contextual follow-up question before routing to external AI"
},
"content_moderation": {
"enabled": true,
"auto_flag": true
Expand Down
35 changes: 32 additions & 3 deletions backend/config.test.template.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
{
"message_limit": 10,
"channels": {
"whatsapp": {
"enabled": true,
"description": "WhatsApp messaging channel via Twilio / Meta API"
},
"messenger": {
"enabled": true,
"typing_indicator_enabled": false,
"description": "Facebook Messenger messaging channel"
}
},
"whatsapp": {
"templates": {
"confirmation": {
Expand Down Expand Up @@ -73,6 +84,12 @@
"max_tokens": 500,
"system_prompt": "You are a helpful agricultural assistant helping farmers get started with AgriConnect. Be friendly, concise, and practical."
},
"follow_up": {
"enabled": true,
"temperature": 0.7,
"max_tokens": 150,
"description": "Ask contextual follow-up question before routing to external AI"
},
"content_moderation": {
"enabled": true,
"auto_flag": true
Expand Down Expand Up @@ -103,9 +120,21 @@
"delimiter": " > ",
"levels": [
{ "level_index": 0, "name": "country", "display": { "en": "Country" } },
{ "level_index": 1, "name": "region", "display": { "en": "Region", "sw": "Mkoa" } },
{ "level_index": 2, "name": "district", "display": { "en": "District", "sw": "Wilaya" } },
{ "level_index": 3, "name": "ward", "display": { "en": "Ward", "sw": "Kata" } }
{
"level_index": 1,
"name": "region",
"display": { "en": "Region", "sw": "Mkoa" }
},
{
"level_index": 2,
"name": "district",
"display": { "en": "District", "sw": "Wilaya" }
},
{
"level_index": 3,
"name": "ward",
"display": { "en": "Ward", "sw": "Kata" }
}
]
},
"onboarding": {
Expand Down
2 changes: 2 additions & 0 deletions backend/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,8 @@
"deleted": "Your account and all associated data have been deleted. If you message us again, a new account will be created."
},
"escalation": {
"question": "Would you like to speak with an extension officer about this?",
"button_escalate": "Talk to Officer",
"confirmed": "Your issue has been transferred to extension service provider. Please wait for a response from them. For urgent issues please call:\n{eo_contacts}",
"confirmed_no_contacts": "Your issue has been transferred to extension service provider. Please wait for a response from them."
},
Expand Down
2 changes: 2 additions & 0 deletions backend/locales/sw.json
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,8 @@
"deleted": "Akaunti yako na data zote zinazohusiana zimefutwa. Ukitutumia ujumbe tena, akaunti mpya itaundwa."
},
"escalation": {
"question": "Je, ungependa kuunganishwa na afisa ugani kuhusu hili?",
"button_escalate": "Wasiliana na Afisa",
"confirmed": "Tatizo lako limehamishwa kwa mtoa huduma wa ugani. Tafadhali subiri jibu kutoka kwao. Kwa masuala ya dharura tafadhali piga simu:\n{eo_contacts}",
"confirmed_no_contacts": "Tatizo lako limehamishwa kwa mtoa huduma wa ugani. Tafadhali subiri jibu kutoka kwao."
},
Expand Down
2 changes: 2 additions & 0 deletions backend/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
devices,
knowledge_base,
messages,
messenger,
service_tokens,
whatsapp,
tickets,
Expand Down Expand Up @@ -112,6 +113,7 @@ async def lifespan(app: FastAPI):
app.include_router(messages.router, prefix="/api")
app.include_router(service_tokens.router, prefix="/api")
app.include_router(whatsapp.router, prefix="/api")
app.include_router(messenger.router, prefix="/api")
app.include_router(tickets.router, prefix="/api")
app.include_router(storage.router)
app.include_router(crop_types.router, prefix="/api")
Expand Down
135 changes: 114 additions & 21 deletions backend/routers/callbacks.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import asyncio
import logging
import uuid
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from sqlalchemy import func
Expand Down Expand Up @@ -256,22 +257,52 @@ async def ai_callback(
f"Sending AI answer to {ai_message.customer.phone_number}"
)

answer_response = whatsapp_service.send_message_with_tracking(
to_number=ai_message.customer.phone_number,
message_body=WhatsAppService.sanitize_whatsapp_content(
ai_response_text
),
message_id=ai_message.id,
db=db,
)
if ai_message.customer.phone_number.startswith(
"messenger:"
):
psid = (
ai_message.customer.phone_number.replace(
"messenger:", ""
)
)
from services.messenger_service import (
MessengerService,
)

# Update message with real Twilio SID
ai_message.message_sid = answer_response["sid"]
ai_message.delivery_status = DeliveryStatus.SENT
msgr_svc = MessengerService()
msgr_res = msgr_svc.send_message(
recipient_psid=psid,
text=ai_response_text,
)
ai_message.message_sid = msgr_res.get(
"message_id",
f"mid.msgr.{uuid.uuid4().hex[:16]}",
)
ai_message.delivery_status = (
DeliveryStatus.SENT
)
logger.info(
f"✓ AI answer sent via Messenger to {psid}"
)
else:
answer_response = whatsapp_service.send_message_with_tracking(
to_number=ai_message.customer.phone_number,
message_body=WhatsAppService.sanitize_whatsapp_content(
ai_response_text
),
message_id=ai_message.id,
db=db,
)

logger.info(
f"✓ AI answer sent successfully: {answer_response['sid']}"
)
# Update message with real Twilio SID
ai_message.message_sid = answer_response["sid"]
ai_message.delivery_status = (
DeliveryStatus.SENT
)

logger.info(
f"✓ AI answer sent successfully: {answer_response['sid']}"
)

# Step 2: Send confirmation template only if citations exist and escalation is enabled
# Citations indicate the response is from knowledge base
Expand All @@ -282,7 +313,16 @@ async def ai_callback(
and len(payload.output.citations) > 0
)

if settings.escalation_enabled and has_citations:
is_messenger = (
ai_message.customer.phone_number.startswith(
"messenger:"
)
)
if (
not is_messenger
and settings.escalation_enabled
and has_citations
):
# Select template based on customer's language
customer_lang = (
ai_message.customer.language_code
Expand All @@ -308,13 +348,59 @@ async def ai_callback(
f"Failed to send confirmation template (non-critical): {e}"
)
# Template failure is non-fatal
elif (
is_messenger
and settings.escalation_enabled
and has_citations
):
customer_lang = (
ai_message.customer.language_code
)
escalate_question = t(
"escalation.question", customer_lang
)
escalate_btn = t(
"escalation.button_escalate", customer_lang
)
try:
from services.messenger_service import (
MessengerService,
)

msgr_svc = MessengerService()
psid = ai_message.customer.phone_number.replace(
"messenger:", ""
)
msgr_svc.send_quick_replies(
recipient_psid=psid,
text=escalate_question,
options=[
{
"title": escalate_btn[:20],
"payload": (
settings.whatsapp_escalate_button_payload
),
}
],
)
logger.info(
"✓ Escalation quick reply sent via "
f"Messenger to {psid}"
)
except Exception as e:
logger.warning(
"Failed to send Messenger escalation "
f"quick reply (non-critical): {e}"
)
elif not settings.escalation_enabled:
logger.info(
"Skipping confirmation template: escalation is disabled in configuration"
"Skipping confirmation template: "
"escalation is disabled in configuration"
)
else:
logger.info(
"Skipping confirmation template: no citations in AI response"
"Skipping confirmation template: no "
"citations in AI response"
)

# CRITICAL: Only commit if WhatsApp send succeeded
Expand All @@ -331,15 +417,22 @@ async def ai_callback(
f"✓ AI message {ai_message.id} delivered and committed"
)

except (TwilioRestException, ValueError) as e:
# CRITICAL: Rollback on Twilio/validation failure
logger.error(f"✗ WhatsApp delivery failed: {e}")
except (
TwilioRestException,
ValueError,
Exception,
) as e:
# CRITICAL: Rollback on channel delivery failure
logger.error(
f"✗ Outbound delivery failed: {e}",
exc_info=True,
)
message_service.rollback_message(ai_message)

return {
"status": "error",
"job_id": payload.job_id,
"error": f"WhatsApp delivery failed: {str(e)}",
"error": f"Delivery failed: {str(e)}",
}

elif (
Expand Down
Loading
Loading