mirror of
https://dev.azure.com/globalhealthx/EMR/_git/helix-engage-server
synced 2026-04-11 10:07:22 +00:00
Compare commits
21 Commits
dev-mouli
...
44f1ec36e1
| Author | SHA1 | Date | |
|---|---|---|---|
| 44f1ec36e1 | |||
| 4bd08a9b02 | |||
| 0248c4cad1 | |||
| be505b8d1f | |||
| dbefa9675a | |||
| 9dc02e107a | |||
| c807cf737f | |||
| 96d0c32000 | |||
| 9665500b63 | |||
| 9f5935e417 | |||
| 898ff65951 | |||
| 7717536622 | |||
| 33dc8b5669 | |||
| ab65823c2e | |||
| 695f119c2b | |||
| eacfce6970 | |||
| 619e9ab405 | |||
| e6c8d950ea | |||
| aa41a2abb7 | |||
| 517b2661b0 | |||
| 76fa6f51de |
@@ -1,3 +1,14 @@
|
||||
# Build artifacts and host-installed deps — the multi-stage Dockerfile
|
||||
# rebuilds these inside the container for the target platform, so the
|
||||
# host copies must NOT leak in (would clobber linux/amd64 binaries
|
||||
# with darwin/arm64 ones).
|
||||
dist
|
||||
node_modules
|
||||
|
||||
# Secrets and local state
|
||||
.env
|
||||
.env.local
|
||||
.git
|
||||
src
|
||||
|
||||
# Local data dirs (Redis cache file, setup-state, etc.)
|
||||
data
|
||||
|
||||
5
.gitignore
vendored
5
.gitignore
vendored
@@ -37,3 +37,8 @@ lerna-debug.log*
|
||||
|
||||
# Environment
|
||||
.env
|
||||
|
||||
# Widget config — instance-specific, auto-generated on first boot.
|
||||
# Each environment mints its own HMAC-signed site key.
|
||||
data/widget.json
|
||||
data/widget-backups/
|
||||
|
||||
49
.woodpecker.yml
Normal file
49
.woodpecker.yml
Normal file
@@ -0,0 +1,49 @@
|
||||
# Woodpecker CI pipeline for Helix Engage Server (sidecar)
|
||||
#
|
||||
# Runs unit tests. Teams notification on completion.
|
||||
|
||||
when:
|
||||
- event: [push, manual]
|
||||
|
||||
steps:
|
||||
unit-tests:
|
||||
image: node:20
|
||||
commands:
|
||||
- npm ci
|
||||
- npm test -- --ci --forceExit
|
||||
|
||||
notify-teams:
|
||||
image: curlimages/curl
|
||||
commands:
|
||||
- |
|
||||
if [ "${CI_PIPELINE_STATUS}" = "success" ]; then
|
||||
ICON="✅"
|
||||
else
|
||||
ICON="❌"
|
||||
fi
|
||||
curl -s -X POST "${TEAMS_WEBHOOK}" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{
|
||||
\"type\": \"message\",
|
||||
\"attachments\": [{
|
||||
\"contentType\": \"application/vnd.microsoft.card.adaptive\",
|
||||
\"content\": {
|
||||
\"type\": \"AdaptiveCard\",
|
||||
\"version\": \"1.4\",
|
||||
\"body\": [
|
||||
{\"type\": \"TextBlock\", \"size\": \"Medium\", \"weight\": \"Bolder\", \"text\": \"${ICON} Helix Engage Server — Pipeline #${CI_PIPELINE_NUMBER}\"},
|
||||
{\"type\": \"TextBlock\", \"text\": \"**Branch:** ${CI_COMMIT_BRANCH}\", \"wrap\": true},
|
||||
{\"type\": \"TextBlock\", \"text\": \"**Status:** ${CI_PIPELINE_STATUS}\", \"wrap\": true},
|
||||
{\"type\": \"TextBlock\", \"text\": \"**Commit:** ${CI_COMMIT_MESSAGE}\", \"wrap\": true}
|
||||
],
|
||||
\"actions\": [
|
||||
{\"type\": \"Action.OpenUrl\", \"title\": \"View Pipeline\", \"url\": \"https://operations.healix360.net/repos/2/pipeline/${CI_PIPELINE_NUMBER}\"}
|
||||
]
|
||||
}
|
||||
}]
|
||||
}"
|
||||
environment:
|
||||
TEAMS_WEBHOOK:
|
||||
from_secret: teams_webhook
|
||||
when:
|
||||
- status: [success, failure]
|
||||
57
Dockerfile
57
Dockerfile
@@ -1,7 +1,58 @@
|
||||
# syntax=docker/dockerfile:1.7
|
||||
#
|
||||
# Multi-stage build for the helix-engage sidecar.
|
||||
#
|
||||
# Why multi-stage instead of "build on host, COPY dist + node_modules"?
|
||||
# The host (developer Mac, CI runner) is rarely the same architecture
|
||||
# as the target (linux/amd64 EC2 / VPS). Copying a host-built
|
||||
# node_modules brings darwin-arm64 native bindings (sharp, livekit,
|
||||
# fsevents, etc.) into the runtime image, which crash on first import.
|
||||
# This Dockerfile rebuilds inside the target-platform container so
|
||||
# native bindings are downloaded/compiled for the right arch.
|
||||
#
|
||||
# The build stage runs `npm ci` + `nest build`, then `npm prune` to
|
||||
# strip dev deps. The runtime stage carries forward only `dist/`,
|
||||
# the pruned `node_modules/`, and `package.json`.
|
||||
|
||||
# --- Builder stage ----------------------------------------------------------
|
||||
FROM node:22-slim AS builder
|
||||
WORKDIR /app
|
||||
|
||||
# Build deps for any native modules whose prebuilt binaries miss the
|
||||
# target arch. Kept minimal — node:22-slim already ships most of what's
|
||||
# needed for the deps in this project, but python/make/g++ are the
|
||||
# canonical "I might need to gyp-rebuild" trio.
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends \
|
||||
python3 \
|
||||
make \
|
||||
g++ \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Lockfile-only install first so this layer caches when only source
|
||||
# changes — much faster repeat builds.
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci --no-audit --no-fund --loglevel=verbose
|
||||
|
||||
# Source + build config
|
||||
COPY tsconfig.json tsconfig.build.json nest-cli.json ./
|
||||
COPY src ./src
|
||||
|
||||
RUN npm run build
|
||||
|
||||
# Strip dev dependencies so the runtime image stays small.
|
||||
RUN npm prune --omit=dev
|
||||
|
||||
|
||||
# --- Runtime stage ----------------------------------------------------------
|
||||
FROM node:22-slim
|
||||
WORKDIR /app
|
||||
COPY dist ./dist
|
||||
COPY node_modules ./node_modules
|
||||
COPY package.json ./
|
||||
|
||||
# Bring across only what the runtime needs. Source, dev deps, build
|
||||
# tooling all stay in the builder stage and get discarded.
|
||||
COPY --from=builder /app/dist ./dist
|
||||
COPY --from=builder /app/node_modules ./node_modules
|
||||
COPY --from=builder /app/package.json ./
|
||||
|
||||
EXPOSE 4100
|
||||
CMD ["node", "dist/main.js"]
|
||||
|
||||
3217
package-lock.json
generated
3217
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
41
public/test.html
Normal file
41
public/test.html
Normal file
@@ -0,0 +1,41 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Global Hospital — Widget Test</title>
|
||||
<style>
|
||||
body { font-family: -apple-system, sans-serif; max-width: 800px; margin: 0 auto; padding: 40px; color: #1f2937; }
|
||||
h1 { font-size: 28px; margin-bottom: 8px; }
|
||||
p { color: #6b7280; line-height: 1.6; }
|
||||
.hero { background: #f0f9ff; border-radius: 12px; padding: 40px; margin: 40px 0; }
|
||||
.hero h2 { color: #1e40af; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>🏥 Global Hospital, Bangalore</h1>
|
||||
<p>Welcome to Global Hospital — Bangalore's leading multi-specialty healthcare provider.</p>
|
||||
|
||||
<div class="hero">
|
||||
<h2>Book Your Appointment Online</h2>
|
||||
<p>Click the chat bubble in the bottom-right corner to talk to our AI assistant, book an appointment, or request a callback.</p>
|
||||
</div>
|
||||
|
||||
<h3>Our Departments</h3>
|
||||
<ul>
|
||||
<li>Cardiology</li>
|
||||
<li>Orthopedics</li>
|
||||
<li>Gynecology</li>
|
||||
<li>ENT</li>
|
||||
<li>General Medicine</li>
|
||||
</ul>
|
||||
|
||||
<p style="margin-top: 40px; font-size: 12px; color: #9ca3af;">
|
||||
This is a test page for the Helix Engage website widget.
|
||||
The widget loads from the sidecar and renders in a shadow DOM.
|
||||
</p>
|
||||
|
||||
<!-- Replace SITE_KEY with the generated key -->
|
||||
<script src="http://localhost:4100/widget.js" data-key="8197d39c9ad946ef.31e3b1f492a7380f77ea0c90d2f86d5d4b1ac8f70fd01423ac3d85b87d9aa511"></script>
|
||||
</body>
|
||||
</html>
|
||||
463
public/widget.js
Normal file
463
public/widget.js
Normal file
File diff suppressed because one or more lines are too long
225
src/__fixtures__/ozonetel-payloads.ts
Normal file
225
src/__fixtures__/ozonetel-payloads.ts
Normal file
@@ -0,0 +1,225 @@
|
||||
/**
|
||||
* Ozonetel API fixtures — accurate to the official docs (2026-04-10).
|
||||
*
|
||||
* These represent the EXACT shapes Ozonetel sends/returns. Used by
|
||||
* unit tests to mock Ozonetel API responses and replay webhook payloads
|
||||
* without a live Ozonetel account.
|
||||
*
|
||||
* Source: https://docs.ozonetel.com/reference
|
||||
*/
|
||||
|
||||
// ─── Webhook "URL to Push" payloads ──────────────────────────────
|
||||
// Ozonetel POSTs these to our /webhooks/ozonetel/missed-call endpoint.
|
||||
// Field names match the CDR detail record (PascalCase).
|
||||
|
||||
export const WEBHOOK_INBOUND_ANSWERED = {
|
||||
CallerID: '9949879837',
|
||||
Status: 'Answered',
|
||||
Type: 'InBound',
|
||||
StartTime: '2026-04-09 14:30:00',
|
||||
EndTime: '2026-04-09 14:34:00',
|
||||
CallDuration: '00:04:00',
|
||||
AgentName: 'global',
|
||||
AudioFile: 'https://s3.ap-southeast-1.amazonaws.com/recordings.kookoo.in/global_healthx/20260409_143000.mp3',
|
||||
monitorUCID: '31712345678901234',
|
||||
Disposition: 'General Enquiry',
|
||||
HangupBy: 'CustomerHangup',
|
||||
DID: '918041763400',
|
||||
CampaignName: 'Inbound_918041763400',
|
||||
};
|
||||
|
||||
export const WEBHOOK_INBOUND_MISSED = {
|
||||
CallerID: '6309248884',
|
||||
Status: 'NotAnswered',
|
||||
Type: 'InBound',
|
||||
StartTime: '2026-04-09 15:00:00',
|
||||
EndTime: '2026-04-09 15:00:30',
|
||||
CallDuration: '00:00:00',
|
||||
AgentName: '',
|
||||
AudioFile: '',
|
||||
monitorUCID: '31712345678905678',
|
||||
Disposition: '',
|
||||
HangupBy: 'CustomerHangup',
|
||||
DID: '918041763400',
|
||||
CampaignName: 'Inbound_918041763400',
|
||||
};
|
||||
|
||||
export const WEBHOOK_OUTBOUND_ANSWERED = {
|
||||
CallerID: '',
|
||||
Status: 'Answered',
|
||||
Type: 'OutBound',
|
||||
StartTime: '2026-04-09 16:00:00',
|
||||
EndTime: '2026-04-09 16:03:00',
|
||||
CallDuration: '00:03:00',
|
||||
AgentName: 'global',
|
||||
AudioFile: 'https://s3.ap-southeast-1.amazonaws.com/recordings.kookoo.in/global_healthx/20260409_160000.mp3',
|
||||
monitorUCID: '31712345678909999',
|
||||
Disposition: 'Appointment Booked',
|
||||
HangupBy: 'AgentHangup',
|
||||
DID: '918041763400',
|
||||
CampaignName: 'Inbound_918041763400',
|
||||
};
|
||||
|
||||
export const WEBHOOK_OUTBOUND_NO_ANSWER = {
|
||||
CallerID: '',
|
||||
Status: 'NotAnswered',
|
||||
Type: 'OutBound',
|
||||
StartTime: '2026-04-09 16:10:00',
|
||||
EndTime: '2026-04-09 16:10:45',
|
||||
CallDuration: '00:00:00',
|
||||
AgentName: 'global',
|
||||
AudioFile: '',
|
||||
monitorUCID: '31712345678908888',
|
||||
Disposition: '',
|
||||
HangupBy: 'Timeout',
|
||||
DID: '918041763400',
|
||||
CampaignName: 'Inbound_918041763400',
|
||||
};
|
||||
|
||||
// ─── Agent Authentication ────────────────────────────────────────
|
||||
// POST /CAServices/AgentAuthenticationV2/index.php
|
||||
|
||||
export const AGENT_AUTH_LOGIN_SUCCESS = {
|
||||
status: 'success',
|
||||
message: 'Agent global logged in successfully',
|
||||
};
|
||||
|
||||
export const AGENT_AUTH_LOGIN_ALREADY = {
|
||||
status: 'error',
|
||||
message: 'Agent has already logged in',
|
||||
};
|
||||
|
||||
export const AGENT_AUTH_LOGOUT_SUCCESS = {
|
||||
status: 'success',
|
||||
message: 'Agent global logged out successfully',
|
||||
};
|
||||
|
||||
export const AGENT_AUTH_INVALID = {
|
||||
status: 'error',
|
||||
message: 'Invalid Authentication',
|
||||
};
|
||||
|
||||
// ─── Set Disposition ─────────────────────────────────────────────
|
||||
// POST /ca_apis/DispositionAPIV2 (action=Set)
|
||||
|
||||
export const DISPOSITION_SET_DURING_CALL = {
|
||||
status: 'Success',
|
||||
message: 'Disposition Queued Successfully',
|
||||
};
|
||||
|
||||
export const DISPOSITION_SET_AFTER_CALL = {
|
||||
details: 'Disposition saved successfully',
|
||||
status: 'Success',
|
||||
};
|
||||
|
||||
export const DISPOSITION_SET_UPDATE = {
|
||||
status: 'Success',
|
||||
message: 'Disposition Updated Successfully',
|
||||
};
|
||||
|
||||
export const DISPOSITION_INVALID_UCID = {
|
||||
status: 'Fail',
|
||||
message: 'Invalid ucid',
|
||||
};
|
||||
|
||||
export const DISPOSITION_INVALID_AGENT = {
|
||||
status: 'Fail',
|
||||
message: 'Invalid Agent ID',
|
||||
};
|
||||
|
||||
// ─── CDR Detail Record ──────────────────────────────────────────
|
||||
// GET /ca_reports/fetchCDRDetails
|
||||
|
||||
export const CDR_DETAIL_RECORD = {
|
||||
AgentDialStatus: 'answered',
|
||||
AgentID: 'global',
|
||||
AgentName: 'global',
|
||||
CallAudio: 'https://s3.ap-southeast-1.amazonaws.com/recordings.kookoo.in/global_healthx/20260409_143000.mp3',
|
||||
CallDate: '2026-04-09',
|
||||
CallID: 31733467784618213,
|
||||
CallerConfAudioFile: '',
|
||||
CallerID: '9949879837',
|
||||
CampaignName: 'Inbound_918041763400',
|
||||
Comments: '',
|
||||
ConferenceDuration: '00:00:00',
|
||||
CustomerDialStatus: 'answered',
|
||||
CustomerRingTime: '00:00:05',
|
||||
DID: '918041763400',
|
||||
DialOutName: '',
|
||||
DialStatus: 'answered',
|
||||
DialedNumber: '523590',
|
||||
Disposition: 'General Enquiry',
|
||||
Duration: '00:04:00',
|
||||
DynamicDID: '',
|
||||
E164: '+919949879837',
|
||||
EndTime: '14:34:00',
|
||||
Event: 'AgentDial',
|
||||
HandlingTime: '00:04:05',
|
||||
HangupBy: 'CustomerHangup',
|
||||
HoldDuration: '00:00:00',
|
||||
Location: 'Bangalore',
|
||||
PickupTime: '14:30:05',
|
||||
Rating: 0,
|
||||
RatingComments: '',
|
||||
Skill: 'General',
|
||||
StartTime: '14:30:00',
|
||||
Status: 'Answered',
|
||||
TalkTime: '00:04:00',
|
||||
TimeToAnswer: '00:00:05',
|
||||
TransferType: '',
|
||||
TransferredTo: '',
|
||||
Type: 'InBound',
|
||||
UCID: 31712345678901234,
|
||||
UUI: '',
|
||||
WrapUpEndTime: '14:34:10',
|
||||
WrapUpStartTime: '14:34:00',
|
||||
WrapupDuration: '00:00:10',
|
||||
};
|
||||
|
||||
export const CDR_RESPONSE_SUCCESS = {
|
||||
status: 'success',
|
||||
message: 'success',
|
||||
details: [CDR_DETAIL_RECORD],
|
||||
};
|
||||
|
||||
export const CDR_RESPONSE_EMPTY = {
|
||||
status: 'success',
|
||||
message: 'success',
|
||||
details: [],
|
||||
};
|
||||
|
||||
// ─── Abandon / Missed Calls ─────────────────────────────────────
|
||||
// GET /ca_apis/abandonCalls
|
||||
|
||||
export const ABANDON_CALL_RECORD = {
|
||||
monitorUCID: 31712345678905678,
|
||||
type: 'InBound',
|
||||
status: 'NotAnswered',
|
||||
campaign: 'Inbound_918041763400',
|
||||
callerID: '6309248884',
|
||||
did: '918041763400',
|
||||
skillID: '',
|
||||
skill: '',
|
||||
agentID: 'global',
|
||||
agent: 'global',
|
||||
hangupBy: 'CustomerHangup',
|
||||
callTime: '2026-04-09 15:00:33',
|
||||
};
|
||||
|
||||
export const ABANDON_RESPONSE_SUCCESS = {
|
||||
status: 'success',
|
||||
message: [ABANDON_CALL_RECORD],
|
||||
};
|
||||
|
||||
export const ABANDON_RESPONSE_EMPTY = {
|
||||
status: 'success',
|
||||
message: [],
|
||||
};
|
||||
|
||||
// ─── Get Disposition List ────────────────────────────────────────
|
||||
// POST /ca_apis/DispositionAPIV2 (action=get)
|
||||
|
||||
export const DISPOSITION_LIST_SUCCESS = {
|
||||
status: 'Success',
|
||||
details: 'General Enquiry, Appointment Booked, Follow Up, Not Interested, Wrong Number, ',
|
||||
};
|
||||
@@ -6,6 +6,8 @@ import type { LanguageModel } from 'ai';
|
||||
import { z } from 'zod';
|
||||
import { PlatformGraphqlService } from '../platform/platform-graphql.service';
|
||||
import { createAiModel, isAiConfigured } from './ai-provider';
|
||||
import { AiConfigService } from '../config/ai-config.service';
|
||||
import { DOCTOR_VISIT_SLOTS_FRAGMENT, normalizeDoctors } from '../shared/doctor-utils';
|
||||
|
||||
type ChatRequest = {
|
||||
message: string;
|
||||
@@ -23,14 +25,19 @@ export class AiChatController {
|
||||
constructor(
|
||||
private config: ConfigService,
|
||||
private platform: PlatformGraphqlService,
|
||||
private aiConfig: AiConfigService,
|
||||
) {
|
||||
this.aiModel = createAiModel(config);
|
||||
const cfg = aiConfig.getConfig();
|
||||
this.aiModel = createAiModel({
|
||||
provider: cfg.provider,
|
||||
model: cfg.model,
|
||||
anthropicApiKey: config.get<string>('ai.anthropicApiKey'),
|
||||
openaiApiKey: config.get<string>('ai.openaiApiKey'),
|
||||
});
|
||||
if (!this.aiModel) {
|
||||
this.logger.warn('AI not configured — chat uses fallback');
|
||||
} else {
|
||||
const provider = config.get<string>('ai.provider') ?? 'openai';
|
||||
const model = config.get<string>('ai.model') ?? 'gpt-4o-mini';
|
||||
this.logger.log(`AI configured: ${provider}/${model}`);
|
||||
this.logger.log(`AI configured: ${cfg.provider}/${cfg.model}`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -120,7 +127,13 @@ export class AiChatController {
|
||||
undefined, auth,
|
||||
),
|
||||
platformService.queryWithAuth<any>(
|
||||
`{ agents(first: 20) { edges { node { id name ozonetelagentid npsscore maxidleminutes minnpsthreshold minconversionpercent } } } }`,
|
||||
// Field names are label-derived camelCase on the
|
||||
// current platform schema. The legacy lowercase
|
||||
// names (ozonetelagentid etc.) only still exist on
|
||||
// staging workspaces that were synced from an
|
||||
// older SDK. See agent-config.service.ts for the
|
||||
// canonical explanation.
|
||||
`{ agents(first: 20) { edges { node { id name ozonetelAgentId npsScore maxIdleMinutes minNpsThreshold minConversion } } } }`,
|
||||
undefined, auth,
|
||||
),
|
||||
platformService.queryWithAuth<any>(
|
||||
@@ -137,7 +150,7 @@ export class AiChatController {
|
||||
const agentMetrics = agents
|
||||
.filter((a: any) => !agentName || a.name.toLowerCase().includes(agentName.toLowerCase()))
|
||||
.map((agent: any) => {
|
||||
const agentCalls = calls.filter((c: any) => c.agentName === agent.name || c.agentName === agent.ozonetelagentid);
|
||||
const agentCalls = calls.filter((c: any) => c.agentName === agent.name || c.agentName === agent.ozonetelAgentId);
|
||||
const totalCalls = agentCalls.length;
|
||||
const missed = agentCalls.filter((c: any) => c.callStatus === 'MISSED').length;
|
||||
const completed = agentCalls.filter((c: any) => c.callStatus === 'COMPLETED').length;
|
||||
@@ -156,12 +169,12 @@ export class AiChatController {
|
||||
conversionRate: `${conversionRate}%`,
|
||||
assignedLeads: agentLeads.length,
|
||||
pendingFollowUps,
|
||||
npsScore: agent.npsscore,
|
||||
maxIdleMinutes: agent.maxidleminutes,
|
||||
minNpsThreshold: agent.minnpsthreshold,
|
||||
minConversionPercent: agent.minconversionpercent,
|
||||
belowNpsThreshold: agent.minnpsthreshold && (agent.npsscore ?? 100) < agent.minnpsthreshold,
|
||||
belowConversionThreshold: agent.minconversionpercent && conversionRate < agent.minconversionpercent,
|
||||
npsScore: agent.npsScore,
|
||||
maxIdleMinutes: agent.maxIdleMinutes,
|
||||
minNpsThreshold: agent.minNpsThreshold,
|
||||
minConversionPercent: agent.minConversion,
|
||||
belowNpsThreshold: agent.minNpsThreshold && (agent.npsScore ?? 100) < agent.minNpsThreshold,
|
||||
belowConversionThreshold: agent.minConversion && conversionRate < agent.minConversion,
|
||||
};
|
||||
});
|
||||
|
||||
@@ -258,7 +271,7 @@ export class AiChatController {
|
||||
inputSchema: z.object({}),
|
||||
execute: async () => {
|
||||
const data = await platformService.queryWithAuth<any>(
|
||||
`{ calls(first: 100, filter: { callStatus: { eq: MISSED }, callbackstatus: { eq: PENDING_CALLBACK } }) { edges { node { id callerNumber { primaryPhoneNumber } startedAt agentName sla } } } }`,
|
||||
`{ calls(first: 100, filter: { callStatus: { eq: MISSED }, callbackStatus: { eq: PENDING_CALLBACK } }) { edges { node { id callerNumber { primaryPhoneNumber } startedAt agentName sla } } } }`,
|
||||
undefined, auth,
|
||||
);
|
||||
const breached = data.calls.edges
|
||||
@@ -344,13 +357,13 @@ export class AiChatController {
|
||||
const data = await platformService.queryWithAuth<any>(
|
||||
`{ doctors(first: 10) { edges { node {
|
||||
id fullName { firstName lastName }
|
||||
department specialty visitingHours
|
||||
department specialty
|
||||
consultationFeeNew { amountMicros currencyCode }
|
||||
clinic { clinicName }
|
||||
${DOCTOR_VISIT_SLOTS_FRAGMENT}
|
||||
} } } }`,
|
||||
undefined, auth,
|
||||
);
|
||||
const doctors = data.doctors.edges.map((e: any) => e.node);
|
||||
const doctors = normalizeDoctors(data.doctors.edges.map((e: any) => e.node));
|
||||
// Strip "Dr." prefix and search flexibly
|
||||
const search = doctorName.toLowerCase().replace(/^dr\.?\s*/i, '').trim();
|
||||
const searchWords = search.split(/\s+/);
|
||||
@@ -556,25 +569,28 @@ export class AiChatController {
|
||||
try {
|
||||
const docData = await this.platform.queryWithAuth<any>(
|
||||
`{ doctors(first: 20) { edges { node {
|
||||
fullName { firstName lastName } department specialty visitingHours
|
||||
id fullName { firstName lastName } department specialty
|
||||
consultationFeeNew { amountMicros currencyCode }
|
||||
clinic { clinicName }
|
||||
${DOCTOR_VISIT_SLOTS_FRAGMENT}
|
||||
} } } }`,
|
||||
undefined, auth,
|
||||
);
|
||||
const doctors = docData.doctors.edges.map((e: any) => e.node);
|
||||
const doctors = normalizeDoctors(docData.doctors.edges.map((e: any) => e.node));
|
||||
if (doctors.length) {
|
||||
sections.push('\n## DOCTORS');
|
||||
for (const d of doctors) {
|
||||
const name = `Dr. ${d.fullName?.firstName ?? ''} ${d.fullName?.lastName ?? ''}`.trim();
|
||||
const fee = d.consultationFeeNew ? `₹${d.consultationFeeNew.amountMicros / 1_000_000}` : '';
|
||||
const clinic = d.clinic?.clinicName ?? '';
|
||||
// List ALL clinics this doctor visits in the KB so
|
||||
// the AI can answer questions like "where can I see
|
||||
// Dr. X" without needing a follow-up tool call.
|
||||
const clinics = d.clinics.map((c) => c.clinicName).join(', ');
|
||||
sections.push(`### ${name}`);
|
||||
sections.push(` Department: ${d.department ?? 'N/A'}`);
|
||||
sections.push(` Specialty: ${d.specialty ?? 'N/A'}`);
|
||||
if (d.visitingHours) sections.push(` Hours: ${d.visitingHours}`);
|
||||
if (fee) sections.push(` Consultation fee: ${fee}`);
|
||||
if (clinic) sections.push(` Clinic: ${clinic}`);
|
||||
if (clinics) sections.push(` Clinics: ${clinics}`);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
@@ -645,24 +661,15 @@ export class AiChatController {
|
||||
}
|
||||
|
||||
private buildSupervisorSystemPrompt(): string {
|
||||
return `You are an AI assistant for supervisors at Global Hospital's call center (Helix Engage).
|
||||
You help supervisors monitor team performance, identify issues, and make data-driven decisions.
|
||||
return this.aiConfig.renderPrompt('supervisorChat', {
|
||||
hospitalName: this.getHospitalName(),
|
||||
});
|
||||
}
|
||||
|
||||
## YOUR CAPABILITIES
|
||||
You have access to tools that query real-time data:
|
||||
- **Agent performance**: call counts, conversion rates, NPS scores, idle time, pending follow-ups
|
||||
- **Campaign stats**: lead counts, conversion rates per campaign, platform breakdown
|
||||
- **Call summary**: total calls, inbound/outbound split, missed call rate, disposition breakdown
|
||||
- **SLA breaches**: missed calls that haven't been called back within the SLA threshold
|
||||
|
||||
## RULES
|
||||
1. ALWAYS use tools to fetch data before answering. NEVER guess or fabricate performance numbers.
|
||||
2. Be specific — include actual numbers from the tool response, not vague qualifiers.
|
||||
3. When comparing agents, use their configured thresholds (minConversionPercent, minNpsThreshold, maxIdleMinutes) and team averages. Let the data determine who is underperforming — do not assume.
|
||||
4. Be concise — supervisors want quick answers. Use bullet points.
|
||||
5. When recommending actions, ground them in the data returned by tools.
|
||||
6. If asked about trends, use the call summary tool with different periods.
|
||||
7. Do not use any agent name in a negative context unless the data explicitly supports it.`;
|
||||
// Best-effort hospital name lookup for the AI prompts. Falls back
|
||||
// to a generic label so prompt rendering never throws.
|
||||
private getHospitalName(): string {
|
||||
return process.env.HOSPITAL_NAME ?? 'the hospital';
|
||||
}
|
||||
|
||||
private buildRulesSystemPrompt(currentConfig: any): string {
|
||||
@@ -712,25 +719,10 @@ ${configJson}
|
||||
}
|
||||
|
||||
private buildSystemPrompt(kb: string): string {
|
||||
return `You are an AI assistant for call center agents at Global Hospital, Bangalore.
|
||||
You help agents answer questions about patients, doctors, appointments, clinics, and hospital services during live calls.
|
||||
|
||||
IMPORTANT — ANSWER FROM KNOWLEDGE BASE FIRST:
|
||||
The knowledge base below contains REAL clinic locations, timings, doctor details, health packages, and insurance partners.
|
||||
When asked about clinic timings, locations, doctor availability, packages, or insurance — ALWAYS check the knowledge base FIRST before saying you don't know.
|
||||
Example: "What are the Koramangala timings?" → Look for "Koramangala" in the Clinics section below.
|
||||
|
||||
RULES:
|
||||
1. For patient-specific questions (history, appointments, calls), use the lookup tools. NEVER guess patient data.
|
||||
2. For doctor details beyond what's in the KB, use the lookup_doctor tool.
|
||||
3. For clinic info, timings, packages, insurance → answer directly from the knowledge base below.
|
||||
4. If you truly cannot find the answer in the KB or via tools, say "I couldn't find that in our system."
|
||||
5. Be concise — agents are on live calls. Under 100 words unless asked for detail.
|
||||
6. NEVER give medical advice, diagnosis, or treatment recommendations.
|
||||
7. Format with bullet points for easy scanning.
|
||||
|
||||
KNOWLEDGE BASE (this is real data from our system):
|
||||
${kb}`;
|
||||
return this.aiConfig.renderPrompt('ccAgentHelper', {
|
||||
hospitalName: this.getHospitalName(),
|
||||
knowledgeBase: kb,
|
||||
});
|
||||
}
|
||||
|
||||
private async chatWithTools(userMessage: string, auth: string) {
|
||||
@@ -844,16 +836,15 @@ ${kb}`;
|
||||
`{ doctors(first: 10) { edges { node {
|
||||
id name fullName { firstName lastName }
|
||||
department specialty qualifications yearsOfExperience
|
||||
visitingHours
|
||||
consultationFeeNew { amountMicros currencyCode }
|
||||
consultationFeeFollowUp { amountMicros currencyCode }
|
||||
active registrationNumber
|
||||
clinic { id name clinicName }
|
||||
${DOCTOR_VISIT_SLOTS_FRAGMENT}
|
||||
} } } }`,
|
||||
undefined, auth,
|
||||
);
|
||||
|
||||
const doctors = data.doctors.edges.map((e: any) => e.node);
|
||||
const doctors = normalizeDoctors(data.doctors.edges.map((e: any) => e.node));
|
||||
const search = doctorName.toLowerCase();
|
||||
const matched = doctors.filter((d: any) => {
|
||||
const full = `${d.fullName?.firstName ?? ''} ${d.fullName?.lastName ?? ''} ${d.name ?? ''}`.toLowerCase();
|
||||
@@ -866,7 +857,13 @@ ${kb}`;
|
||||
found: true,
|
||||
doctors: matched.map((d: any) => ({
|
||||
...d,
|
||||
clinicName: d.clinic?.clinicName ?? d.clinic?.name ?? 'N/A',
|
||||
// Multi-clinic doctors show as
|
||||
// "Koramangala / Indiranagar" so the
|
||||
// model has the full picture without
|
||||
// a follow-up tool call.
|
||||
clinicName: d.clinics.length > 0
|
||||
? d.clinics.map((c: { clinicName: string }) => c.clinicName).join(' / ')
|
||||
: 'N/A',
|
||||
feeNewFormatted: d.consultationFeeNew ? `₹${d.consultationFeeNew.amountMicros / 1_000_000}` : 'N/A',
|
||||
feeFollowUpFormatted: d.consultationFeeFollowUp ? `₹${d.consultationFeeFollowUp.amountMicros / 1_000_000}` : 'N/A',
|
||||
})),
|
||||
@@ -890,13 +887,13 @@ ${kb}`;
|
||||
try {
|
||||
const doctors = await this.platform.queryWithAuth<any>(
|
||||
`{ doctors(first: 10) { edges { node {
|
||||
name fullName { firstName lastName } department specialty visitingHours
|
||||
id name fullName { firstName lastName } department specialty
|
||||
consultationFeeNew { amountMicros currencyCode }
|
||||
clinic { name clinicName }
|
||||
${DOCTOR_VISIT_SLOTS_FRAGMENT}
|
||||
} } } }`,
|
||||
undefined, auth,
|
||||
);
|
||||
const docs = doctors.doctors.edges.map((e: any) => e.node);
|
||||
const docs = normalizeDoctors(doctors.doctors.edges.map((e: any) => e.node));
|
||||
const l = msg.toLowerCase();
|
||||
|
||||
const matchedDoc = docs.find((d: any) => {
|
||||
@@ -906,7 +903,7 @@ ${kb}`;
|
||||
if (matchedDoc) {
|
||||
const fee = matchedDoc.consultationFeeNew ? `₹${matchedDoc.consultationFeeNew.amountMicros / 1_000_000}` : '';
|
||||
const clinic = matchedDoc.clinic?.clinicName ?? '';
|
||||
return `Dr. ${matchedDoc.fullName?.lastName ?? matchedDoc.name} (${matchedDoc.department ?? matchedDoc.specialty}): ${matchedDoc.visitingHours ?? 'hours not set'}${clinic ? ` at ${clinic}` : ''}${fee ? `. Fee: ${fee}` : ''}.`;
|
||||
return `Dr. ${matchedDoc.fullName?.lastName ?? matchedDoc.name} (${matchedDoc.department ?? matchedDoc.specialty}): ${matchedDoc.visitingHours || 'hours not set'}${clinic ? ` at ${clinic}` : ''}${fee ? `. Fee: ${fee}` : ''}.`;
|
||||
}
|
||||
|
||||
if (l.includes('doctor') || l.includes('available')) {
|
||||
|
||||
@@ -4,6 +4,7 @@ import { generateObject } from 'ai';
|
||||
import type { LanguageModel } from 'ai';
|
||||
import { z } from 'zod';
|
||||
import { createAiModel } from './ai-provider';
|
||||
import { AiConfigService } from '../config/ai-config.service';
|
||||
|
||||
type LeadContext = {
|
||||
firstName?: string;
|
||||
@@ -32,8 +33,17 @@ export class AiEnrichmentService {
|
||||
private readonly logger = new Logger(AiEnrichmentService.name);
|
||||
private readonly aiModel: LanguageModel | null;
|
||||
|
||||
constructor(private config: ConfigService) {
|
||||
this.aiModel = createAiModel(config);
|
||||
constructor(
|
||||
private config: ConfigService,
|
||||
private aiConfig: AiConfigService,
|
||||
) {
|
||||
const cfg = aiConfig.getConfig();
|
||||
this.aiModel = createAiModel({
|
||||
provider: cfg.provider,
|
||||
model: cfg.model,
|
||||
anthropicApiKey: config.get<string>('ai.anthropicApiKey'),
|
||||
openaiApiKey: config.get<string>('ai.openaiApiKey'),
|
||||
});
|
||||
if (!this.aiModel) {
|
||||
this.logger.warn('AI not configured — enrichment uses fallback');
|
||||
}
|
||||
@@ -56,19 +66,15 @@ export class AiEnrichmentService {
|
||||
const { object } = await generateObject({
|
||||
model: this.aiModel!,
|
||||
schema: enrichmentSchema,
|
||||
prompt: `You are an AI assistant for a hospital call center.
|
||||
An inbound call is coming in from a lead. Summarize their history and suggest what the call center agent should do.
|
||||
|
||||
Lead details:
|
||||
- Name: ${lead.firstName ?? 'Unknown'} ${lead.lastName ?? ''}
|
||||
- Source: ${lead.leadSource ?? 'Unknown'}
|
||||
- Interested in: ${lead.interestedService ?? 'Unknown'}
|
||||
- Current status: ${lead.leadStatus ?? 'Unknown'}
|
||||
- Lead age: ${daysSince} days
|
||||
- Contact attempts: ${lead.contactAttempts ?? 0}
|
||||
|
||||
Recent activity:
|
||||
${activitiesText}`,
|
||||
prompt: this.aiConfig.renderPrompt('leadEnrichment', {
|
||||
leadName: `${lead.firstName ?? 'Unknown'} ${lead.lastName ?? ''}`.trim(),
|
||||
leadSource: lead.leadSource ?? 'Unknown',
|
||||
interestedService: lead.interestedService ?? 'Unknown',
|
||||
leadStatus: lead.leadStatus ?? 'Unknown',
|
||||
daysSince,
|
||||
contactAttempts: lead.contactAttempts ?? 0,
|
||||
activities: activitiesText,
|
||||
}),
|
||||
});
|
||||
|
||||
this.logger.log(`AI enrichment generated for lead ${lead.firstName} ${lead.lastName}`);
|
||||
|
||||
@@ -1,26 +1,30 @@
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { anthropic } from '@ai-sdk/anthropic';
|
||||
import { openai } from '@ai-sdk/openai';
|
||||
import type { LanguageModel } from 'ai';
|
||||
|
||||
export function createAiModel(config: ConfigService): LanguageModel | null {
|
||||
const provider = config.get<string>('ai.provider') ?? 'openai';
|
||||
const model = config.get<string>('ai.model') ?? 'gpt-4o-mini';
|
||||
// Pure factory — no DI. Caller passes provider/model (admin-editable, from
|
||||
// AiConfigService) and the API key (env-driven, ops-owned). Decoupling means
|
||||
// the model can be re-built per request without re-instantiating the caller
|
||||
// service, so admin updates to provider/model take effect immediately.
|
||||
|
||||
if (provider === 'anthropic') {
|
||||
const apiKey = config.get<string>('ai.anthropicApiKey');
|
||||
if (!apiKey) return null;
|
||||
return anthropic(model);
|
||||
export type AiProviderOpts = {
|
||||
provider: string;
|
||||
model: string;
|
||||
anthropicApiKey?: string;
|
||||
openaiApiKey?: string;
|
||||
};
|
||||
|
||||
export function createAiModel(opts: AiProviderOpts): LanguageModel | null {
|
||||
if (opts.provider === 'anthropic') {
|
||||
if (!opts.anthropicApiKey) return null;
|
||||
return anthropic(opts.model);
|
||||
}
|
||||
|
||||
// Default to openai
|
||||
const apiKey = config.get<string>('ai.openaiApiKey');
|
||||
if (!apiKey) return null;
|
||||
return openai(model);
|
||||
if (!opts.openaiApiKey) return null;
|
||||
return openai(opts.model);
|
||||
}
|
||||
|
||||
export function isAiConfigured(config: ConfigService): boolean {
|
||||
const provider = config.get<string>('ai.provider') ?? 'openai';
|
||||
if (provider === 'anthropic') return !!config.get<string>('ai.anthropicApiKey');
|
||||
return !!config.get<string>('ai.openaiApiKey');
|
||||
export function isAiConfigured(opts: AiProviderOpts): boolean {
|
||||
if (opts.provider === 'anthropic') return !!opts.anthropicApiKey;
|
||||
return !!opts.openaiApiKey;
|
||||
}
|
||||
|
||||
@@ -19,6 +19,10 @@ import { EventsModule } from './events/events.module';
|
||||
import { CallerResolutionModule } from './caller/caller-resolution.module';
|
||||
import { RulesEngineModule } from './rules-engine/rules-engine.module';
|
||||
import { ConfigThemeModule } from './config/config-theme.module';
|
||||
import { WidgetModule } from './widget/widget.module';
|
||||
import { TeamModule } from './team/team.module';
|
||||
import { MasterdataModule } from './masterdata/masterdata.module';
|
||||
import { TelephonyRegistrationService } from './telephony-registration.service';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
@@ -44,6 +48,10 @@ import { ConfigThemeModule } from './config/config-theme.module';
|
||||
CallerResolutionModule,
|
||||
RulesEngineModule,
|
||||
ConfigThemeModule,
|
||||
WidgetModule,
|
||||
TeamModule,
|
||||
MasterdataModule,
|
||||
],
|
||||
providers: [TelephonyRegistrationService],
|
||||
})
|
||||
export class AppModule {}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { PlatformGraphqlService } from '../platform/platform-graphql.service';
|
||||
import { TelephonyConfigService } from '../config/telephony-config.service';
|
||||
|
||||
export type AgentConfig = {
|
||||
id: string;
|
||||
@@ -16,15 +16,20 @@ export type AgentConfig = {
|
||||
export class AgentConfigService {
|
||||
private readonly logger = new Logger(AgentConfigService.name);
|
||||
private readonly cache = new Map<string, AgentConfig>();
|
||||
private readonly sipDomain: string;
|
||||
private readonly sipWsPort: string;
|
||||
|
||||
constructor(
|
||||
private platform: PlatformGraphqlService,
|
||||
private config: ConfigService,
|
||||
) {
|
||||
this.sipDomain = config.get<string>('sip.domain', 'blr-pub-rtc4.ozonetel.com');
|
||||
this.sipWsPort = config.get<string>('sip.wsPort', '444');
|
||||
private telephony: TelephonyConfigService,
|
||||
) {}
|
||||
|
||||
private get sipDomain(): string {
|
||||
return this.telephony.getConfig().sip.domain || 'blr-pub-rtc4.ozonetel.com';
|
||||
}
|
||||
private get sipWsPort(): string {
|
||||
return this.telephony.getConfig().sip.wsPort || '444';
|
||||
}
|
||||
private get defaultCampaignName(): string {
|
||||
return this.telephony.getConfig().ozonetel.campaignName || 'Inbound_918041763265';
|
||||
}
|
||||
|
||||
async getByMemberId(memberId: string): Promise<AgentConfig | null> {
|
||||
@@ -32,22 +37,29 @@ export class AgentConfigService {
|
||||
if (cached) return cached;
|
||||
|
||||
try {
|
||||
// Note: platform GraphQL field names are derived from the SDK
|
||||
// `label`, not `name` — so the filter/column is
|
||||
// `workspaceMemberId` and the SIP fields are camelCase. The
|
||||
// legacy staging workspace was synced from an older SDK that
|
||||
// exposed `wsmemberId`/`ozonetelagentid`/etc., but any fresh
|
||||
// sync (and all new hospitals going forward) uses these
|
||||
// label-derived names. Re-sync staging if it drifts.
|
||||
const data = await this.platform.query<any>(
|
||||
`{ agents(first: 1, filter: { wsmemberId: { eq: "${memberId}" } }) { edges { node {
|
||||
id ozonetelagentid sipextension sippassword campaignname
|
||||
`{ agents(first: 1, filter: { workspaceMemberId: { eq: "${memberId}" } }) { edges { node {
|
||||
id ozonetelAgentId sipExtension sipPassword campaignName
|
||||
} } } }`,
|
||||
);
|
||||
|
||||
const node = data?.agents?.edges?.[0]?.node;
|
||||
if (!node || !node.ozonetelagentid || !node.sipextension) return null;
|
||||
if (!node || !node.ozonetelAgentId || !node.sipExtension) return null;
|
||||
|
||||
const agentConfig: AgentConfig = {
|
||||
id: node.id,
|
||||
ozonetelAgentId: node.ozonetelagentid,
|
||||
sipExtension: node.sipextension,
|
||||
sipPassword: node.sippassword ?? node.sipextension,
|
||||
campaignName: node.campaignname ?? process.env.OZONETEL_CAMPAIGN_NAME ?? 'Inbound_918041763265',
|
||||
sipUri: `sip:${node.sipextension}@${this.sipDomain}`,
|
||||
ozonetelAgentId: node.ozonetelAgentId,
|
||||
sipExtension: node.sipExtension,
|
||||
sipPassword: node.sipPassword ?? node.sipExtension,
|
||||
campaignName: node.campaignName ?? this.defaultCampaignName,
|
||||
sipUri: `sip:${node.sipExtension}@${this.sipDomain}`,
|
||||
sipWsServer: `wss://${this.sipDomain}:${this.sipWsPort}`,
|
||||
};
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import axios from 'axios';
|
||||
import { OzonetelAgentService } from '../ozonetel/ozonetel-agent.service';
|
||||
import { SessionService } from './session.service';
|
||||
import { AgentConfigService } from './agent-config.service';
|
||||
import { TelephonyConfigService } from '../config/telephony-config.service';
|
||||
|
||||
@Controller('auth')
|
||||
export class AuthController {
|
||||
@@ -18,6 +19,7 @@ export class AuthController {
|
||||
private ozonetelAgent: OzonetelAgentService,
|
||||
private sessionService: SessionService,
|
||||
private agentConfigService: AgentConfigService,
|
||||
private telephony: TelephonyConfigService,
|
||||
) {
|
||||
this.graphqlUrl = config.get<string>('platform.graphqlUrl')!;
|
||||
this.workspaceSubdomain = process.env.PLATFORM_WORKSPACE_SUBDOMAIN ?? 'fortytwo-dev';
|
||||
@@ -138,7 +140,7 @@ export class AuthController {
|
||||
this.logger.warn(`Ozonetel token refresh on login failed: ${err.message}`);
|
||||
});
|
||||
|
||||
const ozAgentPassword = process.env.OZONETEL_AGENT_PASSWORD ?? 'Test123$';
|
||||
const ozAgentPassword = this.telephony.getConfig().ozonetel.agentPassword || 'Test123$';
|
||||
this.ozonetelAgent.loginAgent({
|
||||
agentId: agentConfig.ozonetelAgentId,
|
||||
password: ozAgentPassword,
|
||||
@@ -252,7 +254,7 @@ export class AuthController {
|
||||
|
||||
this.ozonetelAgent.logoutAgent({
|
||||
agentId: agentConfig.ozonetelAgentId,
|
||||
password: process.env.OZONETEL_AGENT_PASSWORD ?? 'Test123$',
|
||||
password: this.telephony.getConfig().ozonetel.agentPassword || 'Test123$',
|
||||
}).catch(err => this.logger.warn(`Ozonetel logout failed: ${err.message}`));
|
||||
|
||||
this.agentConfigService.clearCache(memberId);
|
||||
|
||||
@@ -1,19 +1,23 @@
|
||||
import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import Redis from 'ioredis';
|
||||
|
||||
const SESSION_TTL = 3600; // 1 hour
|
||||
|
||||
@Injectable()
|
||||
export class SessionService implements OnModuleInit {
|
||||
export class SessionService {
|
||||
private readonly logger = new Logger(SessionService.name);
|
||||
private redis: Redis;
|
||||
private readonly redis: Redis;
|
||||
|
||||
constructor(private config: ConfigService) {}
|
||||
|
||||
onModuleInit() {
|
||||
// Redis client is constructed eagerly (not in onModuleInit) so
|
||||
// other services can call cache methods from THEIR onModuleInit
|
||||
// hooks. NestJS instantiates all providers before running any
|
||||
// onModuleInit callback, so the client is guaranteed ready even
|
||||
// when an earlier-firing module's init path touches the cache
|
||||
// (e.g. WidgetConfigService → WidgetKeysService → setCachePersistent).
|
||||
constructor(private config: ConfigService) {
|
||||
const url = this.config.get<string>('redis.url', 'redis://localhost:6379');
|
||||
this.redis = new Redis(url);
|
||||
this.redis = new Redis(url, { lazyConnect: false });
|
||||
this.redis.on('connect', () => this.logger.log('Redis connected'));
|
||||
this.redis.on('error', (err) => this.logger.error(`Redis error: ${err.message}`));
|
||||
}
|
||||
@@ -60,6 +64,10 @@ export class SessionService implements OnModuleInit {
|
||||
await this.redis.set(key, value, 'EX', ttlSeconds);
|
||||
}
|
||||
|
||||
async setCachePersistent(key: string, value: string): Promise<void> {
|
||||
await this.redis.set(key, value);
|
||||
}
|
||||
|
||||
async deleteCache(key: string): Promise<void> {
|
||||
await this.redis.del(key);
|
||||
}
|
||||
|
||||
@@ -4,6 +4,8 @@ import { generateText } from 'ai';
|
||||
import { PlatformGraphqlService } from '../platform/platform-graphql.service';
|
||||
import { createAiModel } from '../ai/ai-provider';
|
||||
import type { LanguageModel } from 'ai';
|
||||
import { AiConfigService } from '../config/ai-config.service';
|
||||
import { DOCTOR_VISIT_SLOTS_FRAGMENT, normalizeDoctors } from '../shared/doctor-utils';
|
||||
|
||||
@Injectable()
|
||||
export class CallAssistService {
|
||||
@@ -14,8 +16,15 @@ export class CallAssistService {
|
||||
constructor(
|
||||
private config: ConfigService,
|
||||
private platform: PlatformGraphqlService,
|
||||
private aiConfig: AiConfigService,
|
||||
) {
|
||||
this.aiModel = createAiModel(config);
|
||||
const cfg = aiConfig.getConfig();
|
||||
this.aiModel = createAiModel({
|
||||
provider: cfg.provider,
|
||||
model: cfg.model,
|
||||
anthropicApiKey: config.get<string>('ai.anthropicApiKey'),
|
||||
openaiApiKey: config.get<string>('ai.openaiApiKey'),
|
||||
});
|
||||
this.platformApiKey = config.get<string>('platform.apiKey') ?? '';
|
||||
}
|
||||
|
||||
@@ -73,16 +82,24 @@ export class CallAssistService {
|
||||
|
||||
const docResult = await this.platform.queryWithAuth<any>(
|
||||
`{ doctors(first: 20) { edges { node {
|
||||
fullName { firstName lastName } department specialty clinic { clinicName }
|
||||
id fullName { firstName lastName } department specialty
|
||||
${DOCTOR_VISIT_SLOTS_FRAGMENT}
|
||||
} } } }`,
|
||||
undefined, authHeader,
|
||||
);
|
||||
const docs = docResult.doctors.edges.map((e: any) => e.node);
|
||||
const docs = normalizeDoctors(docResult.doctors.edges.map((e: any) => e.node));
|
||||
if (docs.length > 0) {
|
||||
parts.push('\nAVAILABLE DOCTORS:');
|
||||
for (const d of docs) {
|
||||
const name = d.fullName ? `Dr. ${d.fullName.firstName} ${d.fullName.lastName}`.trim() : 'Unknown';
|
||||
parts.push(`- ${name} — ${d.department ?? '?'} — ${d.clinic?.clinicName ?? '?'}`);
|
||||
// Show all clinics the doctor visits, joined with
|
||||
// " / " — call assist context is read by the AI
|
||||
// whisperer so multi-clinic doctors don't get
|
||||
// truncated to their first location.
|
||||
const clinicLabel = d.clinics.length > 0
|
||||
? d.clinics.map((c) => c.clinicName).join(' / ')
|
||||
: '?';
|
||||
parts.push(`- ${name} — ${d.department ?? '?'} — ${clinicLabel}`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -99,18 +116,10 @@ export class CallAssistService {
|
||||
try {
|
||||
const { text } = await generateText({
|
||||
model: this.aiModel,
|
||||
system: `You are a real-time call assistant for Global Hospital Bangalore.
|
||||
You listen to the customer's words and provide brief, actionable suggestions for the CC agent.
|
||||
|
||||
${context}
|
||||
|
||||
RULES:
|
||||
- Keep suggestions under 2 sentences
|
||||
- Focus on actionable next steps the agent should take NOW
|
||||
- If customer mentions a doctor or department, suggest available slots
|
||||
- If customer wants to cancel or reschedule, note relevant appointment details
|
||||
- If customer sounds upset, suggest empathetic response
|
||||
- Do NOT repeat what the agent already knows`,
|
||||
system: this.aiConfig.renderPrompt('callAssist', {
|
||||
hospitalName: process.env.HOSPITAL_NAME ?? 'the hospital',
|
||||
context,
|
||||
}),
|
||||
prompt: `Conversation transcript so far:\n${transcript}\n\nProvide a brief suggestion for the agent based on what was just said.`,
|
||||
maxOutputTokens: 150,
|
||||
});
|
||||
|
||||
@@ -1,13 +1,18 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { PlatformModule } from '../platform/platform.module';
|
||||
import { AiModule } from '../ai/ai.module';
|
||||
import { CallerResolutionModule } from '../caller/caller-resolution.module';
|
||||
import { CallEventsService } from './call-events.service';
|
||||
import { CallEventsGateway } from './call-events.gateway';
|
||||
import { CallLookupController } from './call-lookup.controller';
|
||||
import { LeadEnrichController } from './lead-enrich.controller';
|
||||
|
||||
@Module({
|
||||
imports: [PlatformModule, AiModule],
|
||||
controllers: [CallLookupController],
|
||||
// CallerResolutionModule is imported so LeadEnrichController can
|
||||
// inject CallerResolutionService to invalidate the Redis caller
|
||||
// cache after a forced re-enrichment.
|
||||
imports: [PlatformModule, AiModule, CallerResolutionModule],
|
||||
controllers: [CallLookupController, LeadEnrichController],
|
||||
providers: [CallEventsService, CallEventsGateway],
|
||||
exports: [CallEventsService, CallEventsGateway],
|
||||
})
|
||||
|
||||
122
src/call-events/lead-enrich.controller.ts
Normal file
122
src/call-events/lead-enrich.controller.ts
Normal file
@@ -0,0 +1,122 @@
|
||||
import { Body, Controller, Headers, HttpException, Logger, Param, Post } from '@nestjs/common';
|
||||
import { PlatformGraphqlService } from '../platform/platform-graphql.service';
|
||||
import { AiEnrichmentService } from '../ai/ai-enrichment.service';
|
||||
import { CallerResolutionService } from '../caller/caller-resolution.service';
|
||||
|
||||
// POST /api/lead/:id/enrich
|
||||
//
|
||||
// Force re-generation of a lead's AI summary + suggested action. Used by
|
||||
// the call-desk appointment/enquiry forms when the agent explicitly edits
|
||||
// the caller's name — the previously-generated summary was built against
|
||||
// the stale identity, so we discard it and run the enrichment prompt
|
||||
// again with the corrected name.
|
||||
//
|
||||
// Optional body: `{ phone?: string }` — when provided, also invalidates
|
||||
// the Redis caller-resolution cache for that phone so the NEXT incoming
|
||||
// call from the same number picks up fresh data from the platform
|
||||
// instead of the stale cached entry.
|
||||
//
|
||||
// This is distinct from the cache-miss enrichment path in
|
||||
// call-lookup.controller.ts `POST /api/call/lookup` which only runs
|
||||
// enrichment when `lead.aiSummary` is null. That path is fine for
|
||||
// first-time lookups; this one is for explicit "the old summary is
|
||||
// wrong, regenerate it" triggers.
|
||||
@Controller('api/lead')
|
||||
export class LeadEnrichController {
|
||||
private readonly logger = new Logger(LeadEnrichController.name);
|
||||
|
||||
constructor(
|
||||
private readonly platform: PlatformGraphqlService,
|
||||
private readonly ai: AiEnrichmentService,
|
||||
private readonly callerResolution: CallerResolutionService,
|
||||
) {}
|
||||
|
||||
@Post(':id/enrich')
|
||||
async enrichLead(
|
||||
@Param('id') leadId: string,
|
||||
@Body() body: { phone?: string },
|
||||
@Headers('authorization') authHeader: string,
|
||||
) {
|
||||
if (!authHeader) throw new HttpException('Authorization required', 401);
|
||||
if (!leadId) throw new HttpException('leadId required', 400);
|
||||
|
||||
this.logger.log(`Force-enriching lead ${leadId}`);
|
||||
|
||||
// 1. Fetch fresh lead from platform (with the staging-aligned
|
||||
// field names — see findLeadByIdWithToken comment).
|
||||
let lead: any;
|
||||
try {
|
||||
lead = await this.platform.findLeadByIdWithToken(leadId, authHeader);
|
||||
} catch (err) {
|
||||
this.logger.error(`[LEAD-ENRICH] Lead fetch failed for ${leadId}: ${err}`);
|
||||
throw new HttpException(`Lead fetch failed: ${(err as Error).message}`, 500);
|
||||
}
|
||||
if (!lead) {
|
||||
throw new HttpException(`Lead not found: ${leadId}`, 404);
|
||||
}
|
||||
|
||||
// 2. Fetch recent activities so the prompt has conversation context.
|
||||
let activities: any[] = [];
|
||||
try {
|
||||
activities = await this.platform.getLeadActivitiesWithToken(leadId, authHeader, 5);
|
||||
} catch (err) {
|
||||
// Non-fatal — enrichment just has less context.
|
||||
this.logger.warn(`[LEAD-ENRICH] Activity fetch failed: ${err}`);
|
||||
}
|
||||
|
||||
// 3. Run enrichment. LeadContext uses the legacy `leadStatus`/
|
||||
// `leadSource` internal names even though the platform now
|
||||
// exposes them as `status`/`source` — we just map across.
|
||||
const enrichment = await this.ai.enrichLead({
|
||||
firstName: lead.contactName?.firstName ?? undefined,
|
||||
lastName: lead.contactName?.lastName ?? undefined,
|
||||
leadSource: lead.source ?? undefined,
|
||||
interestedService: lead.interestedService ?? undefined,
|
||||
leadStatus: lead.status ?? undefined,
|
||||
contactAttempts: lead.contactAttempts ?? undefined,
|
||||
createdAt: lead.createdAt,
|
||||
activities: activities.map((a) => ({
|
||||
activityType: a.activityType ?? '',
|
||||
summary: a.summary ?? '',
|
||||
})),
|
||||
});
|
||||
|
||||
// 4. Persist the new summary back to the lead.
|
||||
try {
|
||||
await this.platform.updateLeadWithToken(
|
||||
leadId,
|
||||
{
|
||||
aiSummary: enrichment.aiSummary,
|
||||
aiSuggestedAction: enrichment.aiSuggestedAction,
|
||||
},
|
||||
authHeader,
|
||||
);
|
||||
} catch (err) {
|
||||
this.logger.error(`[LEAD-ENRICH] Failed to persist enrichment for ${leadId}: ${err}`);
|
||||
throw new HttpException(
|
||||
`Failed to persist enrichment: ${(err as Error).message}`,
|
||||
500,
|
||||
);
|
||||
}
|
||||
|
||||
// 5. Invalidate the caller cache so the next incoming call from
|
||||
// this phone number does a fresh platform lookup (and picks
|
||||
// up the corrected identity + new summary).
|
||||
if (body?.phone) {
|
||||
try {
|
||||
await this.callerResolution.invalidate(body.phone);
|
||||
this.logger.log(`[LEAD-ENRICH] Caller cache invalidated for ${body.phone}`);
|
||||
} catch (err) {
|
||||
this.logger.warn(`[LEAD-ENRICH] Failed to invalidate caller cache: ${err}`);
|
||||
}
|
||||
}
|
||||
|
||||
this.logger.log(`[LEAD-ENRICH] Lead ${leadId} enriched successfully`);
|
||||
|
||||
return {
|
||||
leadId,
|
||||
aiSummary: enrichment.aiSummary,
|
||||
aiSuggestedAction: enrichment.aiSuggestedAction,
|
||||
};
|
||||
}
|
||||
}
|
||||
213
src/caller/caller-resolution.spec.ts
Normal file
213
src/caller/caller-resolution.spec.ts
Normal file
@@ -0,0 +1,213 @@
|
||||
/**
|
||||
* Caller Resolution Service — unit tests
|
||||
*
|
||||
* QA coverage: TC-IB-05 (lead creation from enquiry),
|
||||
* TC-IB-06 (new patient registration), TC-IB-07/08 (AI context)
|
||||
*
|
||||
* Tests the phone→lead+patient resolution logic:
|
||||
* - Existing patient + existing lead → returns both, links if needed
|
||||
* - Existing lead, no patient → creates patient, links
|
||||
* - Existing patient, no lead → creates lead, links
|
||||
* - New caller (neither exists) → creates both
|
||||
* - Phone normalization (strips +91, non-digits)
|
||||
* - Cache hit/miss behavior
|
||||
*/
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { CallerResolutionService, ResolvedCaller } from './caller-resolution.service';
|
||||
import { PlatformGraphqlService } from '../platform/platform-graphql.service';
|
||||
import { SessionService } from '../auth/session.service';
|
||||
|
||||
describe('CallerResolutionService', () => {
|
||||
let service: CallerResolutionService;
|
||||
let platform: jest.Mocked<PlatformGraphqlService>;
|
||||
let cache: jest.Mocked<SessionService>;
|
||||
|
||||
const AUTH = 'Bearer test-token';
|
||||
|
||||
const existingLead = {
|
||||
id: 'lead-001',
|
||||
contactName: { firstName: 'Priya', lastName: 'Sharma' },
|
||||
contactPhone: { primaryPhoneNumber: '+919949879837' },
|
||||
patientId: 'patient-001',
|
||||
};
|
||||
|
||||
const existingPatient = {
|
||||
id: 'patient-001',
|
||||
fullName: { firstName: 'Priya', lastName: 'Sharma' },
|
||||
phones: { primaryPhoneNumber: '+919949879837' },
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
const module = await Test.createTestingModule({
|
||||
providers: [
|
||||
CallerResolutionService,
|
||||
{
|
||||
provide: PlatformGraphqlService,
|
||||
useValue: {
|
||||
queryWithAuth: jest.fn(),
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: SessionService,
|
||||
useValue: {
|
||||
getCache: jest.fn().mockResolvedValue(null), // no cache by default
|
||||
setCache: jest.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
},
|
||||
],
|
||||
}).compile();
|
||||
|
||||
service = module.get(CallerResolutionService);
|
||||
platform = module.get(PlatformGraphqlService);
|
||||
cache = module.get(SessionService);
|
||||
});
|
||||
|
||||
// ── TC-IB-05: Existing lead + existing patient ───────────────
|
||||
|
||||
it('TC-IB-05: should return existing lead+patient when both found by phone', async () => {
|
||||
platform.queryWithAuth
|
||||
// leads query
|
||||
.mockResolvedValueOnce({ leads: { edges: [{ node: existingLead }] } })
|
||||
// patients query
|
||||
.mockResolvedValueOnce({ patients: { edges: [{ node: existingPatient }] } });
|
||||
|
||||
const result = await service.resolve('9949879837', AUTH);
|
||||
|
||||
expect(result.leadId).toBe('lead-001');
|
||||
expect(result.patientId).toBe('patient-001');
|
||||
expect(result.isNew).toBe(false);
|
||||
expect(result.firstName).toBe('Priya');
|
||||
});
|
||||
|
||||
// ── TC-IB-06: New caller → creates both lead + patient ──────
|
||||
|
||||
it('TC-IB-06: should create both lead+patient for unknown caller', async () => {
|
||||
platform.queryWithAuth
|
||||
// leads query → empty
|
||||
.mockResolvedValueOnce({ leads: { edges: [] } })
|
||||
// patients query → empty
|
||||
.mockResolvedValueOnce({ patients: { edges: [] } })
|
||||
// createPatient
|
||||
.mockResolvedValueOnce({ createPatient: { id: 'new-patient-001' } })
|
||||
// createLead
|
||||
.mockResolvedValueOnce({ createLead: { id: 'new-lead-001' } });
|
||||
|
||||
const result = await service.resolve('6309248884', AUTH);
|
||||
|
||||
expect(result.leadId).toBe('new-lead-001');
|
||||
expect(result.patientId).toBe('new-patient-001');
|
||||
expect(result.isNew).toBe(true);
|
||||
});
|
||||
|
||||
// ── Lead exists, no patient → creates patient ────────────────
|
||||
|
||||
it('should create patient when lead exists without patient match', async () => {
|
||||
const leadNoPatient = { ...existingLead, patientId: null };
|
||||
|
||||
platform.queryWithAuth
|
||||
.mockResolvedValueOnce({ leads: { edges: [{ node: leadNoPatient }] } })
|
||||
.mockResolvedValueOnce({ patients: { edges: [] } })
|
||||
// createPatient
|
||||
.mockResolvedValueOnce({ createPatient: { id: 'new-patient-002' } })
|
||||
// linkLeadToPatient (updateLead)
|
||||
.mockResolvedValueOnce({ updateLead: { id: 'lead-001' } });
|
||||
|
||||
const result = await service.resolve('9949879837', AUTH);
|
||||
|
||||
expect(result.patientId).toBe('new-patient-002');
|
||||
expect(result.leadId).toBe('lead-001');
|
||||
expect(result.isNew).toBe(false);
|
||||
});
|
||||
|
||||
// ── Patient exists, no lead → creates lead ───────────────────
|
||||
|
||||
it('should create lead when patient exists without lead match', async () => {
|
||||
platform.queryWithAuth
|
||||
.mockResolvedValueOnce({ leads: { edges: [] } })
|
||||
.mockResolvedValueOnce({ patients: { edges: [{ node: existingPatient }] } })
|
||||
// createLead
|
||||
.mockResolvedValueOnce({ createLead: { id: 'new-lead-002' } });
|
||||
|
||||
const result = await service.resolve('9949879837', AUTH);
|
||||
|
||||
expect(result.leadId).toBe('new-lead-002');
|
||||
expect(result.patientId).toBe('patient-001');
|
||||
expect(result.isNew).toBe(false);
|
||||
});
|
||||
|
||||
// ── Phone normalization ──────────────────────────────────────
|
||||
|
||||
it('should normalize phone: strip +91 prefix and non-digits', async () => {
|
||||
platform.queryWithAuth
|
||||
.mockResolvedValueOnce({ leads: { edges: [] } })
|
||||
.mockResolvedValueOnce({ patients: { edges: [] } })
|
||||
.mockResolvedValueOnce({ createPatient: { id: 'p' } })
|
||||
.mockResolvedValueOnce({ createLead: { id: 'l' } });
|
||||
|
||||
const result = await service.resolve('+91-994-987-9837', AUTH);
|
||||
|
||||
expect(result.phone).toBe('9949879837');
|
||||
});
|
||||
|
||||
it('should reject invalid short phone numbers', async () => {
|
||||
await expect(service.resolve('12345', AUTH)).rejects.toThrow('Invalid phone');
|
||||
});
|
||||
|
||||
// ── Cache hit ────────────────────────────────────────────────
|
||||
|
||||
it('should return cached result without hitting platform', async () => {
|
||||
const cached: ResolvedCaller = {
|
||||
leadId: 'cached-lead',
|
||||
patientId: 'cached-patient',
|
||||
firstName: 'Cache',
|
||||
lastName: 'Hit',
|
||||
phone: '9949879837',
|
||||
isNew: false,
|
||||
};
|
||||
cache.getCache.mockResolvedValueOnce(JSON.stringify(cached));
|
||||
|
||||
const result = await service.resolve('9949879837', AUTH);
|
||||
|
||||
expect(result).toEqual(cached);
|
||||
expect(platform.queryWithAuth).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
// ── Cache write ──────────────────────────────────────────────
|
||||
|
||||
it('should cache result after successful resolve', async () => {
|
||||
platform.queryWithAuth
|
||||
.mockResolvedValueOnce({ leads: { edges: [{ node: existingLead }] } })
|
||||
.mockResolvedValueOnce({ patients: { edges: [{ node: existingPatient }] } });
|
||||
|
||||
await service.resolve('9949879837', AUTH);
|
||||
|
||||
expect(cache.setCache).toHaveBeenCalledWith(
|
||||
'caller:9949879837',
|
||||
expect.any(String),
|
||||
3600,
|
||||
);
|
||||
});
|
||||
|
||||
// ── Links unlinked lead to patient ───────────────────────────
|
||||
|
||||
it('should link lead to patient when both exist but are unlinked', async () => {
|
||||
const unlinkedLead = { ...existingLead, patientId: null };
|
||||
|
||||
platform.queryWithAuth
|
||||
.mockResolvedValueOnce({ leads: { edges: [{ node: unlinkedLead }] } })
|
||||
.mockResolvedValueOnce({ patients: { edges: [{ node: existingPatient }] } })
|
||||
// updateLead to link
|
||||
.mockResolvedValueOnce({ updateLead: { id: 'lead-001' } });
|
||||
|
||||
const result = await service.resolve('9949879837', AUTH);
|
||||
|
||||
expect(result.leadId).toBe('lead-001');
|
||||
expect(result.patientId).toBe('patient-001');
|
||||
|
||||
// Verify the link mutation was called
|
||||
const linkCall = platform.queryWithAuth.mock.calls.find(
|
||||
c => typeof c[0] === 'string' && c[0].includes('updateLead'),
|
||||
);
|
||||
expect(linkCall).toBeDefined();
|
||||
});
|
||||
});
|
||||
49
src/config/ai-config.controller.ts
Normal file
49
src/config/ai-config.controller.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import { Body, Controller, Get, Logger, Param, Post, Put } from '@nestjs/common';
|
||||
import { AiConfigService } from './ai-config.service';
|
||||
import type { AiActorKey, AiConfig } from './ai.defaults';
|
||||
|
||||
// Mounted under /api/config alongside theme/widget/telephony/setup-state.
|
||||
//
|
||||
// GET /api/config/ai — full config (no secrets here, all safe to return)
|
||||
// PUT /api/config/ai — admin update (provider/model/temperature)
|
||||
// POST /api/config/ai/reset — reset entire config to defaults
|
||||
// PUT /api/config/ai/prompts/:actor — update one persona's system prompt template
|
||||
// POST /api/config/ai/prompts/:actor/reset — restore one persona to its default
|
||||
@Controller('api/config')
|
||||
export class AiConfigController {
|
||||
private readonly logger = new Logger(AiConfigController.name);
|
||||
|
||||
constructor(private readonly ai: AiConfigService) {}
|
||||
|
||||
@Get('ai')
|
||||
getAi() {
|
||||
return this.ai.getConfig();
|
||||
}
|
||||
|
||||
@Put('ai')
|
||||
updateAi(@Body() body: Partial<AiConfig>) {
|
||||
this.logger.log('AI config update request');
|
||||
return this.ai.updateConfig(body);
|
||||
}
|
||||
|
||||
@Post('ai/reset')
|
||||
resetAi() {
|
||||
this.logger.log('AI config reset request');
|
||||
return this.ai.resetConfig();
|
||||
}
|
||||
|
||||
@Put('ai/prompts/:actor')
|
||||
updatePrompt(
|
||||
@Param('actor') actor: AiActorKey,
|
||||
@Body() body: { template: string; editedBy?: string },
|
||||
) {
|
||||
this.logger.log(`AI prompt update for actor '${actor}'`);
|
||||
return this.ai.updatePrompt(actor, body.template, body.editedBy ?? null);
|
||||
}
|
||||
|
||||
@Post('ai/prompts/:actor/reset')
|
||||
resetPrompt(@Param('actor') actor: AiActorKey) {
|
||||
this.logger.log(`AI prompt reset for actor '${actor}'`);
|
||||
return this.ai.resetPrompt(actor);
|
||||
}
|
||||
}
|
||||
218
src/config/ai-config.service.ts
Normal file
218
src/config/ai-config.service.ts
Normal file
@@ -0,0 +1,218 @@
|
||||
import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
|
||||
import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';
|
||||
import { dirname, join } from 'path';
|
||||
import {
|
||||
AI_ACTOR_KEYS,
|
||||
AI_ENV_SEEDS,
|
||||
DEFAULT_AI_CONFIG,
|
||||
DEFAULT_AI_PROMPTS,
|
||||
type AiActorKey,
|
||||
type AiConfig,
|
||||
type AiPromptConfig,
|
||||
type AiProvider,
|
||||
} from './ai.defaults';
|
||||
|
||||
const CONFIG_PATH = join(process.cwd(), 'data', 'ai.json');
|
||||
const BACKUP_DIR = join(process.cwd(), 'data', 'ai-backups');
|
||||
|
||||
// File-backed AI config — provider, model, temperature, and per-actor
|
||||
// system prompt templates. API keys stay in env. Mirrors
|
||||
// TelephonyConfigService.
|
||||
@Injectable()
|
||||
export class AiConfigService implements OnModuleInit {
|
||||
private readonly logger = new Logger(AiConfigService.name);
|
||||
private cached: AiConfig | null = null;
|
||||
|
||||
onModuleInit() {
|
||||
this.ensureReady();
|
||||
}
|
||||
|
||||
getConfig(): AiConfig {
|
||||
if (this.cached) return this.cached;
|
||||
return this.load();
|
||||
}
|
||||
|
||||
updateConfig(updates: Partial<AiConfig>): AiConfig {
|
||||
const current = this.getConfig();
|
||||
const merged: AiConfig = {
|
||||
...current,
|
||||
...updates,
|
||||
// Clamp temperature to a sane range so an admin typo can't break
|
||||
// the model — most providers reject < 0 or > 2.
|
||||
temperature:
|
||||
updates.temperature !== undefined
|
||||
? Math.max(0, Math.min(2, updates.temperature))
|
||||
: current.temperature,
|
||||
version: (current.version ?? 0) + 1,
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
this.backup();
|
||||
this.writeFile(merged);
|
||||
this.cached = merged;
|
||||
this.logger.log(`AI config updated to v${merged.version}`);
|
||||
return merged;
|
||||
}
|
||||
|
||||
resetConfig(): AiConfig {
|
||||
this.backup();
|
||||
const fresh = JSON.parse(JSON.stringify(DEFAULT_AI_CONFIG)) as AiConfig;
|
||||
this.writeFile(fresh);
|
||||
this.cached = fresh;
|
||||
this.logger.log('AI config reset to defaults');
|
||||
return fresh;
|
||||
}
|
||||
|
||||
// Update a single actor's prompt template, preserving the audit
|
||||
// trail. Used by the wizard's edit slideout. Validates the actor
|
||||
// key so a typo from a hand-crafted PUT can't write garbage.
|
||||
updatePrompt(actor: AiActorKey, template: string, editedBy: string | null): AiConfig {
|
||||
if (!AI_ACTOR_KEYS.includes(actor)) {
|
||||
throw new Error(`Unknown AI actor: ${actor}`);
|
||||
}
|
||||
const current = this.getConfig();
|
||||
const existing = current.prompts[actor] ?? DEFAULT_AI_PROMPTS[actor];
|
||||
const updatedPrompt: AiPromptConfig = {
|
||||
...existing,
|
||||
template,
|
||||
lastEditedAt: new Date().toISOString(),
|
||||
lastEditedBy: editedBy,
|
||||
};
|
||||
const merged: AiConfig = {
|
||||
...current,
|
||||
prompts: { ...current.prompts, [actor]: updatedPrompt },
|
||||
version: (current.version ?? 0) + 1,
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
this.backup();
|
||||
this.writeFile(merged);
|
||||
this.cached = merged;
|
||||
this.logger.log(`AI prompt for actor '${actor}' updated to v${merged.version}`);
|
||||
return merged;
|
||||
}
|
||||
|
||||
// Restore a single actor's prompt back to the SDK-shipped default.
|
||||
// Clears the audit fields so it looks "fresh" in the UI.
|
||||
resetPrompt(actor: AiActorKey): AiConfig {
|
||||
if (!AI_ACTOR_KEYS.includes(actor)) {
|
||||
throw new Error(`Unknown AI actor: ${actor}`);
|
||||
}
|
||||
const current = this.getConfig();
|
||||
const fresh: AiPromptConfig = {
|
||||
...DEFAULT_AI_PROMPTS[actor],
|
||||
lastEditedAt: null,
|
||||
lastEditedBy: null,
|
||||
};
|
||||
const merged: AiConfig = {
|
||||
...current,
|
||||
prompts: { ...current.prompts, [actor]: fresh },
|
||||
version: (current.version ?? 0) + 1,
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
this.backup();
|
||||
this.writeFile(merged);
|
||||
this.cached = merged;
|
||||
this.logger.log(`AI prompt for actor '${actor}' reset to default`);
|
||||
return merged;
|
||||
}
|
||||
|
||||
// Render a prompt with `{{variable}}` substitution. Variables not
|
||||
// present in `vars` are left as-is so a missing fill is loud
|
||||
// (the AI sees `{{leadName}}` literally) rather than silently
|
||||
// dropping the placeholder. Falls back to DEFAULT_AI_PROMPTS if
|
||||
// the actor key is missing from the loaded config (handles old
|
||||
// ai.json files that predate this refactor).
|
||||
renderPrompt(actor: AiActorKey, vars: Record<string, string | number | null | undefined>): string {
|
||||
const cfg = this.getConfig();
|
||||
const prompt = cfg.prompts?.[actor] ?? DEFAULT_AI_PROMPTS[actor];
|
||||
const template = prompt.template;
|
||||
return template.replace(/\{\{(\w+)\}\}/g, (match, key) => {
|
||||
const value = vars[key];
|
||||
if (value === undefined || value === null) return match;
|
||||
return String(value);
|
||||
});
|
||||
}
|
||||
|
||||
private ensureReady(): AiConfig {
|
||||
if (existsSync(CONFIG_PATH)) {
|
||||
return this.load();
|
||||
}
|
||||
const seeded: AiConfig = JSON.parse(JSON.stringify(DEFAULT_AI_CONFIG)) as AiConfig;
|
||||
let appliedCount = 0;
|
||||
for (const seed of AI_ENV_SEEDS) {
|
||||
const value = process.env[seed.env];
|
||||
if (value === undefined || value === '') continue;
|
||||
(seeded as any)[seed.field] = value;
|
||||
appliedCount += 1;
|
||||
}
|
||||
seeded.version = 1;
|
||||
seeded.updatedAt = new Date().toISOString();
|
||||
this.writeFile(seeded);
|
||||
this.cached = seeded;
|
||||
this.logger.log(
|
||||
`AI config seeded from env (${appliedCount} env var${appliedCount === 1 ? '' : 's'} applied)`,
|
||||
);
|
||||
return seeded;
|
||||
}
|
||||
|
||||
private load(): AiConfig {
|
||||
try {
|
||||
const raw = readFileSync(CONFIG_PATH, 'utf8');
|
||||
const parsed = JSON.parse(raw);
|
||||
// Merge incoming prompts against defaults so old ai.json
|
||||
// files (written before the prompts refactor) get topped
|
||||
// up with the new actor entries instead of crashing on
|
||||
// first read. Per-actor merging keeps any admin edits
|
||||
// intact while filling in missing actors.
|
||||
const mergedPrompts: Record<AiActorKey, AiPromptConfig> = { ...DEFAULT_AI_PROMPTS };
|
||||
if (parsed.prompts && typeof parsed.prompts === 'object') {
|
||||
for (const key of AI_ACTOR_KEYS) {
|
||||
const incoming = parsed.prompts[key];
|
||||
if (incoming && typeof incoming === 'object') {
|
||||
mergedPrompts[key] = {
|
||||
...DEFAULT_AI_PROMPTS[key],
|
||||
...incoming,
|
||||
// Always pull `defaultTemplate` from the
|
||||
// shipped defaults — never trust the
|
||||
// file's copy, since the SDK baseline can
|
||||
// change between releases and we want
|
||||
// "reset to default" to always reset to
|
||||
// the latest baseline.
|
||||
defaultTemplate: DEFAULT_AI_PROMPTS[key].defaultTemplate,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
const merged: AiConfig = {
|
||||
...DEFAULT_AI_CONFIG,
|
||||
...parsed,
|
||||
provider: (parsed.provider ?? DEFAULT_AI_CONFIG.provider) as AiProvider,
|
||||
prompts: mergedPrompts,
|
||||
};
|
||||
this.cached = merged;
|
||||
this.logger.log('AI config loaded from file');
|
||||
return merged;
|
||||
} catch (err) {
|
||||
this.logger.warn(`Failed to load AI config, using defaults: ${err}`);
|
||||
const fresh = JSON.parse(JSON.stringify(DEFAULT_AI_CONFIG)) as AiConfig;
|
||||
this.cached = fresh;
|
||||
return fresh;
|
||||
}
|
||||
}
|
||||
|
||||
private writeFile(cfg: AiConfig) {
|
||||
const dir = dirname(CONFIG_PATH);
|
||||
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
|
||||
writeFileSync(CONFIG_PATH, JSON.stringify(cfg, null, 2), 'utf8');
|
||||
}
|
||||
|
||||
private backup() {
|
||||
try {
|
||||
if (!existsSync(CONFIG_PATH)) return;
|
||||
if (!existsSync(BACKUP_DIR)) mkdirSync(BACKUP_DIR, { recursive: true });
|
||||
const ts = new Date().toISOString().replace(/[:.]/g, '-');
|
||||
copyFileSync(CONFIG_PATH, join(BACKUP_DIR, `ai-${ts}.json`));
|
||||
} catch (err) {
|
||||
this.logger.warn(`AI config backup failed: ${err}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
286
src/config/ai.defaults.ts
Normal file
286
src/config/ai.defaults.ts
Normal file
@@ -0,0 +1,286 @@
|
||||
// Admin-editable AI assistant config. Holds the user-facing knobs (provider,
|
||||
// model, temperature) AND a per-actor system prompt template map. API keys
|
||||
// themselves stay in env vars because they are true secrets and rotation is
|
||||
// an ops event.
|
||||
//
|
||||
// Each "actor" is a distinct AI persona used by the sidecar — widget chat,
|
||||
// CC agent helper, supervisor, lead enrichment, etc. Pulling these out of
|
||||
// hardcoded service files lets the hospital admin tune tone, boundaries,
|
||||
// and instructions per persona without a sidecar redeploy. The 7 actors
|
||||
// listed below cover every customer-facing AI surface in Helix Engage as
|
||||
// of 2026-04-08; internal/dev-only prompts (rules engine config helper,
|
||||
// recording speaker-channel identification) stay hardcoded since they are
|
||||
// not customer-tunable.
|
||||
//
|
||||
// Templating: each actor's prompt is a string with `{{variable}}` placeholders
|
||||
// that the calling service fills in via AiConfigService.renderPrompt(actor,
|
||||
// vars). The variable shape per actor is documented in the `variables` field
|
||||
// so the wizard UI can show admins what they can reference.
|
||||
|
||||
export type AiProvider = 'openai' | 'anthropic';
|
||||
|
||||
// Stable keys for each configurable persona. Adding a new actor:
|
||||
// 1. add a key here
|
||||
// 2. add a default entry in DEFAULT_AI_PROMPTS below
|
||||
// 3. add the corresponding renderPrompt call in the consuming service
|
||||
export const AI_ACTOR_KEYS = [
|
||||
'widgetChat',
|
||||
'ccAgentHelper',
|
||||
'supervisorChat',
|
||||
'leadEnrichment',
|
||||
'callInsight',
|
||||
'callAssist',
|
||||
'recordingAnalysis',
|
||||
] as const;
|
||||
export type AiActorKey = (typeof AI_ACTOR_KEYS)[number];
|
||||
|
||||
export type AiPromptConfig = {
|
||||
// Human-readable name shown in the wizard UI.
|
||||
label: string;
|
||||
// One-line description of when this persona is invoked.
|
||||
description: string;
|
||||
// Variables the template can reference, with a one-line hint each.
|
||||
// Surfaced in the edit slideout so admins know what `{{var}}` they
|
||||
// can use without reading code.
|
||||
variables: Array<{ key: string; description: string }>;
|
||||
// The current template (may be admin-edited).
|
||||
template: string;
|
||||
// The original baseline so we can offer a "reset to default" button.
|
||||
defaultTemplate: string;
|
||||
// Audit fields — when this prompt was last edited and by whom.
|
||||
// null on the default-supplied entries.
|
||||
lastEditedAt: string | null;
|
||||
lastEditedBy: string | null;
|
||||
};
|
||||
|
||||
export type AiConfig = {
|
||||
provider: AiProvider;
|
||||
model: string;
|
||||
// 0..2, controls randomness. Default 0.7 matches the existing hardcoded
|
||||
// values used in WidgetChatService and AI tools.
|
||||
temperature: number;
|
||||
// Per-actor system prompt templates. Keyed by AiActorKey so callers can
|
||||
// do `config.prompts.widgetChat.template` and missing keys are caught
|
||||
// at compile time.
|
||||
prompts: Record<AiActorKey, AiPromptConfig>;
|
||||
version?: number;
|
||||
updatedAt?: string;
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Default templates — extracted verbatim from the hardcoded versions in:
|
||||
// - widget-chat.service.ts → widgetChat
|
||||
// - ai-chat.controller.ts → ccAgentHelper, supervisorChat
|
||||
// - ai-enrichment.service.ts → leadEnrichment
|
||||
// - ai-insight.consumer.ts → callInsight
|
||||
// - call-assist.service.ts → callAssist
|
||||
// - recordings.service.ts → recordingAnalysis
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const WIDGET_CHAT_DEFAULT = `You are a helpful, concise assistant for {{hospitalName}}.
|
||||
You are chatting with a website visitor named {{userName}}.
|
||||
|
||||
{{branchContext}}
|
||||
|
||||
TOOL USAGE RULES (STRICT):
|
||||
- When the user asks about departments, call list_departments and DO NOT also list departments in prose.
|
||||
- When they ask about clinic timings, visiting hours, or "when is X open", call show_clinic_timings.
|
||||
- When they ask about doctors in a department, call show_doctors and DO NOT also list doctors in prose.
|
||||
- When they ask about a specific doctor's availability or want to book with them, call show_doctor_slots.
|
||||
- When the conversation is trending toward booking, call suggest_booking.
|
||||
- After calling a tool, DO NOT restate its contents in prose. At most write a single short sentence
|
||||
(under 15 words) framing the widget, or no text at all. The widget already shows the data.
|
||||
- If you are about to write a bulleted or numbered list of departments, doctors, hours, or slots,
|
||||
STOP and call the appropriate tool instead.
|
||||
- NEVER use markdown formatting (no **bold**, no *italic*, no bullet syntax). Plain text only in
|
||||
non-tool replies.
|
||||
- NEVER invent or mention specific dates in prose or tool inputs. The server owns "today".
|
||||
If the visitor asks about a future date, tell them to use the Book tab's date picker.
|
||||
|
||||
OTHER RULES:
|
||||
- Answer other questions (directions, general info) concisely in prose.
|
||||
- If you do not know something, say so and suggest they call the hospital.
|
||||
- Never quote prices. No medical advice. For clinical questions, defer to a doctor.
|
||||
|
||||
{{knowledgeBase}}`;
|
||||
|
||||
const CC_AGENT_HELPER_DEFAULT = `You are an AI assistant for call center agents at {{hospitalName}}.
|
||||
You help agents answer questions about patients, doctors, appointments, clinics, and hospital services during live calls.
|
||||
|
||||
IMPORTANT — ANSWER FROM KNOWLEDGE BASE FIRST:
|
||||
The knowledge base below contains REAL clinic locations, timings, doctor details, health packages, and insurance partners.
|
||||
When asked about clinic timings, locations, doctor availability, packages, or insurance — ALWAYS check the knowledge base FIRST before saying you don't know.
|
||||
|
||||
RULES:
|
||||
1. For patient-specific questions (history, appointments, calls), use the lookup tools. NEVER guess patient data.
|
||||
2. For doctor details beyond what's in the KB, use the lookup_doctor tool.
|
||||
3. For clinic info, timings, packages, insurance → answer directly from the knowledge base below.
|
||||
4. If you truly cannot find the answer in the KB or via tools, say "I couldn't find that in our system."
|
||||
5. Be concise — agents are on live calls. Under 100 words unless asked for detail.
|
||||
6. NEVER give medical advice, diagnosis, or treatment recommendations.
|
||||
7. Format with bullet points for easy scanning.
|
||||
|
||||
KNOWLEDGE BASE (this is real data from our system):
|
||||
{{knowledgeBase}}`;
|
||||
|
||||
const SUPERVISOR_CHAT_DEFAULT = `You are an AI assistant for supervisors at {{hospitalName}}'s call center (Helix Engage).
|
||||
You help supervisors monitor team performance, identify issues, and make data-driven decisions.
|
||||
|
||||
## YOUR CAPABILITIES
|
||||
You have access to tools that query real-time data:
|
||||
- **Agent performance**: call counts, conversion rates, NPS scores, idle time, pending follow-ups
|
||||
- **Campaign stats**: lead counts, conversion rates per campaign, platform breakdown
|
||||
- **Call summary**: total calls, inbound/outbound split, missed call rate, disposition breakdown
|
||||
- **SLA breaches**: missed calls that haven't been called back within the SLA threshold
|
||||
|
||||
## RULES
|
||||
1. ALWAYS use tools to fetch data before answering. NEVER guess or fabricate performance numbers.
|
||||
2. Be specific — include actual numbers from the tool response, not vague qualifiers.
|
||||
3. When comparing agents, use their configured thresholds (minConversionPercent, minNpsThreshold, maxIdleMinutes) and team averages. Let the data determine who is underperforming — do not assume.
|
||||
4. Be concise — supervisors want quick answers. Use bullet points.
|
||||
5. When recommending actions, ground them in the data returned by tools.
|
||||
6. If asked about trends, use the call summary tool with different periods.
|
||||
7. Do not use any agent name in a negative context unless the data explicitly supports it.`;
|
||||
|
||||
const LEAD_ENRICHMENT_DEFAULT = `You are an AI assistant for a hospital call center.
|
||||
An inbound call is coming in from a lead. Summarize their history and suggest what the call center agent should do.
|
||||
|
||||
Lead details:
|
||||
- Name: {{leadName}}
|
||||
- Source: {{leadSource}}
|
||||
- Interested in: {{interestedService}}
|
||||
- Current status: {{leadStatus}}
|
||||
- Lead age: {{daysSince}} days
|
||||
- Contact attempts: {{contactAttempts}}
|
||||
|
||||
Recent activity:
|
||||
{{activities}}`;
|
||||
|
||||
const CALL_INSIGHT_DEFAULT = `You are a CRM assistant for {{hospitalName}}.
|
||||
Generate a brief, actionable insight about this lead based on their interaction history.
|
||||
Be specific — reference actual dates, dispositions, and patterns.
|
||||
If the lead has booked appointments, mention upcoming ones.
|
||||
If they keep calling about the same thing, note the pattern.`;
|
||||
|
||||
const CALL_ASSIST_DEFAULT = `You are a real-time call assistant for {{hospitalName}}.
|
||||
You listen to the customer's words and provide brief, actionable suggestions for the CC agent.
|
||||
|
||||
{{context}}
|
||||
|
||||
RULES:
|
||||
- Keep suggestions under 2 sentences
|
||||
- Focus on actionable next steps the agent should take NOW
|
||||
- If customer mentions a doctor or department, suggest available slots
|
||||
- If customer wants to cancel or reschedule, note relevant appointment details
|
||||
- If customer sounds upset, suggest empathetic response
|
||||
- Do NOT repeat what the agent already knows`;
|
||||
|
||||
const RECORDING_ANALYSIS_DEFAULT = `You are a call quality analyst for {{hospitalName}}.
|
||||
Analyze the following call recording transcript and provide structured insights.
|
||||
Be specific, brief, and actionable. Focus on healthcare context.
|
||||
{{summaryBlock}}
|
||||
{{topicsBlock}}`;
|
||||
|
||||
// Helper that builds an AiPromptConfig with the same template for both
|
||||
// `template` and `defaultTemplate` — what every actor starts with on a
|
||||
// fresh boot.
|
||||
const promptDefault = (
|
||||
label: string,
|
||||
description: string,
|
||||
variables: Array<{ key: string; description: string }>,
|
||||
template: string,
|
||||
): AiPromptConfig => ({
|
||||
label,
|
||||
description,
|
||||
variables,
|
||||
template,
|
||||
defaultTemplate: template,
|
||||
lastEditedAt: null,
|
||||
lastEditedBy: null,
|
||||
});
|
||||
|
||||
export const DEFAULT_AI_PROMPTS: Record<AiActorKey, AiPromptConfig> = {
|
||||
widgetChat: promptDefault(
|
||||
'Website widget chat',
|
||||
'Patient-facing bot embedded on the hospital website. Handles general questions, finds doctors, suggests appointments.',
|
||||
[
|
||||
{ key: 'hospitalName', description: 'Branded hospital display name from theme.json' },
|
||||
{ key: 'userName', description: 'Visitor first name (or "there" if unknown)' },
|
||||
{ key: 'branchContext', description: 'Pre-rendered branch-selection instructions block' },
|
||||
{ key: 'knowledgeBase', description: 'Pre-rendered list of departments + doctors + clinics' },
|
||||
],
|
||||
WIDGET_CHAT_DEFAULT,
|
||||
),
|
||||
ccAgentHelper: promptDefault(
|
||||
'CC agent helper',
|
||||
'In-call assistant the CC agent uses to look up patient history, doctor details, and clinic info while on a call.',
|
||||
[
|
||||
{ key: 'hospitalName', description: 'Branded hospital display name' },
|
||||
{ key: 'knowledgeBase', description: 'Pre-rendered hospital knowledge base (clinics, doctors, packages)' },
|
||||
],
|
||||
CC_AGENT_HELPER_DEFAULT,
|
||||
),
|
||||
supervisorChat: promptDefault(
|
||||
'Supervisor assistant',
|
||||
'AI tools the supervisor uses to query agent performance, campaign stats, and SLA breaches.',
|
||||
[
|
||||
{ key: 'hospitalName', description: 'Branded hospital display name' },
|
||||
],
|
||||
SUPERVISOR_CHAT_DEFAULT,
|
||||
),
|
||||
leadEnrichment: promptDefault(
|
||||
'Lead enrichment',
|
||||
'Generates an AI summary + suggested action for a new inbound lead before the agent picks up.',
|
||||
[
|
||||
{ key: 'leadName', description: 'Lead first + last name' },
|
||||
{ key: 'leadSource', description: 'Source channel (WHATSAPP, GOOGLE_ADS, etc.)' },
|
||||
{ key: 'interestedService', description: 'What the lead enquired about' },
|
||||
{ key: 'leadStatus', description: 'Current lead status' },
|
||||
{ key: 'daysSince', description: 'Days since the lead was created' },
|
||||
{ key: 'contactAttempts', description: 'Prior contact attempts count' },
|
||||
{ key: 'activities', description: 'Pre-rendered recent activity summary' },
|
||||
],
|
||||
LEAD_ENRICHMENT_DEFAULT,
|
||||
),
|
||||
callInsight: promptDefault(
|
||||
'Post-call insight',
|
||||
'After each call, generates a 2-3 sentence summary + a single suggested next action for the lead record.',
|
||||
[
|
||||
{ key: 'hospitalName', description: 'Branded hospital display name' },
|
||||
],
|
||||
CALL_INSIGHT_DEFAULT,
|
||||
),
|
||||
callAssist: promptDefault(
|
||||
'Live call whisper',
|
||||
'Real-time suggestions whispered to the CC agent during a call, based on the running transcript.',
|
||||
[
|
||||
{ key: 'hospitalName', description: 'Branded hospital display name' },
|
||||
{ key: 'context', description: 'Pre-rendered call context (current lead, recent activities, available doctors)' },
|
||||
],
|
||||
CALL_ASSIST_DEFAULT,
|
||||
),
|
||||
recordingAnalysis: promptDefault(
|
||||
'Call recording analysis',
|
||||
'Analyses post-call recording transcripts to extract key topics, action items, coaching notes, and compliance flags.',
|
||||
[
|
||||
{ key: 'hospitalName', description: 'Branded hospital display name' },
|
||||
{ key: 'summaryBlock', description: 'Optional pre-rendered "Call summary: ..." line (empty when none)' },
|
||||
{ key: 'topicsBlock', description: 'Optional pre-rendered "Detected topics: ..." line (empty when none)' },
|
||||
],
|
||||
RECORDING_ANALYSIS_DEFAULT,
|
||||
),
|
||||
};
|
||||
|
||||
export const DEFAULT_AI_CONFIG: AiConfig = {
|
||||
provider: 'openai',
|
||||
model: 'gpt-4o-mini',
|
||||
temperature: 0.7,
|
||||
prompts: DEFAULT_AI_PROMPTS,
|
||||
};
|
||||
|
||||
// Field-by-field mapping from the legacy env vars used by ai-provider.ts
|
||||
// (AI_PROVIDER + AI_MODEL). API keys are NOT seeded — they remain in env.
|
||||
export const AI_ENV_SEEDS: Array<{ env: string; field: keyof Pick<AiConfig, 'provider' | 'model'> }> = [
|
||||
{ env: 'AI_PROVIDER', field: 'provider' },
|
||||
{ env: 'AI_MODEL', field: 'model' },
|
||||
];
|
||||
@@ -1,10 +1,54 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { AuthModule } from '../auth/auth.module';
|
||||
import { PlatformModule } from '../platform/platform.module';
|
||||
import { ThemeController } from './theme.controller';
|
||||
import { ThemeService } from './theme.service';
|
||||
import { WidgetKeysService } from './widget-keys.service';
|
||||
import { WidgetConfigService } from './widget-config.service';
|
||||
import { WidgetConfigController } from './widget-config.controller';
|
||||
import { SetupStateService } from './setup-state.service';
|
||||
import { SetupStateController } from './setup-state.controller';
|
||||
import { TelephonyConfigService } from './telephony-config.service';
|
||||
import { TelephonyConfigController } from './telephony-config.controller';
|
||||
import { AiConfigService } from './ai-config.service';
|
||||
import { AiConfigController } from './ai-config.controller';
|
||||
|
||||
// Central config module — owns everything in data/*.json that's editable
|
||||
// from the admin portal. Today: theme, widget, setup-state, telephony, ai.
|
||||
//
|
||||
// Marked @Global() so the 3 new sidecar config services (setup-state, telephony,
|
||||
// ai) are injectable from any module without explicit import wiring. Without this,
|
||||
// AuthModule + OzonetelAgentModule + MaintModule would all need to import
|
||||
// ConfigThemeModule, which would create a circular dependency with AuthModule
|
||||
// (ConfigThemeModule already imports AuthModule for SessionService).
|
||||
//
|
||||
// AuthModule is imported because WidgetKeysService depends on SessionService
|
||||
// (Redis-backed cache for widget site key storage).
|
||||
@Global()
|
||||
@Module({
|
||||
controllers: [ThemeController],
|
||||
providers: [ThemeService],
|
||||
exports: [ThemeService],
|
||||
imports: [AuthModule, PlatformModule],
|
||||
controllers: [
|
||||
ThemeController,
|
||||
WidgetConfigController,
|
||||
SetupStateController,
|
||||
TelephonyConfigController,
|
||||
AiConfigController,
|
||||
],
|
||||
providers: [
|
||||
ThemeService,
|
||||
WidgetKeysService,
|
||||
WidgetConfigService,
|
||||
SetupStateService,
|
||||
TelephonyConfigService,
|
||||
AiConfigService,
|
||||
],
|
||||
exports: [
|
||||
ThemeService,
|
||||
WidgetKeysService,
|
||||
WidgetConfigService,
|
||||
SetupStateService,
|
||||
TelephonyConfigService,
|
||||
AiConfigService,
|
||||
],
|
||||
})
|
||||
export class ConfigThemeModule {}
|
||||
|
||||
56
src/config/setup-state.controller.ts
Normal file
56
src/config/setup-state.controller.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
import { Body, Controller, Get, Logger, Param, Post, Put } from '@nestjs/common';
|
||||
import { SetupStateService } from './setup-state.service';
|
||||
import type { SetupStepName } from './setup-state.defaults';
|
||||
|
||||
// Public endpoint family for the onboarding wizard. Mounted under /api/config
|
||||
// alongside theme/widget. No auth guard yet — matches existing convention with
|
||||
// ThemeController. To be tightened when the staff portal admin auth is in place.
|
||||
//
|
||||
// GET /api/config/setup-state full state + isWizardRequired
|
||||
// PUT /api/config/setup-state/steps/:step { completed: bool, completedBy?: string }
|
||||
// POST /api/config/setup-state/dismiss dismiss the wizard for this workspace
|
||||
// POST /api/config/setup-state/reset reset all steps to incomplete (admin)
|
||||
@Controller('api/config')
|
||||
export class SetupStateController {
|
||||
private readonly logger = new Logger(SetupStateController.name);
|
||||
|
||||
constructor(private readonly setupState: SetupStateService) {}
|
||||
|
||||
@Get('setup-state')
|
||||
async getState() {
|
||||
// Use the checked variant so the platform workspace probe runs
|
||||
// before we serialize. Catches workspace changes (DB resets,
|
||||
// re-onboards) on the very first frontend GET.
|
||||
const state = await this.setupState.getStateChecked();
|
||||
return {
|
||||
...state,
|
||||
wizardRequired: this.setupState.isWizardRequired(),
|
||||
};
|
||||
}
|
||||
|
||||
@Put('setup-state/steps/:step')
|
||||
updateStep(
|
||||
@Param('step') step: SetupStepName,
|
||||
@Body() body: { completed: boolean; completedBy?: string },
|
||||
) {
|
||||
const updated = body.completed
|
||||
? this.setupState.markStepCompleted(step, body.completedBy ?? null)
|
||||
: this.setupState.markStepIncomplete(step);
|
||||
// Mirror GET shape — include `wizardRequired` so the frontend
|
||||
// doesn't see a state object missing the field and re-render
|
||||
// into an inconsistent shape.
|
||||
return { ...updated, wizardRequired: this.setupState.isWizardRequired() };
|
||||
}
|
||||
|
||||
@Post('setup-state/dismiss')
|
||||
dismiss() {
|
||||
const updated = this.setupState.dismissWizard();
|
||||
return { ...updated, wizardRequired: this.setupState.isWizardRequired() };
|
||||
}
|
||||
|
||||
@Post('setup-state/reset')
|
||||
reset() {
|
||||
const updated = this.setupState.resetState();
|
||||
return { ...updated, wizardRequired: this.setupState.isWizardRequired() };
|
||||
}
|
||||
}
|
||||
60
src/config/setup-state.defaults.ts
Normal file
60
src/config/setup-state.defaults.ts
Normal file
@@ -0,0 +1,60 @@
|
||||
// Tracks completion of the 6 onboarding setup steps the hospital admin walks
|
||||
// through after first login. Drives the wizard auto-show on /setup and the
|
||||
// completion badges on the Settings hub.
|
||||
|
||||
export type SetupStepName =
|
||||
| 'identity'
|
||||
| 'clinics'
|
||||
| 'doctors'
|
||||
| 'team'
|
||||
| 'telephony'
|
||||
| 'ai';
|
||||
|
||||
export type SetupStepStatus = {
|
||||
completed: boolean;
|
||||
completedAt: string | null;
|
||||
completedBy: string | null;
|
||||
};
|
||||
|
||||
export type SetupState = {
|
||||
version?: number;
|
||||
updatedAt?: string;
|
||||
// When true the wizard never auto-shows even if some steps are incomplete.
|
||||
// Settings hub still shows the per-section badges.
|
||||
wizardDismissed: boolean;
|
||||
steps: Record<SetupStepName, SetupStepStatus>;
|
||||
// The platform workspace this state belongs to. The sidecar's API key
|
||||
// is scoped to exactly one workspace, so on every load we compare the
|
||||
// file's workspaceId against the live currentWorkspace.id and reset
|
||||
// the file if they differ. Stops setup-state from leaking across DB
|
||||
// resets and re-onboards.
|
||||
workspaceId?: string | null;
|
||||
};
|
||||
|
||||
const emptyStep = (): SetupStepStatus => ({
|
||||
completed: false,
|
||||
completedAt: null,
|
||||
completedBy: null,
|
||||
});
|
||||
|
||||
export const SETUP_STEP_NAMES: readonly SetupStepName[] = [
|
||||
'identity',
|
||||
'clinics',
|
||||
'doctors',
|
||||
'team',
|
||||
'telephony',
|
||||
'ai',
|
||||
] as const;
|
||||
|
||||
export const DEFAULT_SETUP_STATE: SetupState = {
|
||||
wizardDismissed: false,
|
||||
workspaceId: null,
|
||||
steps: {
|
||||
identity: emptyStep(),
|
||||
clinics: emptyStep(),
|
||||
doctors: emptyStep(),
|
||||
team: emptyStep(),
|
||||
telephony: emptyStep(),
|
||||
ai: emptyStep(),
|
||||
},
|
||||
};
|
||||
220
src/config/setup-state.service.ts
Normal file
220
src/config/setup-state.service.ts
Normal file
@@ -0,0 +1,220 @@
|
||||
import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';
|
||||
import { dirname, join } from 'path';
|
||||
import { PlatformGraphqlService } from '../platform/platform-graphql.service';
|
||||
import {
|
||||
DEFAULT_SETUP_STATE,
|
||||
SETUP_STEP_NAMES,
|
||||
type SetupState,
|
||||
type SetupStepName,
|
||||
} from './setup-state.defaults';
|
||||
|
||||
const SETUP_STATE_PATH = join(process.cwd(), 'data', 'setup-state.json');
|
||||
|
||||
// File-backed store for the onboarding wizard's progress. Mirrors the
|
||||
// pattern of ThemeService and WidgetConfigService — load on init, cache in
|
||||
// memory, write on every change. No backups (the data is small and easily
|
||||
// recreated by the wizard if it ever gets corrupted).
|
||||
//
|
||||
// Workspace scoping: the sidecar's API key is scoped to exactly one
|
||||
// workspace, so on first access we compare the file's stored workspaceId
|
||||
// against the live currentWorkspace.id from the platform. If they differ
|
||||
// (DB reset, re-onboard, sidecar pointed at a new workspace), the file is
|
||||
// reset before any reads return. This guarantees a fresh wizard for a
|
||||
// fresh workspace without manual file deletion.
|
||||
@Injectable()
|
||||
export class SetupStateService implements OnModuleInit {
|
||||
private readonly logger = new Logger(SetupStateService.name);
|
||||
private cached: SetupState | null = null;
|
||||
// Memoize the platform's currentWorkspace.id lookup so we don't hit
|
||||
// the platform on every getState() call. Set once per process boot
|
||||
// (or after a successful reset).
|
||||
private liveWorkspaceId: string | null = null;
|
||||
private workspaceCheckPromise: Promise<void> | null = null;
|
||||
|
||||
constructor(private platform: PlatformGraphqlService) {}
|
||||
|
||||
onModuleInit() {
|
||||
this.load();
|
||||
// Fire-and-forget the workspace probe so the file gets aligned
|
||||
// before the frontend's first GET. Errors are logged but
|
||||
// non-fatal — if the platform is down at boot, the legacy
|
||||
// unscoped behaviour kicks in until the first reachable probe.
|
||||
this.ensureWorkspaceMatch().catch((err) =>
|
||||
this.logger.warn(`Initial workspace probe failed: ${err}`),
|
||||
);
|
||||
}
|
||||
|
||||
getState(): SetupState {
|
||||
if (this.cached) return this.cached;
|
||||
return this.load();
|
||||
}
|
||||
|
||||
// Awaits a workspace check before returning state. The controller
|
||||
// calls this so the GET response always reflects the current
|
||||
// workspace, not yesterday's.
|
||||
async getStateChecked(): Promise<SetupState> {
|
||||
await this.ensureWorkspaceMatch();
|
||||
return this.getState();
|
||||
}
|
||||
|
||||
private async ensureWorkspaceMatch(): Promise<void> {
|
||||
// Single-flight: if a check is already running, await it.
|
||||
if (this.workspaceCheckPromise) return this.workspaceCheckPromise;
|
||||
if (this.liveWorkspaceId) {
|
||||
// Already validated this process. Trust the cache.
|
||||
return;
|
||||
}
|
||||
this.workspaceCheckPromise = (async () => {
|
||||
try {
|
||||
const data = await this.platform.query<{
|
||||
currentWorkspace: { id: string };
|
||||
}>(`{ currentWorkspace { id } }`);
|
||||
const liveId = data?.currentWorkspace?.id ?? null;
|
||||
if (!liveId) {
|
||||
this.logger.warn(
|
||||
'currentWorkspace.id was empty — cannot scope setup-state',
|
||||
);
|
||||
return;
|
||||
}
|
||||
this.liveWorkspaceId = liveId;
|
||||
const current = this.getState();
|
||||
if (current.workspaceId && current.workspaceId !== liveId) {
|
||||
this.logger.log(
|
||||
`Workspace changed (${current.workspaceId} → ${liveId}) — resetting setup-state`,
|
||||
);
|
||||
this.resetState();
|
||||
}
|
||||
if (!current.workspaceId) {
|
||||
// First boot after the workspaceId field was added
|
||||
// (or first boot ever). Stamp the file so future
|
||||
// boots can detect drift.
|
||||
const stamped: SetupState = {
|
||||
...this.getState(),
|
||||
workspaceId: liveId,
|
||||
};
|
||||
this.writeFile(stamped);
|
||||
this.cached = stamped;
|
||||
}
|
||||
} finally {
|
||||
this.workspaceCheckPromise = null;
|
||||
}
|
||||
})();
|
||||
return this.workspaceCheckPromise;
|
||||
}
|
||||
|
||||
// Returns true if any required step is incomplete and the wizard hasn't
|
||||
// been explicitly dismissed. Used by the frontend post-login redirect.
|
||||
isWizardRequired(): boolean {
|
||||
const s = this.getState();
|
||||
if (s.wizardDismissed) return false;
|
||||
return SETUP_STEP_NAMES.some(name => !s.steps[name].completed);
|
||||
}
|
||||
|
||||
markStepCompleted(step: SetupStepName, completedBy: string | null = null): SetupState {
|
||||
const current = this.getState();
|
||||
if (!current.steps[step]) {
|
||||
throw new Error(`Unknown setup step: ${step}`);
|
||||
}
|
||||
const updated: SetupState = {
|
||||
...current,
|
||||
steps: {
|
||||
...current.steps,
|
||||
[step]: {
|
||||
completed: true,
|
||||
completedAt: new Date().toISOString(),
|
||||
completedBy,
|
||||
},
|
||||
},
|
||||
version: (current.version ?? 0) + 1,
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
this.writeFile(updated);
|
||||
this.cached = updated;
|
||||
this.logger.log(`Setup step '${step}' marked completed`);
|
||||
return updated;
|
||||
}
|
||||
|
||||
markStepIncomplete(step: SetupStepName): SetupState {
|
||||
const current = this.getState();
|
||||
if (!current.steps[step]) {
|
||||
throw new Error(`Unknown setup step: ${step}`);
|
||||
}
|
||||
const updated: SetupState = {
|
||||
...current,
|
||||
steps: {
|
||||
...current.steps,
|
||||
[step]: { completed: false, completedAt: null, completedBy: null },
|
||||
},
|
||||
version: (current.version ?? 0) + 1,
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
this.writeFile(updated);
|
||||
this.cached = updated;
|
||||
this.logger.log(`Setup step '${step}' marked incomplete`);
|
||||
return updated;
|
||||
}
|
||||
|
||||
dismissWizard(): SetupState {
|
||||
const current = this.getState();
|
||||
const updated: SetupState = {
|
||||
...current,
|
||||
wizardDismissed: true,
|
||||
version: (current.version ?? 0) + 1,
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
this.writeFile(updated);
|
||||
this.cached = updated;
|
||||
this.logger.log('Setup wizard dismissed');
|
||||
return updated;
|
||||
}
|
||||
|
||||
resetState(): SetupState {
|
||||
// Preserve the live workspaceId on reset so the file remains
|
||||
// scoped — otherwise the next workspace check would think the
|
||||
// file is unscoped and re-stamp it, which is fine but creates
|
||||
// an extra write.
|
||||
const fresh: SetupState = {
|
||||
...DEFAULT_SETUP_STATE,
|
||||
workspaceId: this.liveWorkspaceId ?? null,
|
||||
};
|
||||
this.writeFile(fresh);
|
||||
this.cached = fresh;
|
||||
this.logger.log('Setup state reset to defaults');
|
||||
return this.cached;
|
||||
}
|
||||
|
||||
private load(): SetupState {
|
||||
try {
|
||||
if (existsSync(SETUP_STATE_PATH)) {
|
||||
const raw = readFileSync(SETUP_STATE_PATH, 'utf8');
|
||||
const parsed = JSON.parse(raw);
|
||||
// Defensive merge: if a new step name is added later, the old
|
||||
// file won't have it. Fill missing steps with the empty default.
|
||||
const merged: SetupState = {
|
||||
...DEFAULT_SETUP_STATE,
|
||||
...parsed,
|
||||
steps: {
|
||||
...DEFAULT_SETUP_STATE.steps,
|
||||
...(parsed.steps ?? {}),
|
||||
},
|
||||
};
|
||||
this.cached = merged;
|
||||
this.logger.log('Setup state loaded from file');
|
||||
return merged;
|
||||
}
|
||||
} catch (err) {
|
||||
this.logger.warn(`Failed to load setup state: ${err}`);
|
||||
}
|
||||
const fresh: SetupState = JSON.parse(JSON.stringify(DEFAULT_SETUP_STATE));
|
||||
this.cached = fresh;
|
||||
this.logger.log('Using default setup state (no file yet)');
|
||||
return fresh;
|
||||
}
|
||||
|
||||
private writeFile(state: SetupState) {
|
||||
const dir = dirname(SETUP_STATE_PATH);
|
||||
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
|
||||
writeFileSync(SETUP_STATE_PATH, JSON.stringify(state, null, 2), 'utf8');
|
||||
}
|
||||
}
|
||||
32
src/config/telephony-config.controller.ts
Normal file
32
src/config/telephony-config.controller.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
import { Body, Controller, Get, Logger, Post, Put } from '@nestjs/common';
|
||||
import { TelephonyConfigService } from './telephony-config.service';
|
||||
import type { TelephonyConfig } from './telephony.defaults';
|
||||
|
||||
// Mounted under /api/config alongside theme/widget/setup-state.
|
||||
//
|
||||
// GET /api/config/telephony — masked (secrets returned as '***masked***')
|
||||
// PUT /api/config/telephony — admin update; '***masked***' is treated as "no change"
|
||||
// POST /api/config/telephony/reset — reset to defaults (admin)
|
||||
@Controller('api/config')
|
||||
export class TelephonyConfigController {
|
||||
private readonly logger = new Logger(TelephonyConfigController.name);
|
||||
|
||||
constructor(private readonly telephony: TelephonyConfigService) {}
|
||||
|
||||
@Get('telephony')
|
||||
getTelephony() {
|
||||
return this.telephony.getMaskedConfig();
|
||||
}
|
||||
|
||||
@Put('telephony')
|
||||
updateTelephony(@Body() body: Partial<TelephonyConfig>) {
|
||||
this.logger.log('Telephony config update request');
|
||||
return this.telephony.updateConfig(body);
|
||||
}
|
||||
|
||||
@Post('telephony/reset')
|
||||
resetTelephony() {
|
||||
this.logger.log('Telephony config reset request');
|
||||
return this.telephony.resetConfig();
|
||||
}
|
||||
}
|
||||
160
src/config/telephony-config.service.ts
Normal file
160
src/config/telephony-config.service.ts
Normal file
@@ -0,0 +1,160 @@
|
||||
import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
|
||||
import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';
|
||||
import { dirname, join } from 'path';
|
||||
import {
|
||||
DEFAULT_TELEPHONY_CONFIG,
|
||||
TELEPHONY_ENV_SEEDS,
|
||||
type TelephonyConfig,
|
||||
} from './telephony.defaults';
|
||||
|
||||
const CONFIG_PATH = join(process.cwd(), 'data', 'telephony.json');
|
||||
const BACKUP_DIR = join(process.cwd(), 'data', 'telephony-backups');
|
||||
|
||||
// File-backed telephony config. Replaces eight env vars (OZONETEL_*, SIP_*,
|
||||
// EXOTEL_*). On first boot we copy whatever those env vars hold into the
|
||||
// config file so existing deployments don't break — after that, the env vars
|
||||
// are no longer read by anything.
|
||||
//
|
||||
// Mirrors WidgetConfigService and ThemeService — load on init, in-memory
|
||||
// cache, file backups on every change.
|
||||
@Injectable()
|
||||
export class TelephonyConfigService implements OnModuleInit {
|
||||
private readonly logger = new Logger(TelephonyConfigService.name);
|
||||
private cached: TelephonyConfig | null = null;
|
||||
|
||||
onModuleInit() {
|
||||
this.ensureReady();
|
||||
}
|
||||
|
||||
getConfig(): TelephonyConfig {
|
||||
if (this.cached) return this.cached;
|
||||
return this.load();
|
||||
}
|
||||
|
||||
// Public-facing subset for the GET endpoint — masks the Exotel API token
|
||||
// so it can't be exfiltrated by an unauthenticated reader. The admin UI
|
||||
// gets the full config via getConfig() through the controller's PUT path
|
||||
// (the new value is supplied client-side, the old value is never displayed).
|
||||
getMaskedConfig() {
|
||||
const c = this.getConfig();
|
||||
return {
|
||||
...c,
|
||||
exotel: {
|
||||
...c.exotel,
|
||||
apiToken: c.exotel.apiToken ? '***masked***' : '',
|
||||
},
|
||||
ozonetel: {
|
||||
...c.ozonetel,
|
||||
agentPassword: c.ozonetel.agentPassword ? '***masked***' : '',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
updateConfig(updates: Partial<TelephonyConfig>): TelephonyConfig {
|
||||
const current = this.getConfig();
|
||||
// Deep-ish merge — each top-level group merges its own keys.
|
||||
const merged: TelephonyConfig = {
|
||||
ozonetel: { ...current.ozonetel, ...(updates.ozonetel ?? {}) },
|
||||
sip: { ...current.sip, ...(updates.sip ?? {}) },
|
||||
exotel: { ...current.exotel, ...(updates.exotel ?? {}) },
|
||||
version: (current.version ?? 0) + 1,
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
// Strip the masked sentinel — admin UI sends back '***masked***' for
|
||||
// unchanged secret fields. We treat that as "keep the existing value".
|
||||
if (merged.exotel.apiToken === '***masked***') {
|
||||
merged.exotel.apiToken = current.exotel.apiToken;
|
||||
}
|
||||
if (merged.ozonetel.agentPassword === '***masked***') {
|
||||
merged.ozonetel.agentPassword = current.ozonetel.agentPassword;
|
||||
}
|
||||
this.backup();
|
||||
this.writeFile(merged);
|
||||
this.cached = merged;
|
||||
this.logger.log(`Telephony config updated to v${merged.version}`);
|
||||
return merged;
|
||||
}
|
||||
|
||||
resetConfig(): TelephonyConfig {
|
||||
this.backup();
|
||||
const fresh = JSON.parse(JSON.stringify(DEFAULT_TELEPHONY_CONFIG)) as TelephonyConfig;
|
||||
this.writeFile(fresh);
|
||||
this.cached = fresh;
|
||||
this.logger.log('Telephony config reset to defaults');
|
||||
return fresh;
|
||||
}
|
||||
|
||||
// First-boot bootstrap: if no telephony.json exists yet, seed it from the
|
||||
// legacy env vars. After this runs once the env vars are dead code.
|
||||
private ensureReady(): TelephonyConfig {
|
||||
if (existsSync(CONFIG_PATH)) {
|
||||
return this.load();
|
||||
}
|
||||
const seeded: TelephonyConfig = JSON.parse(
|
||||
JSON.stringify(DEFAULT_TELEPHONY_CONFIG),
|
||||
) as TelephonyConfig;
|
||||
let appliedCount = 0;
|
||||
for (const seed of TELEPHONY_ENV_SEEDS) {
|
||||
const value = process.env[seed.env];
|
||||
if (value === undefined || value === '') continue;
|
||||
this.setNested(seeded, seed.path, value);
|
||||
appliedCount += 1;
|
||||
}
|
||||
seeded.version = 1;
|
||||
seeded.updatedAt = new Date().toISOString();
|
||||
this.writeFile(seeded);
|
||||
this.cached = seeded;
|
||||
this.logger.log(
|
||||
`Telephony config seeded from env (${appliedCount} env var${appliedCount === 1 ? '' : 's'} applied)`,
|
||||
);
|
||||
return seeded;
|
||||
}
|
||||
|
||||
private load(): TelephonyConfig {
|
||||
try {
|
||||
const raw = readFileSync(CONFIG_PATH, 'utf8');
|
||||
const parsed = JSON.parse(raw);
|
||||
const merged: TelephonyConfig = {
|
||||
ozonetel: { ...DEFAULT_TELEPHONY_CONFIG.ozonetel, ...(parsed.ozonetel ?? {}) },
|
||||
sip: { ...DEFAULT_TELEPHONY_CONFIG.sip, ...(parsed.sip ?? {}) },
|
||||
exotel: { ...DEFAULT_TELEPHONY_CONFIG.exotel, ...(parsed.exotel ?? {}) },
|
||||
version: parsed.version,
|
||||
updatedAt: parsed.updatedAt,
|
||||
};
|
||||
this.cached = merged;
|
||||
this.logger.log('Telephony config loaded from file');
|
||||
return merged;
|
||||
} catch (err) {
|
||||
this.logger.warn(`Failed to load telephony config, using defaults: ${err}`);
|
||||
const fresh = JSON.parse(JSON.stringify(DEFAULT_TELEPHONY_CONFIG)) as TelephonyConfig;
|
||||
this.cached = fresh;
|
||||
return fresh;
|
||||
}
|
||||
}
|
||||
|
||||
private setNested(obj: any, path: string[], value: string) {
|
||||
let cursor = obj;
|
||||
for (let i = 0; i < path.length - 1; i++) {
|
||||
if (!cursor[path[i]]) cursor[path[i]] = {};
|
||||
cursor = cursor[path[i]];
|
||||
}
|
||||
cursor[path[path.length - 1]] = value;
|
||||
}
|
||||
|
||||
private writeFile(cfg: TelephonyConfig) {
|
||||
const dir = dirname(CONFIG_PATH);
|
||||
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
|
||||
writeFileSync(CONFIG_PATH, JSON.stringify(cfg, null, 2), 'utf8');
|
||||
}
|
||||
|
||||
private backup() {
|
||||
try {
|
||||
if (!existsSync(CONFIG_PATH)) return;
|
||||
if (!existsSync(BACKUP_DIR)) mkdirSync(BACKUP_DIR, { recursive: true });
|
||||
const ts = new Date().toISOString().replace(/[:.]/g, '-');
|
||||
copyFileSync(CONFIG_PATH, join(BACKUP_DIR, `telephony-${ts}.json`));
|
||||
} catch (err) {
|
||||
this.logger.warn(`Telephony backup failed: ${err}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
77
src/config/telephony.defaults.ts
Normal file
77
src/config/telephony.defaults.ts
Normal file
@@ -0,0 +1,77 @@
|
||||
// Admin-editable telephony config. Holds Ozonetel cloud-call-center settings,
|
||||
// the Ozonetel SIP gateway info, and the Exotel REST API credentials.
|
||||
//
|
||||
// All of these used to live in env vars (OZONETEL_*, SIP_*, EXOTEL_*).
|
||||
// On first boot, TelephonyConfigService seeds this file from those env vars
|
||||
// so existing deployments keep working without manual migration. After that,
|
||||
// admins edit via the staff portal "Telephony" settings page and the env vars
|
||||
// are no longer read.
|
||||
//
|
||||
// SECRETS — note: EXOTEL_WEBHOOK_SECRET stays in env (true secret used for
|
||||
// inbound webhook HMAC verification). EXOTEL_API_TOKEN is stored here because
|
||||
// the admin must be able to rotate it from the UI. The GET endpoint masks it.
|
||||
|
||||
export type TelephonyConfig = {
|
||||
ozonetel: {
|
||||
// Default test agent — used by maintenance and provisioning flows.
|
||||
agentId: string;
|
||||
agentPassword: string;
|
||||
// Default DID (the hospital's published number).
|
||||
did: string;
|
||||
// Default SIP extension that maps to a softphone session.
|
||||
sipId: string;
|
||||
// Default outbound campaign name on Ozonetel CloudAgent.
|
||||
campaignName: string;
|
||||
};
|
||||
// Ozonetel WebRTC gateway used by the staff portal softphone.
|
||||
sip: {
|
||||
domain: string;
|
||||
wsPort: string;
|
||||
};
|
||||
// Exotel REST API credentials for inbound number management + SMS.
|
||||
exotel: {
|
||||
apiKey: string;
|
||||
apiToken: string;
|
||||
accountSid: string;
|
||||
subdomain: string;
|
||||
};
|
||||
version?: number;
|
||||
updatedAt?: string;
|
||||
};
|
||||
|
||||
export const DEFAULT_TELEPHONY_CONFIG: TelephonyConfig = {
|
||||
ozonetel: {
|
||||
agentId: '',
|
||||
agentPassword: '',
|
||||
did: '',
|
||||
sipId: '',
|
||||
campaignName: '',
|
||||
},
|
||||
sip: {
|
||||
domain: 'blr-pub-rtc4.ozonetel.com',
|
||||
wsPort: '444',
|
||||
},
|
||||
exotel: {
|
||||
apiKey: '',
|
||||
apiToken: '',
|
||||
accountSid: '',
|
||||
subdomain: 'api.exotel.com',
|
||||
},
|
||||
};
|
||||
|
||||
// Field-by-field mapping from legacy env var names to config paths. Used by
|
||||
// the first-boot seeder. Keep in sync with the migration target sites.
|
||||
export const TELEPHONY_ENV_SEEDS: Array<{ env: string; path: string[] }> = [
|
||||
// OZONETEL_AGENT_ID removed — agentId is per-user on the Agent entity,
|
||||
// not a sidecar-level config. All endpoints require agentId from caller.
|
||||
{ env: 'OZONETEL_AGENT_PASSWORD', path: ['ozonetel', 'agentPassword'] },
|
||||
{ env: 'OZONETEL_DID', path: ['ozonetel', 'did'] },
|
||||
{ env: 'OZONETEL_SIP_ID', path: ['ozonetel', 'sipId'] },
|
||||
{ env: 'OZONETEL_CAMPAIGN_NAME', path: ['ozonetel', 'campaignName'] },
|
||||
{ env: 'SIP_DOMAIN', path: ['sip', 'domain'] },
|
||||
{ env: 'SIP_WS_PORT', path: ['sip', 'wsPort'] },
|
||||
{ env: 'EXOTEL_API_KEY', path: ['exotel', 'apiKey'] },
|
||||
{ env: 'EXOTEL_API_TOKEN', path: ['exotel', 'apiToken'] },
|
||||
{ env: 'EXOTEL_ACCOUNT_SID', path: ['exotel', 'accountSid'] },
|
||||
{ env: 'EXOTEL_SUBDOMAIN', path: ['exotel', 'subdomain'] },
|
||||
];
|
||||
50
src/config/widget-config.controller.ts
Normal file
50
src/config/widget-config.controller.ts
Normal file
@@ -0,0 +1,50 @@
|
||||
import { Controller, Get, Put, Post, Body, Logger } from '@nestjs/common';
|
||||
import { WidgetConfigService } from './widget-config.service';
|
||||
import type { WidgetConfig } from './widget.defaults';
|
||||
|
||||
// Mounted under /api/config (same prefix as ThemeController).
|
||||
//
|
||||
// GET /api/config/widget — public subset, called by the embed
|
||||
// page to decide whether & how to load
|
||||
// widget.js
|
||||
// GET /api/config/widget/admin — full config incl. origins + metadata
|
||||
// PUT /api/config/widget — admin update (merge patch)
|
||||
// POST /api/config/widget/rotate-key — rotate the HMAC site key
|
||||
// POST /api/config/widget/reset — reset to defaults (regenerates key)
|
||||
//
|
||||
// TODO: protect the admin endpoints with the admin guard once the settings UI
|
||||
// ships. Matches the current ThemeController convention (also currently open).
|
||||
@Controller('api/config')
|
||||
export class WidgetConfigController {
|
||||
private readonly logger = new Logger(WidgetConfigController.name);
|
||||
|
||||
constructor(private readonly widgetConfig: WidgetConfigService) {}
|
||||
|
||||
@Get('widget')
|
||||
getPublicWidget() {
|
||||
return this.widgetConfig.getPublicConfig();
|
||||
}
|
||||
|
||||
@Get('widget/admin')
|
||||
getAdminWidget() {
|
||||
return this.widgetConfig.getConfig();
|
||||
}
|
||||
|
||||
@Put('widget')
|
||||
async updateWidget(@Body() body: Partial<WidgetConfig>) {
|
||||
this.logger.log('Widget config update request');
|
||||
return this.widgetConfig.updateConfig(body);
|
||||
}
|
||||
|
||||
@Post('widget/rotate-key')
|
||||
async rotateKey() {
|
||||
this.logger.log('Widget key rotation request');
|
||||
return this.widgetConfig.rotateKey();
|
||||
}
|
||||
|
||||
@Post('widget/reset')
|
||||
async resetWidget() {
|
||||
this.logger.log('Widget config reset request');
|
||||
return this.widgetConfig.resetConfig();
|
||||
}
|
||||
}
|
||||
202
src/config/widget-config.service.ts
Normal file
202
src/config/widget-config.service.ts
Normal file
@@ -0,0 +1,202 @@
|
||||
import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
|
||||
import { readFileSync, writeFileSync, existsSync, mkdirSync, copyFileSync } from 'fs';
|
||||
import { join, dirname } from 'path';
|
||||
import { DEFAULT_WIDGET_CONFIG, type WidgetConfig } from './widget.defaults';
|
||||
import { WidgetKeysService } from './widget-keys.service';
|
||||
import { ThemeService } from './theme.service';
|
||||
|
||||
const CONFIG_PATH = join(process.cwd(), 'data', 'widget.json');
|
||||
const BACKUP_DIR = join(process.cwd(), 'data', 'widget-backups');
|
||||
|
||||
// File-backed store for admin-editable widget configuration. Mirrors ThemeService:
|
||||
// - onModuleInit() → load from disk → ensure key exists (generate + persist)
|
||||
// - getConfig() → in-memory cached lookup
|
||||
// - updateConfig() → merge patch + backup + write + bump version
|
||||
// - rotateKey() → revoke old siteId in Redis + generate new + persist
|
||||
//
|
||||
// Also guarantees the key stays valid across Redis flushes: if the file has a
|
||||
// key but Redis doesn't know about its siteId, we silently re-register it on
|
||||
// boot so POST /api/widget/* requests keep authenticating.
|
||||
@Injectable()
|
||||
export class WidgetConfigService implements OnModuleInit {
|
||||
private readonly logger = new Logger(WidgetConfigService.name);
|
||||
private cached: WidgetConfig | null = null;
|
||||
|
||||
constructor(
|
||||
private readonly widgetKeys: WidgetKeysService,
|
||||
private readonly theme: ThemeService,
|
||||
) {}
|
||||
|
||||
// Hospital name comes from the theme — single source of truth. The widget
|
||||
// key's Redis label is just bookkeeping; pulling it from theme means
|
||||
// renaming the hospital via /branding-settings flows through to the next
|
||||
// key rotation automatically.
|
||||
private get hospitalName(): string {
|
||||
return this.theme.getTheme().brand.hospitalName;
|
||||
}
|
||||
|
||||
async onModuleInit() {
|
||||
await this.ensureReady();
|
||||
}
|
||||
|
||||
getConfig(): WidgetConfig {
|
||||
if (this.cached) return this.cached;
|
||||
return this.load();
|
||||
}
|
||||
|
||||
// Public-facing subset served from GET /api/config/widget. Only the fields
|
||||
// the embed bootstrap code needs — no origins, no hospital label, no
|
||||
// version metadata.
|
||||
getPublicConfig() {
|
||||
const c = this.getConfig();
|
||||
return {
|
||||
enabled: c.enabled,
|
||||
key: c.key,
|
||||
url: c.url,
|
||||
embed: c.embed,
|
||||
};
|
||||
}
|
||||
|
||||
async updateConfig(updates: Partial<WidgetConfig>): Promise<WidgetConfig> {
|
||||
const current = this.getConfig();
|
||||
const merged: WidgetConfig = {
|
||||
...current,
|
||||
...updates,
|
||||
embed: { ...current.embed, ...updates.embed },
|
||||
allowedOrigins: updates.allowedOrigins ?? current.allowedOrigins,
|
||||
version: (current.version ?? 0) + 1,
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
this.backup();
|
||||
this.writeFile(merged);
|
||||
this.cached = merged;
|
||||
this.logger.log(`Widget config updated to v${merged.version}`);
|
||||
return merged;
|
||||
}
|
||||
|
||||
// Revoke the current siteId in Redis, mint a new key with the current
|
||||
// theme.brand.hospitalName + allowedOrigins, persist both the Redis entry
|
||||
// and the config file. Used by admins to invalidate a leaked or stale key.
|
||||
async rotateKey(): Promise<WidgetConfig> {
|
||||
const current = this.getConfig();
|
||||
if (current.siteId) {
|
||||
await this.widgetKeys.revokeKey(current.siteId).catch(err => {
|
||||
this.logger.warn(`Revoke of old siteId ${current.siteId} failed: ${err}`);
|
||||
});
|
||||
}
|
||||
const { key, siteKey } = this.widgetKeys.generateKey(
|
||||
this.hospitalName,
|
||||
current.allowedOrigins,
|
||||
);
|
||||
await this.widgetKeys.saveKey(siteKey);
|
||||
|
||||
const updated: WidgetConfig = {
|
||||
...current,
|
||||
key,
|
||||
siteId: siteKey.siteId,
|
||||
version: (current.version ?? 0) + 1,
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
this.backup();
|
||||
this.writeFile(updated);
|
||||
this.cached = updated;
|
||||
this.logger.log(`Widget key rotated: new siteId=${siteKey.siteId}`);
|
||||
return updated;
|
||||
}
|
||||
|
||||
async resetConfig(): Promise<WidgetConfig> {
|
||||
this.backup();
|
||||
this.writeFile(DEFAULT_WIDGET_CONFIG);
|
||||
this.cached = { ...DEFAULT_WIDGET_CONFIG };
|
||||
this.logger.log('Widget config reset to defaults');
|
||||
return this.ensureReady();
|
||||
}
|
||||
|
||||
private async ensureReady(): Promise<WidgetConfig> {
|
||||
let cfg = this.load();
|
||||
|
||||
// First boot or missing key → generate + persist.
|
||||
const needsKey = !cfg.key || !cfg.siteId;
|
||||
if (needsKey) {
|
||||
this.logger.log('No widget key in config — generating a fresh one');
|
||||
const { key, siteKey } = this.widgetKeys.generateKey(
|
||||
this.hospitalName,
|
||||
cfg.allowedOrigins,
|
||||
);
|
||||
await this.widgetKeys.saveKey(siteKey);
|
||||
cfg = {
|
||||
...cfg,
|
||||
key,
|
||||
siteId: siteKey.siteId,
|
||||
// Allow WIDGET_PUBLIC_URL env var to seed the url field on
|
||||
// first boot, so dev/staging don't start with a blank URL.
|
||||
url: cfg.url || process.env.WIDGET_PUBLIC_URL || '',
|
||||
version: (cfg.version ?? 0) + 1,
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
this.writeFile(cfg);
|
||||
this.cached = cfg;
|
||||
this.logger.log(`Widget key generated: siteId=${siteKey.siteId}`);
|
||||
return cfg;
|
||||
}
|
||||
|
||||
// Key exists on disk but may be missing from Redis (e.g., Redis
|
||||
// flushed or sidecar migrated to new Redis). Re-register so requests
|
||||
// validate correctly. This is silent — callers don't care.
|
||||
const validated = await this.widgetKeys.validateKey(cfg.key).catch(() => null);
|
||||
if (!validated) {
|
||||
this.logger.warn(
|
||||
`Widget key in config not found in Redis — re-registering siteId=${cfg.siteId}`,
|
||||
);
|
||||
await this.widgetKeys.saveKey({
|
||||
siteId: cfg.siteId,
|
||||
hospitalName: this.hospitalName,
|
||||
allowedOrigins: cfg.allowedOrigins,
|
||||
active: true,
|
||||
createdAt: cfg.updatedAt ?? new Date().toISOString(),
|
||||
});
|
||||
}
|
||||
return cfg;
|
||||
}
|
||||
|
||||
private load(): WidgetConfig {
|
||||
try {
|
||||
if (existsSync(CONFIG_PATH)) {
|
||||
const raw = readFileSync(CONFIG_PATH, 'utf8');
|
||||
const parsed = JSON.parse(raw);
|
||||
const merged: WidgetConfig = {
|
||||
...DEFAULT_WIDGET_CONFIG,
|
||||
...parsed,
|
||||
embed: { ...DEFAULT_WIDGET_CONFIG.embed, ...parsed.embed },
|
||||
allowedOrigins: parsed.allowedOrigins ?? DEFAULT_WIDGET_CONFIG.allowedOrigins,
|
||||
};
|
||||
this.cached = merged;
|
||||
this.logger.log('Widget config loaded from file');
|
||||
return merged;
|
||||
}
|
||||
} catch (err) {
|
||||
this.logger.warn(`Failed to load widget config: ${err}`);
|
||||
}
|
||||
const fallback: WidgetConfig = { ...DEFAULT_WIDGET_CONFIG };
|
||||
this.cached = fallback;
|
||||
this.logger.log('Using default widget config');
|
||||
return fallback;
|
||||
}
|
||||
|
||||
private writeFile(cfg: WidgetConfig) {
|
||||
const dir = dirname(CONFIG_PATH);
|
||||
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
|
||||
writeFileSync(CONFIG_PATH, JSON.stringify(cfg, null, 2), 'utf8');
|
||||
}
|
||||
|
||||
private backup() {
|
||||
try {
|
||||
if (!existsSync(CONFIG_PATH)) return;
|
||||
if (!existsSync(BACKUP_DIR)) mkdirSync(BACKUP_DIR, { recursive: true });
|
||||
const ts = new Date().toISOString().replace(/[:.]/g, '-');
|
||||
copyFileSync(CONFIG_PATH, join(BACKUP_DIR, `widget-${ts}.json`));
|
||||
} catch (err) {
|
||||
this.logger.warn(`Widget config backup failed: ${err}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
94
src/config/widget-keys.service.ts
Normal file
94
src/config/widget-keys.service.ts
Normal file
@@ -0,0 +1,94 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { createHmac, timingSafeEqual, randomUUID } from 'crypto';
|
||||
import { SessionService } from '../auth/session.service';
|
||||
import type { WidgetSiteKey } from '../widget/widget.types';
|
||||
|
||||
const KEY_PREFIX = 'widget:keys:';
|
||||
|
||||
@Injectable()
|
||||
export class WidgetKeysService {
|
||||
private readonly logger = new Logger(WidgetKeysService.name);
|
||||
private readonly secret: string;
|
||||
|
||||
constructor(
|
||||
private config: ConfigService,
|
||||
private session: SessionService,
|
||||
) {
|
||||
this.secret = process.env.WIDGET_SECRET ?? config.get<string>('WIDGET_SECRET') ?? 'helix-widget-default-secret';
|
||||
}
|
||||
|
||||
generateKey(hospitalName: string, allowedOrigins: string[]): { key: string; siteKey: WidgetSiteKey } {
|
||||
const siteId = randomUUID().replace(/-/g, '').substring(0, 16);
|
||||
const signature = this.sign(siteId);
|
||||
const key = `${siteId}.${signature}`;
|
||||
|
||||
const siteKey: WidgetSiteKey = {
|
||||
siteId,
|
||||
hospitalName,
|
||||
allowedOrigins,
|
||||
active: true,
|
||||
createdAt: new Date().toISOString(),
|
||||
};
|
||||
|
||||
return { key, siteKey };
|
||||
}
|
||||
|
||||
async saveKey(siteKey: WidgetSiteKey): Promise<void> {
|
||||
await this.session.setCachePersistent(`${KEY_PREFIX}${siteKey.siteId}`, JSON.stringify(siteKey));
|
||||
this.logger.log(`Widget key saved: ${siteKey.siteId} (${siteKey.hospitalName})`);
|
||||
}
|
||||
|
||||
async validateKey(rawKey: string): Promise<WidgetSiteKey | null> {
|
||||
const dotIndex = rawKey.indexOf('.');
|
||||
if (dotIndex === -1) return null;
|
||||
|
||||
const siteId = rawKey.substring(0, dotIndex);
|
||||
const signature = rawKey.substring(dotIndex + 1);
|
||||
|
||||
const expected = this.sign(siteId);
|
||||
try {
|
||||
if (!timingSafeEqual(Buffer.from(signature, 'hex'), Buffer.from(expected, 'hex'))) return null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
|
||||
const data = await this.session.getCache(`${KEY_PREFIX}${siteId}`);
|
||||
if (!data) return null;
|
||||
|
||||
const siteKey: WidgetSiteKey = JSON.parse(data);
|
||||
if (!siteKey.active) return null;
|
||||
|
||||
return siteKey;
|
||||
}
|
||||
|
||||
validateOrigin(siteKey: WidgetSiteKey, origin: string | undefined): boolean {
|
||||
if (!origin) return true; // Allow no-origin for dev/testing
|
||||
if (siteKey.allowedOrigins.length === 0) return true;
|
||||
return siteKey.allowedOrigins.some(allowed => origin.startsWith(allowed));
|
||||
}
|
||||
|
||||
async listKeys(): Promise<WidgetSiteKey[]> {
|
||||
const keys = await this.session.scanKeys(`${KEY_PREFIX}*`);
|
||||
const results: WidgetSiteKey[] = [];
|
||||
for (const key of keys) {
|
||||
const data = await this.session.getCache(key);
|
||||
if (data) results.push(JSON.parse(data));
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
async revokeKey(siteId: string): Promise<boolean> {
|
||||
const data = await this.session.getCache(`${KEY_PREFIX}${siteId}`);
|
||||
if (!data) return false;
|
||||
const siteKey: WidgetSiteKey = JSON.parse(data);
|
||||
siteKey.active = false;
|
||||
await this.session.setCachePersistent(`${KEY_PREFIX}${siteId}`, JSON.stringify(siteKey));
|
||||
this.logger.log(`Widget key revoked: ${siteId}`);
|
||||
return true;
|
||||
}
|
||||
|
||||
private sign(data: string): string {
|
||||
return createHmac('sha256', this.secret).update(data).digest('hex');
|
||||
}
|
||||
}
|
||||
46
src/config/widget.defaults.ts
Normal file
46
src/config/widget.defaults.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
// Shape of the website-widget configuration, stored in data/widget.json.
|
||||
// Mirrors the theme config pattern — file-backed, versioned, admin-editable.
|
||||
export type WidgetConfig = {
|
||||
// Master feature flag. When false, the widget does not render anywhere.
|
||||
enabled: boolean;
|
||||
|
||||
// HMAC-signed site key the embed script passes as data-key. Auto-generated
|
||||
// on first boot if empty. Rotate via POST /api/config/widget/rotate-key.
|
||||
key: string;
|
||||
|
||||
// Stable site identifier derived from the key. Used for Redis lookup and
|
||||
// revocation. Populated alongside `key`.
|
||||
siteId: string;
|
||||
|
||||
// Public base URL where widget.js is hosted. Typically the sidecar host.
|
||||
// If empty, the embed page falls back to its own VITE_API_URL at fetch time.
|
||||
url: string;
|
||||
|
||||
// Origin allowlist. Empty array means any origin is accepted (test mode).
|
||||
// Set tight values in production: ['https://hospital.com'].
|
||||
allowedOrigins: string[];
|
||||
|
||||
// Embed toggles — where the widget should render. Kept as an object so we
|
||||
// can add other surfaces (public landing page, portal, etc.) without a
|
||||
// breaking schema change.
|
||||
embed: {
|
||||
// Show on the staff login page. Useful for testing without a public
|
||||
// landing page; turn off in production.
|
||||
loginPage: boolean;
|
||||
};
|
||||
|
||||
// Bookkeeping — incremented on every update, like the theme config.
|
||||
version?: number;
|
||||
updatedAt?: string;
|
||||
};
|
||||
|
||||
export const DEFAULT_WIDGET_CONFIG: WidgetConfig = {
|
||||
enabled: true,
|
||||
key: '',
|
||||
siteId: '',
|
||||
url: '',
|
||||
allowedOrigins: [],
|
||||
embed: {
|
||||
loginPage: true,
|
||||
},
|
||||
};
|
||||
@@ -8,6 +8,7 @@ import type { CallCompletedEvent } from '../event-types';
|
||||
import { PlatformGraphqlService } from '../../platform/platform-graphql.service';
|
||||
import { createAiModel } from '../../ai/ai-provider';
|
||||
import type { LanguageModel } from 'ai';
|
||||
import { AiConfigService } from '../../config/ai-config.service';
|
||||
|
||||
@Injectable()
|
||||
export class AiInsightConsumer implements OnModuleInit {
|
||||
@@ -18,8 +19,15 @@ export class AiInsightConsumer implements OnModuleInit {
|
||||
private eventBus: EventBusService,
|
||||
private platform: PlatformGraphqlService,
|
||||
private config: ConfigService,
|
||||
private aiConfig: AiConfigService,
|
||||
) {
|
||||
this.aiModel = createAiModel(config);
|
||||
const cfg = aiConfig.getConfig();
|
||||
this.aiModel = createAiModel({
|
||||
provider: cfg.provider,
|
||||
model: cfg.model,
|
||||
anthropicApiKey: config.get<string>('ai.anthropicApiKey'),
|
||||
openaiApiKey: config.get<string>('ai.openaiApiKey'),
|
||||
});
|
||||
}
|
||||
|
||||
onModuleInit() {
|
||||
@@ -74,11 +82,9 @@ export class AiInsightConsumer implements OnModuleInit {
|
||||
summary: z.string().describe('2-3 sentence summary of this lead based on all their interactions'),
|
||||
suggestedAction: z.string().describe('One clear next action for the agent'),
|
||||
}),
|
||||
system: `You are a CRM assistant for Global Hospital Bangalore.
|
||||
Generate a brief, actionable insight about this lead based on their interaction history.
|
||||
Be specific — reference actual dates, dispositions, and patterns.
|
||||
If the lead has booked appointments, mention upcoming ones.
|
||||
If they keep calling about the same thing, note the pattern.`,
|
||||
system: this.aiConfig.renderPrompt('callInsight', {
|
||||
hospitalName: process.env.HOSPITAL_NAME ?? 'the hospital',
|
||||
}),
|
||||
prompt: `Lead: ${leadName}
|
||||
Status: ${lead.status ?? 'Unknown'}
|
||||
Source: ${lead.source ?? 'Unknown'}
|
||||
|
||||
15
src/main.ts
15
src/main.ts
@@ -1,9 +1,11 @@
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import type { NestExpressApplication } from '@nestjs/platform-express';
|
||||
import { join } from 'path';
|
||||
import { AppModule } from './app.module';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
|
||||
async function bootstrap() {
|
||||
const app = await NestFactory.create(AppModule);
|
||||
const app = await NestFactory.create<NestExpressApplication>(AppModule);
|
||||
const config = app.get(ConfigService);
|
||||
|
||||
app.enableCors({
|
||||
@@ -11,6 +13,17 @@ async function bootstrap() {
|
||||
credentials: true,
|
||||
});
|
||||
|
||||
// Serve widget.js and other static files from /public
|
||||
// In dev mode __dirname = src/, in prod __dirname = dist/ — resolve from process.cwd()
|
||||
app.useStaticAssets(join(process.cwd(), 'public'), {
|
||||
setHeaders: (res, path) => {
|
||||
if (path.endsWith('.js')) {
|
||||
res.setHeader('Cache-Control', 'public, max-age=3600');
|
||||
res.setHeader('Access-Control-Allow-Origin', '*');
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const port = config.get('port');
|
||||
await app.listen(port);
|
||||
console.log(`Helix Engage Server running on port ${port}`);
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { Controller, Post, UseGuards, Logger } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { Body, Controller, HttpException, Post, UseGuards, Logger } from '@nestjs/common';
|
||||
import { MaintGuard } from './maint.guard';
|
||||
import { OzonetelAgentService } from '../ozonetel/ozonetel-agent.service';
|
||||
import { PlatformGraphqlService } from '../platform/platform-graphql.service';
|
||||
import { SessionService } from '../auth/session.service';
|
||||
import { SupervisorService } from '../supervisor/supervisor.service';
|
||||
import { CallerResolutionService } from '../caller/caller-resolution.service';
|
||||
import { TelephonyConfigService } from '../config/telephony-config.service';
|
||||
|
||||
@Controller('api/maint')
|
||||
@UseGuards(MaintGuard)
|
||||
@@ -13,7 +13,7 @@ export class MaintController {
|
||||
private readonly logger = new Logger(MaintController.name);
|
||||
|
||||
constructor(
|
||||
private readonly config: ConfigService,
|
||||
private readonly telephony: TelephonyConfigService,
|
||||
private readonly ozonetel: OzonetelAgentService,
|
||||
private readonly platform: PlatformGraphqlService,
|
||||
private readonly session: SessionService,
|
||||
@@ -22,10 +22,14 @@ export class MaintController {
|
||||
) {}
|
||||
|
||||
@Post('force-ready')
|
||||
async forceReady() {
|
||||
const agentId = this.config.get<string>('OZONETEL_AGENT_ID') ?? 'agent3';
|
||||
const password = process.env.OZONETEL_AGENT_PASSWORD ?? 'Test123$';
|
||||
const sipId = this.config.get<string>('OZONETEL_SIP_ID') ?? '521814';
|
||||
async forceReady(@Body() body: { agentId: string }) {
|
||||
if (!body?.agentId) throw new HttpException('agentId required', 400);
|
||||
const agentId = body.agentId;
|
||||
const oz = this.telephony.getConfig().ozonetel;
|
||||
const password = oz.agentPassword;
|
||||
if (!password) throw new HttpException('agent password not configured', 400);
|
||||
const sipId = oz.sipId;
|
||||
if (!sipId) throw new HttpException('SIP ID not configured', 400);
|
||||
|
||||
this.logger.log(`[MAINT] Force ready: agent=${agentId}`);
|
||||
|
||||
@@ -47,8 +51,9 @@ export class MaintController {
|
||||
}
|
||||
|
||||
@Post('unlock-agent')
|
||||
async unlockAgent() {
|
||||
const agentId = this.config.get<string>('OZONETEL_AGENT_ID') ?? 'agent3';
|
||||
async unlockAgent(@Body() body: { agentId: string }) {
|
||||
if (!body?.agentId) throw new HttpException('agentId required', 400);
|
||||
const agentId = body.agentId;
|
||||
this.logger.log(`[MAINT] Unlock agent session: ${agentId}`);
|
||||
|
||||
try {
|
||||
|
||||
45
src/masterdata/masterdata.controller.ts
Normal file
45
src/masterdata/masterdata.controller.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
import { Controller, Get, Query, Logger } from '@nestjs/common';
|
||||
import { MasterdataService } from './masterdata.service';
|
||||
|
||||
@Controller('api/masterdata')
|
||||
export class MasterdataController {
|
||||
private readonly logger = new Logger(MasterdataController.name);
|
||||
|
||||
constructor(private masterdata: MasterdataService) {}
|
||||
|
||||
@Get('departments')
|
||||
async departments() {
|
||||
return this.masterdata.getDepartments();
|
||||
}
|
||||
|
||||
@Get('doctors')
|
||||
async doctors() {
|
||||
return this.masterdata.getDoctors();
|
||||
}
|
||||
|
||||
@Get('clinics')
|
||||
async clinics() {
|
||||
return this.masterdata.getClinics();
|
||||
}
|
||||
|
||||
// Available time slots for a doctor on a given date.
|
||||
// Computed from DoctorVisitSlot entities (doctor × clinic × dayOfWeek).
|
||||
// Returns 30-min slots within the doctor's visiting window for that day.
|
||||
//
|
||||
// GET /api/masterdata/slots?doctorId=xxx&date=2026-04-15
|
||||
@Get('slots')
|
||||
async slots(
|
||||
@Query('doctorId') doctorId: string,
|
||||
@Query('date') date: string,
|
||||
) {
|
||||
if (!doctorId || !date) return [];
|
||||
return this.masterdata.getAvailableSlots(doctorId, date);
|
||||
}
|
||||
|
||||
// Force cache refresh (admin use)
|
||||
@Get('refresh')
|
||||
async refresh() {
|
||||
await this.masterdata.invalidateAll();
|
||||
return { refreshed: true };
|
||||
}
|
||||
}
|
||||
13
src/masterdata/masterdata.module.ts
Normal file
13
src/masterdata/masterdata.module.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { PlatformModule } from '../platform/platform.module';
|
||||
import { AuthModule } from '../auth/auth.module';
|
||||
import { MasterdataController } from './masterdata.controller';
|
||||
import { MasterdataService } from './masterdata.service';
|
||||
|
||||
@Module({
|
||||
imports: [PlatformModule, AuthModule],
|
||||
controllers: [MasterdataController],
|
||||
providers: [MasterdataService],
|
||||
exports: [MasterdataService],
|
||||
})
|
||||
export class MasterdataModule {}
|
||||
183
src/masterdata/masterdata.service.ts
Normal file
183
src/masterdata/masterdata.service.ts
Normal file
@@ -0,0 +1,183 @@
|
||||
import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { PlatformGraphqlService } from '../platform/platform-graphql.service';
|
||||
import { SessionService } from '../auth/session.service';
|
||||
|
||||
// Master data: cached lookups for departments, doctors, clinics.
|
||||
// Fetched from the platform on first request, cached in Redis with TTL.
|
||||
// Frontend dropdowns use these instead of direct GraphQL queries.
|
||||
|
||||
const CACHE_TTL = 300; // 5 minutes
|
||||
const KEY_DEPARTMENTS = 'masterdata:departments';
|
||||
const KEY_DOCTORS = 'masterdata:doctors';
|
||||
const KEY_CLINICS = 'masterdata:clinics';
|
||||
|
||||
@Injectable()
|
||||
export class MasterdataService implements OnModuleInit {
|
||||
private readonly logger = new Logger(MasterdataService.name);
|
||||
private readonly apiKey: string;
|
||||
|
||||
constructor(
|
||||
private config: ConfigService,
|
||||
private platform: PlatformGraphqlService,
|
||||
private cache: SessionService,
|
||||
) {
|
||||
this.apiKey = this.config.get<string>('platform.apiKey') ?? process.env.PLATFORM_API_KEY ?? '';
|
||||
}
|
||||
|
||||
async onModuleInit() {
|
||||
// Warm cache on startup
|
||||
try {
|
||||
await this.getDepartments();
|
||||
await this.getDoctors();
|
||||
await this.getClinics();
|
||||
this.logger.log('Master data cache warmed');
|
||||
} catch (err: any) {
|
||||
this.logger.warn(`Cache warm failed: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async getDepartments(): Promise<string[]> {
|
||||
const cached = await this.cache.getCache(KEY_DEPARTMENTS);
|
||||
if (cached) return JSON.parse(cached);
|
||||
|
||||
const auth = `Bearer ${this.apiKey}`;
|
||||
const data = await this.platform.queryWithAuth<any>(
|
||||
`{ doctors(first: 500) { edges { node { department } } } }`,
|
||||
undefined, auth,
|
||||
);
|
||||
|
||||
const departments = Array.from(new Set(
|
||||
data.doctors.edges
|
||||
.map((e: any) => e.node.department)
|
||||
.filter((d: string) => d && d.trim()),
|
||||
)).sort() as string[];
|
||||
|
||||
await this.cache.setCache(KEY_DEPARTMENTS, JSON.stringify(departments), CACHE_TTL);
|
||||
this.logger.log(`Cached ${departments.length} departments`);
|
||||
return departments;
|
||||
}
|
||||
|
||||
async getDoctors(): Promise<Array<{ id: string; name: string; department: string; qualifications: string }>> {
|
||||
const cached = await this.cache.getCache(KEY_DOCTORS);
|
||||
if (cached) return JSON.parse(cached);
|
||||
|
||||
const auth = `Bearer ${this.apiKey}`;
|
||||
const data = await this.platform.queryWithAuth<any>(
|
||||
`{ doctors(first: 500) { edges { node {
|
||||
id name department qualifications specialty active
|
||||
fullName { firstName lastName }
|
||||
} } } }`,
|
||||
undefined, auth,
|
||||
);
|
||||
|
||||
const doctors = data.doctors.edges
|
||||
.map((e: any) => ({
|
||||
id: e.node.id,
|
||||
name: e.node.name ?? `${e.node.fullName?.firstName ?? ''} ${e.node.fullName?.lastName ?? ''}`.trim(),
|
||||
department: e.node.department ?? '',
|
||||
qualifications: e.node.qualifications ?? '',
|
||||
specialty: e.node.specialty ?? '',
|
||||
active: e.node.active ?? true,
|
||||
}))
|
||||
.filter((d: any) => d.active !== false);
|
||||
|
||||
await this.cache.setCache(KEY_DOCTORS, JSON.stringify(doctors), CACHE_TTL);
|
||||
this.logger.log(`Cached ${doctors.length} doctors`);
|
||||
return doctors;
|
||||
}
|
||||
|
||||
async getClinics(): Promise<Array<{ id: string; name: string; phone: string; address: string; opensAt: string; closesAt: string }>> {
|
||||
const cached = await this.cache.getCache(KEY_CLINICS);
|
||||
if (cached) return JSON.parse(cached);
|
||||
|
||||
const auth = `Bearer ${this.apiKey}`;
|
||||
const data = await this.platform.queryWithAuth<any>(
|
||||
`{ clinics(first: 50) { edges { node {
|
||||
id clinicName status opensAt closesAt
|
||||
phone { primaryPhoneNumber }
|
||||
addressCustom { addressCity addressState }
|
||||
} } } }`,
|
||||
undefined, auth,
|
||||
);
|
||||
|
||||
const clinics = data.clinics.edges
|
||||
.filter((e: any) => e.node.status !== 'INACTIVE')
|
||||
.map((e: any) => ({
|
||||
id: e.node.id,
|
||||
name: e.node.clinicName ?? '',
|
||||
phone: e.node.phone?.primaryPhoneNumber ?? '',
|
||||
opensAt: e.node.opensAt ?? '08:00',
|
||||
closesAt: e.node.closesAt ?? '20:00',
|
||||
address: [e.node.addressCustom?.addressCity, e.node.addressCustom?.addressState].filter(Boolean).join(', '),
|
||||
}));
|
||||
|
||||
await this.cache.setCache(KEY_CLINICS, JSON.stringify(clinics), CACHE_TTL);
|
||||
this.logger.log(`Cached ${clinics.length} clinics`);
|
||||
return clinics;
|
||||
}
|
||||
|
||||
// Available time slots for a doctor on a given date.
|
||||
// Reads DoctorVisitSlot entities for the matching dayOfWeek,
|
||||
// then generates 30-min slots within each visiting window.
|
||||
async getAvailableSlots(doctorId: string, date: string): Promise<Array<{ time: string; label: string; clinicId: string; clinicName: string }>> {
|
||||
const dayOfWeek = new Date(date).toLocaleDateString('en-US', { weekday: 'long' }).toUpperCase();
|
||||
const cacheKey = `masterdata:slots:${doctorId}:${dayOfWeek}`;
|
||||
|
||||
const cached = await this.cache.getCache(cacheKey);
|
||||
if (cached) return JSON.parse(cached);
|
||||
|
||||
const auth = `Bearer ${this.apiKey}`;
|
||||
const data = await this.platform.queryWithAuth<any>(
|
||||
`{ doctorVisitSlots(first: 100, filter: { doctorId: { eq: "${doctorId}" }, dayOfWeek: { eq: ${dayOfWeek} } }) {
|
||||
edges { node { id startTime endTime clinic { id clinicName } } }
|
||||
} }`,
|
||||
undefined, auth,
|
||||
);
|
||||
|
||||
const slots: Array<{ time: string; label: string; clinicId: string; clinicName: string }> = [];
|
||||
|
||||
for (const edge of data.doctorVisitSlots?.edges ?? []) {
|
||||
const node = edge.node;
|
||||
const clinicId = node.clinic?.id ?? '';
|
||||
const clinicName = node.clinic?.clinicName ?? '';
|
||||
const startTime = node.startTime ?? '09:00';
|
||||
const endTime = node.endTime ?? '17:00';
|
||||
|
||||
// Generate 30-min slots within visiting window
|
||||
const [startH, startM] = startTime.split(':').map(Number);
|
||||
const [endH, endM] = endTime.split(':').map(Number);
|
||||
let h = startH, m = startM ?? 0;
|
||||
const endMin = endH * 60 + (endM ?? 0);
|
||||
|
||||
while (h * 60 + m < endMin) {
|
||||
const hh = h.toString().padStart(2, '0');
|
||||
const mm = m.toString().padStart(2, '0');
|
||||
const ampm = h < 12 ? 'AM' : 'PM';
|
||||
const displayH = h === 0 ? 12 : h > 12 ? h - 12 : h;
|
||||
slots.push({
|
||||
time: `${hh}:${mm}`,
|
||||
label: `${displayH}:${mm.toString().padStart(2, '0')} ${ampm} — ${clinicName}`,
|
||||
clinicId,
|
||||
clinicName,
|
||||
});
|
||||
m += 30;
|
||||
if (m >= 60) { h++; m = 0; }
|
||||
}
|
||||
}
|
||||
|
||||
// Sort by time
|
||||
slots.sort((a, b) => a.time.localeCompare(b.time));
|
||||
|
||||
await this.cache.setCache(cacheKey, JSON.stringify(slots), CACHE_TTL);
|
||||
this.logger.log(`Generated ${slots.length} slots for doctor ${doctorId} on ${dayOfWeek}`);
|
||||
return slots;
|
||||
}
|
||||
|
||||
async invalidateAll(): Promise<void> {
|
||||
await this.cache.setCache(KEY_DEPARTMENTS, '', 1);
|
||||
await this.cache.setCache(KEY_DOCTORS, '', 1);
|
||||
await this.cache.setCache(KEY_CLINICS, '', 1);
|
||||
this.logger.log('Master data cache invalidated');
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,17 @@
|
||||
import { Controller, Get, Query, Logger, Header } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { TelephonyConfigService } from '../config/telephony-config.service';
|
||||
|
||||
@Controller('kookoo')
|
||||
export class KookooIvrController {
|
||||
private readonly logger = new Logger(KookooIvrController.name);
|
||||
private readonly sipId: string;
|
||||
private readonly callerId: string;
|
||||
|
||||
constructor(private config: ConfigService) {
|
||||
this.sipId = process.env.OZONETEL_SIP_ID ?? '523590';
|
||||
this.callerId = process.env.OZONETEL_DID ?? '918041763265';
|
||||
constructor(private telephony: TelephonyConfigService) {}
|
||||
|
||||
private get sipId(): string {
|
||||
return this.telephony.getConfig().ozonetel.sipId || '523590';
|
||||
}
|
||||
private get callerId(): string {
|
||||
return this.telephony.getConfig().ozonetel.did || '918041763265';
|
||||
}
|
||||
|
||||
@Get('ivr')
|
||||
|
||||
@@ -1,29 +1,28 @@
|
||||
import { Controller, Post, Get, Body, Query, Logger, HttpException } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { OzonetelAgentService } from './ozonetel-agent.service';
|
||||
import { MissedQueueService } from '../worklist/missed-queue.service';
|
||||
import { PlatformGraphqlService } from '../platform/platform-graphql.service';
|
||||
import { EventBusService } from '../events/event-bus.service';
|
||||
import { Topics } from '../events/event-types';
|
||||
import { TelephonyConfigService } from '../config/telephony-config.service';
|
||||
import { SupervisorService } from '../supervisor/supervisor.service';
|
||||
|
||||
@Controller('api/ozonetel')
|
||||
export class OzonetelAgentController {
|
||||
private readonly logger = new Logger(OzonetelAgentController.name);
|
||||
private readonly defaultAgentId: string;
|
||||
private readonly defaultAgentPassword: string;
|
||||
|
||||
private readonly defaultSipId: string;
|
||||
|
||||
constructor(
|
||||
private readonly ozonetelAgent: OzonetelAgentService,
|
||||
private readonly config: ConfigService,
|
||||
private readonly telephony: TelephonyConfigService,
|
||||
private readonly missedQueue: MissedQueueService,
|
||||
private readonly platform: PlatformGraphqlService,
|
||||
private readonly eventBus: EventBusService,
|
||||
) {
|
||||
this.defaultAgentId = config.get<string>('OZONETEL_AGENT_ID') ?? 'agent3';
|
||||
this.defaultAgentPassword = config.get<string>('OZONETEL_AGENT_PASSWORD') ?? '';
|
||||
this.defaultSipId = config.get<string>('OZONETEL_SIP_ID') ?? '521814';
|
||||
private readonly supervisor: SupervisorService,
|
||||
) {}
|
||||
|
||||
private requireAgentId(agentId: string | undefined | null): string {
|
||||
if (!agentId) throw new HttpException('agentId required', 400);
|
||||
return agentId;
|
||||
}
|
||||
|
||||
@Post('agent-login')
|
||||
@@ -62,17 +61,18 @@ export class OzonetelAgentController {
|
||||
|
||||
@Post('agent-state')
|
||||
async agentState(
|
||||
@Body() body: { state: 'Ready' | 'Pause'; pauseReason?: string },
|
||||
@Body() body: { agentId: string; state: 'Ready' | 'Pause'; pauseReason?: string },
|
||||
) {
|
||||
if (!body.state) {
|
||||
throw new HttpException('state required', 400);
|
||||
}
|
||||
const agentId = this.requireAgentId(body.agentId);
|
||||
|
||||
this.logger.log(`[AGENT-STATE] ${this.defaultAgentId} → ${body.state} (${body.pauseReason ?? 'none'})`);
|
||||
this.logger.log(`[AGENT-STATE] ${agentId} → ${body.state} (${body.pauseReason ?? 'none'})`);
|
||||
|
||||
try {
|
||||
const result = await this.ozonetelAgent.changeAgentState({
|
||||
agentId: this.defaultAgentId,
|
||||
agentId,
|
||||
state: body.state,
|
||||
pauseReason: body.pauseReason,
|
||||
});
|
||||
@@ -81,7 +81,7 @@ export class OzonetelAgentController {
|
||||
// Auto-assign missed call when agent goes Ready
|
||||
if (body.state === 'Ready') {
|
||||
try {
|
||||
const assigned = await this.missedQueue.assignNext(this.defaultAgentId);
|
||||
const assigned = await this.missedQueue.assignNext(agentId);
|
||||
if (assigned) {
|
||||
this.logger.log(`[AGENT-STATE] Auto-assigned missed call ${assigned.id}`);
|
||||
return { ...result, assignedCall: assigned };
|
||||
@@ -107,6 +107,7 @@ export class OzonetelAgentController {
|
||||
@Body() body: {
|
||||
ucid: string;
|
||||
disposition: string;
|
||||
agentId: string;
|
||||
callerPhone?: string;
|
||||
direction?: string;
|
||||
durationSec?: number;
|
||||
@@ -119,13 +120,17 @@ export class OzonetelAgentController {
|
||||
throw new HttpException('ucid and disposition required', 400);
|
||||
}
|
||||
|
||||
const agentId = this.requireAgentId(body.agentId);
|
||||
const ozonetelDisposition = this.mapToOzonetelDisposition(body.disposition);
|
||||
|
||||
this.logger.log(`[DISPOSE] ucid=${body.ucid} disposition=${body.disposition} → ozonetel="${ozonetelDisposition}" agentId=${this.defaultAgentId} callerPhone=${body.callerPhone ?? 'none'} direction=${body.direction ?? 'unknown'} leadId=${body.leadId ?? 'none'}`);
|
||||
// Cancel the ACW auto-dispose timer — the frontend submitted disposition
|
||||
this.supervisor.cancelAcwTimer(agentId);
|
||||
|
||||
this.logger.log(`[DISPOSE] ucid=${body.ucid} disposition=${body.disposition} → ozonetel="${ozonetelDisposition}" agentId=${agentId} callerPhone=${body.callerPhone ?? 'none'} direction=${body.direction ?? 'unknown'} leadId=${body.leadId ?? 'none'}`);
|
||||
|
||||
try {
|
||||
const result = await this.ozonetelAgent.setDisposition({
|
||||
agentId: this.defaultAgentId,
|
||||
agentId,
|
||||
ucid: body.ucid,
|
||||
disposition: ozonetelDisposition,
|
||||
});
|
||||
@@ -136,6 +141,37 @@ export class OzonetelAgentController {
|
||||
this.logger.error(`[DISPOSE] FAILED: ${message} ${responseData}`);
|
||||
}
|
||||
|
||||
// Create call record for outbound calls. Inbound calls are
|
||||
// created by the webhook — but we skip outbound in the webhook
|
||||
// (they're not "missed calls"). So the dispose endpoint is the
|
||||
// only place that creates the call record for outbound dials.
|
||||
if (body.direction === 'OUTBOUND' && body.callerPhone) {
|
||||
try {
|
||||
const callData: Record<string, any> = {
|
||||
name: `Outbound — ${body.callerPhone}`,
|
||||
direction: 'OUTBOUND',
|
||||
callStatus: 'COMPLETED',
|
||||
callerNumber: { primaryPhoneNumber: `+91${body.callerPhone.replace(/^\+?91/, '')}` },
|
||||
agentName: agentId,
|
||||
durationSec: body.durationSec ?? 0,
|
||||
disposition: body.disposition,
|
||||
};
|
||||
if (body.leadId) callData.leadId = body.leadId;
|
||||
|
||||
const apiKey = process.env.PLATFORM_API_KEY;
|
||||
if (apiKey) {
|
||||
const result = await this.platform.queryWithAuth<any>(
|
||||
`mutation($data: CallCreateInput!) { createCall(data: $data) { id } }`,
|
||||
{ data: callData },
|
||||
`Bearer ${apiKey}`,
|
||||
);
|
||||
this.logger.log(`[DISPOSE] Created outbound call record: ${result.createCall.id}`);
|
||||
}
|
||||
} catch (err: any) {
|
||||
this.logger.warn(`[DISPOSE] Failed to create outbound call record: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Handle missed call callback status update
|
||||
if (body.missedCallId) {
|
||||
const statusMap: Record<string, string> = {
|
||||
@@ -149,7 +185,7 @@ export class OzonetelAgentController {
|
||||
if (newStatus) {
|
||||
try {
|
||||
await this.platform.query<any>(
|
||||
`mutation { updateCall(id: "${body.missedCallId}", data: { callbackstatus: ${newStatus} }) { id } }`,
|
||||
`mutation { updateCall(id: "${body.missedCallId}", data: { callbackStatus: ${newStatus} }) { id } }`,
|
||||
);
|
||||
} catch (err) {
|
||||
this.logger.warn(`Failed to update missed call status: ${err}`);
|
||||
@@ -159,7 +195,7 @@ export class OzonetelAgentController {
|
||||
|
||||
// Auto-assign next missed call to this agent
|
||||
try {
|
||||
await this.missedQueue.assignNext(this.defaultAgentId);
|
||||
await this.missedQueue.assignNext(agentId);
|
||||
} catch (err) {
|
||||
this.logger.warn(`Auto-assignment after dispose failed: ${err}`);
|
||||
}
|
||||
@@ -168,7 +204,7 @@ export class OzonetelAgentController {
|
||||
this.eventBus.emit(Topics.CALL_COMPLETED, {
|
||||
callId: null,
|
||||
ucid: body.ucid,
|
||||
agentId: this.defaultAgentId,
|
||||
agentId,
|
||||
callerPhone: body.callerPhone ?? '',
|
||||
direction: body.direction ?? 'INBOUND',
|
||||
durationSec: body.durationSec ?? 0,
|
||||
@@ -183,19 +219,27 @@ export class OzonetelAgentController {
|
||||
|
||||
@Post('dial')
|
||||
async dial(
|
||||
@Body() body: { phoneNumber: string; campaignName?: string; leadId?: string },
|
||||
@Body() body: { phoneNumber: string; agentId: string; campaignName?: string; leadId?: string },
|
||||
) {
|
||||
if (!body.phoneNumber) {
|
||||
throw new HttpException('phoneNumber required', 400);
|
||||
}
|
||||
|
||||
const campaignName = body.campaignName ?? process.env.OZONETEL_CAMPAIGN_NAME ?? 'Inbound_918041763265';
|
||||
const agentId = this.requireAgentId(body.agentId);
|
||||
const did = this.telephony.getConfig().ozonetel.did;
|
||||
const campaignName = body.campaignName
|
||||
|| this.telephony.getConfig().ozonetel.campaignName
|
||||
|| (did ? `Inbound_${did}` : '');
|
||||
|
||||
this.logger.log(`[DIAL] phone=${body.phoneNumber} campaign=${campaignName} agentId=${this.defaultAgentId} lead=${body.leadId ?? 'none'}`);
|
||||
if (!campaignName) {
|
||||
throw new HttpException('Campaign name not configured — set in Telephony settings or pass campaignName', 400);
|
||||
}
|
||||
|
||||
this.logger.log(`[DIAL] phone=${body.phoneNumber} campaign=${campaignName} agentId=${agentId} lead=${body.leadId ?? 'none'}`);
|
||||
|
||||
try {
|
||||
const result = await this.ozonetelAgent.manualDial({
|
||||
agentId: this.defaultAgentId,
|
||||
agentId,
|
||||
campaignName,
|
||||
customerNumber: body.phoneNumber,
|
||||
});
|
||||
@@ -273,23 +317,27 @@ export class OzonetelAgentController {
|
||||
}
|
||||
|
||||
@Get('performance')
|
||||
async performance(@Query('date') date?: string) {
|
||||
async performance(@Query('date') date?: string, @Query('agentId') agentId?: string) {
|
||||
const agent = this.requireAgentId(agentId);
|
||||
const targetDate = date ?? new Date().toISOString().split('T')[0];
|
||||
this.logger.log(`Performance: date=${targetDate} agent=${this.defaultAgentId}`);
|
||||
this.logger.log(`Performance: date=${targetDate} agent=${agent}`);
|
||||
|
||||
const [cdr, summary, aht] = await Promise.all([
|
||||
this.ozonetelAgent.fetchCDR({ date: targetDate }),
|
||||
this.ozonetelAgent.getAgentSummary(this.defaultAgentId, targetDate),
|
||||
this.ozonetelAgent.getAHT(this.defaultAgentId),
|
||||
this.ozonetelAgent.getAgentSummary(agent, targetDate),
|
||||
this.ozonetelAgent.getAHT(agent),
|
||||
]);
|
||||
|
||||
const totalCalls = cdr.length;
|
||||
const inbound = cdr.filter((c: any) => c.Type === 'InBound').length;
|
||||
const outbound = cdr.filter((c: any) => c.Type === 'Manual' || c.Type === 'Progressive').length;
|
||||
const answered = cdr.filter((c: any) => c.Status === 'Answered').length;
|
||||
const missed = cdr.filter((c: any) => c.Status === 'Unanswered' || c.Status === 'NotAnswered').length;
|
||||
// Filter CDR to this agent only — fetchCDR returns all agents' calls
|
||||
const agentCdr = cdr.filter((c: any) => c.AgentID === agent || c.AgentName === agent);
|
||||
|
||||
const talkTimes = cdr
|
||||
const totalCalls = agentCdr.length;
|
||||
const inbound = agentCdr.filter((c: any) => c.Type === 'InBound').length;
|
||||
const outbound = agentCdr.filter((c: any) => c.Type === 'Manual' || c.Type === 'Progressive').length;
|
||||
const answered = agentCdr.filter((c: any) => c.Status === 'Answered').length;
|
||||
const missed = agentCdr.filter((c: any) => c.Status === 'NotAnswered').length;
|
||||
|
||||
const talkTimes = agentCdr
|
||||
.filter((c: any) => c.TalkTime && c.TalkTime !== '00:00:00')
|
||||
.map((c: any) => {
|
||||
const parts = c.TalkTime.split(':').map(Number);
|
||||
@@ -300,12 +348,12 @@ export class OzonetelAgentController {
|
||||
: 0;
|
||||
|
||||
const dispositions: Record<string, number> = {};
|
||||
for (const c of cdr) {
|
||||
for (const c of agentCdr) {
|
||||
const d = (c as any).Disposition || 'No Disposition';
|
||||
dispositions[d] = (dispositions[d] ?? 0) + 1;
|
||||
}
|
||||
|
||||
const appointmentsBooked = cdr.filter((c: any) =>
|
||||
const appointmentsBooked = agentCdr.filter((c: any) =>
|
||||
c.Disposition?.toLowerCase().includes('appointment'),
|
||||
).length;
|
||||
|
||||
|
||||
@@ -4,9 +4,10 @@ import { OzonetelAgentService } from './ozonetel-agent.service';
|
||||
import { KookooIvrController } from './kookoo-ivr.controller';
|
||||
import { WorklistModule } from '../worklist/worklist.module';
|
||||
import { PlatformModule } from '../platform/platform.module';
|
||||
import { SupervisorModule } from '../supervisor/supervisor.module';
|
||||
|
||||
@Module({
|
||||
imports: [PlatformModule, forwardRef(() => WorklistModule)],
|
||||
imports: [PlatformModule, forwardRef(() => WorklistModule), forwardRef(() => SupervisorModule)],
|
||||
controllers: [OzonetelAgentController, KookooIvrController],
|
||||
providers: [OzonetelAgentService],
|
||||
exports: [OzonetelAgentService],
|
||||
|
||||
269
src/ozonetel/ozonetel-agent.service.spec.ts
Normal file
269
src/ozonetel/ozonetel-agent.service.spec.ts
Normal file
@@ -0,0 +1,269 @@
|
||||
/**
|
||||
* Ozonetel Agent Service — unit tests
|
||||
*
|
||||
* QA coverage: agent auth (login/logout), manual dial, set disposition,
|
||||
* change agent state, call control. Covers the Ozonetel HTTP layer that
|
||||
* backs TC-IB-01→06, TC-OB-01→06, TC-FU-01→02 via disposition flows.
|
||||
*
|
||||
* axios is mocked — no real HTTP to Ozonetel.
|
||||
*/
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { OzonetelAgentService } from './ozonetel-agent.service';
|
||||
import { TelephonyConfigService } from '../config/telephony-config.service';
|
||||
import axios from 'axios';
|
||||
import {
|
||||
AGENT_AUTH_LOGIN_SUCCESS,
|
||||
AGENT_AUTH_LOGIN_ALREADY,
|
||||
AGENT_AUTH_LOGOUT_SUCCESS,
|
||||
AGENT_AUTH_INVALID,
|
||||
DISPOSITION_SET_DURING_CALL,
|
||||
DISPOSITION_SET_AFTER_CALL,
|
||||
DISPOSITION_INVALID_UCID,
|
||||
} from '../__fixtures__/ozonetel-payloads';
|
||||
|
||||
jest.mock('axios');
|
||||
const mockedAxios = axios as jest.Mocked<typeof axios>;
|
||||
|
||||
describe('OzonetelAgentService', () => {
|
||||
let service: OzonetelAgentService;
|
||||
|
||||
const mockTelephonyConfig = {
|
||||
exotel: {
|
||||
apiKey: 'KK_TEST_KEY',
|
||||
accountSid: 'test_account',
|
||||
subdomain: 'in1-ccaas-api.ozonetel.com',
|
||||
},
|
||||
ozonetel: {
|
||||
agentId: 'global',
|
||||
agentPassword: 'Test123$',
|
||||
sipId: '523590',
|
||||
campaignName: 'Inbound_918041763400',
|
||||
did: '918041763400',
|
||||
},
|
||||
sip: { domain: 'blr-pub-rtc4.ozonetel.com', wsPort: '444' },
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
jest.clearAllMocks();
|
||||
|
||||
// Mock token generation (needed before most API calls)
|
||||
mockedAxios.post.mockImplementation(async (url: string, data?: any) => {
|
||||
if (url.includes('generateToken')) {
|
||||
return { data: { token: 'mock-bearer-token', status: 'success' } };
|
||||
}
|
||||
return { data: {} };
|
||||
});
|
||||
|
||||
const module = await Test.createTestingModule({
|
||||
providers: [
|
||||
OzonetelAgentService,
|
||||
{
|
||||
provide: TelephonyConfigService,
|
||||
useValue: { getConfig: () => mockTelephonyConfig },
|
||||
},
|
||||
],
|
||||
}).compile();
|
||||
|
||||
service = module.get(OzonetelAgentService);
|
||||
});
|
||||
|
||||
// ── Agent Login ──────────────────────────────────────────────
|
||||
|
||||
describe('loginAgent', () => {
|
||||
it('should send correct params to Ozonetel auth endpoint', async () => {
|
||||
mockedAxios.post.mockResolvedValueOnce({ data: AGENT_AUTH_LOGIN_SUCCESS });
|
||||
|
||||
const result = await service.loginAgent({
|
||||
agentId: 'global',
|
||||
password: 'Test123$',
|
||||
phoneNumber: '523590',
|
||||
mode: 'blended',
|
||||
});
|
||||
|
||||
expect(result).toEqual(AGENT_AUTH_LOGIN_SUCCESS);
|
||||
|
||||
const authCall = mockedAxios.post.mock.calls[0];
|
||||
expect(authCall[0]).toContain('AgentAuthenticationV2');
|
||||
// Body is URLSearchParams string
|
||||
expect(authCall[1]).toContain('userName=test_account');
|
||||
expect(authCall[1]).toContain('apiKey=KK_TEST_KEY');
|
||||
expect(authCall[1]).toContain('phoneNumber=523590');
|
||||
expect(authCall[1]).toContain('action=login');
|
||||
expect(authCall[1]).toContain('mode=blended');
|
||||
// Basic auth
|
||||
expect(authCall[2]?.auth).toEqual({ username: 'global', password: 'Test123$' });
|
||||
});
|
||||
|
||||
it('should auto-retry on "already logged in" response', async () => {
|
||||
// First call: already logged in
|
||||
mockedAxios.post
|
||||
.mockResolvedValueOnce({ data: AGENT_AUTH_LOGIN_ALREADY })
|
||||
// Logout call
|
||||
.mockResolvedValueOnce({ data: AGENT_AUTH_LOGOUT_SUCCESS })
|
||||
// Re-login call
|
||||
.mockResolvedValueOnce({ data: AGENT_AUTH_LOGIN_SUCCESS });
|
||||
|
||||
const result = await service.loginAgent({
|
||||
agentId: 'global',
|
||||
password: 'Test123$',
|
||||
phoneNumber: '523590',
|
||||
});
|
||||
|
||||
// Should have made 3 calls: login, logout, re-login
|
||||
expect(mockedAxios.post).toHaveBeenCalledTimes(3);
|
||||
expect(result).toEqual(AGENT_AUTH_LOGIN_SUCCESS);
|
||||
});
|
||||
|
||||
it('should throw on invalid authentication', async () => {
|
||||
mockedAxios.post.mockRejectedValueOnce({
|
||||
response: { status: 401, data: AGENT_AUTH_INVALID },
|
||||
});
|
||||
|
||||
await expect(
|
||||
service.loginAgent({ agentId: 'bad', password: 'wrong', phoneNumber: '000' }),
|
||||
).rejects.toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
// ── Agent Logout ─────────────────────────────────────────────
|
||||
|
||||
describe('logoutAgent', () => {
|
||||
it('should send logout action', async () => {
|
||||
mockedAxios.post.mockResolvedValueOnce({ data: AGENT_AUTH_LOGOUT_SUCCESS });
|
||||
|
||||
const result = await service.logoutAgent({ agentId: 'global', password: 'Test123$' });
|
||||
|
||||
expect(result).toEqual(AGENT_AUTH_LOGOUT_SUCCESS);
|
||||
const call = mockedAxios.post.mock.calls[0];
|
||||
expect(call[1]).toContain('action=logout');
|
||||
});
|
||||
});
|
||||
|
||||
// ── Manual Dial ──────────────────────────────────────────────
|
||||
|
||||
describe('manualDial', () => {
|
||||
it('should send correct params with bearer token', async () => {
|
||||
// First call: token generation, second: manual dial
|
||||
mockedAxios.post
|
||||
.mockResolvedValueOnce({ data: { token: 'mock-token', status: 'success' } })
|
||||
.mockResolvedValueOnce({
|
||||
data: { status: 'success', ucid: '31712345678901234', message: 'Call initiated' },
|
||||
});
|
||||
|
||||
const result = await service.manualDial({
|
||||
agentId: 'global',
|
||||
campaignName: 'Inbound_918041763400',
|
||||
customerNumber: '9949879837',
|
||||
});
|
||||
|
||||
expect(result).toEqual(expect.objectContaining({ status: 'success' }));
|
||||
|
||||
// The dial call (second post)
|
||||
const dialCall = mockedAxios.post.mock.calls[1];
|
||||
expect(dialCall[0]).toContain('AgentManualDial');
|
||||
expect(dialCall[1]).toMatchObject({
|
||||
userName: 'test_account',
|
||||
agentID: 'global',
|
||||
campaignName: 'Inbound_918041763400',
|
||||
customerNumber: '9949879837',
|
||||
});
|
||||
expect(dialCall[2]?.headers?.Authorization).toBe('Bearer mock-token');
|
||||
});
|
||||
});
|
||||
|
||||
// ── Set Disposition ──────────────────────────────────────────
|
||||
|
||||
describe('setDisposition', () => {
|
||||
it('should send disposition with correct fields', async () => {
|
||||
mockedAxios.post
|
||||
.mockResolvedValueOnce({ data: { token: 'mock-token', status: 'success' } })
|
||||
.mockResolvedValueOnce({ data: DISPOSITION_SET_AFTER_CALL });
|
||||
|
||||
const result = await service.setDisposition({
|
||||
agentId: 'global',
|
||||
ucid: '31712345678901234',
|
||||
disposition: 'General Enquiry',
|
||||
});
|
||||
|
||||
expect(result).toEqual(DISPOSITION_SET_AFTER_CALL);
|
||||
|
||||
const dispCall = mockedAxios.post.mock.calls[1];
|
||||
expect(dispCall[0]).toContain('DispositionAPIV2');
|
||||
expect(dispCall[1]).toMatchObject({
|
||||
userName: 'test_account',
|
||||
agentID: 'global',
|
||||
ucid: '31712345678901234',
|
||||
action: 'Set',
|
||||
disposition: 'General Enquiry',
|
||||
did: '918041763400',
|
||||
autoRelease: 'true',
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle queued disposition (during call)', async () => {
|
||||
mockedAxios.post
|
||||
.mockResolvedValueOnce({ data: { token: 'mock-token', status: 'success' } })
|
||||
.mockResolvedValueOnce({ data: DISPOSITION_SET_DURING_CALL });
|
||||
|
||||
const result = await service.setDisposition({
|
||||
agentId: 'global',
|
||||
ucid: '31712345678901234',
|
||||
disposition: 'Appointment Booked',
|
||||
});
|
||||
|
||||
expect(result.status).toBe('Success');
|
||||
expect(result.message).toContain('Queued');
|
||||
});
|
||||
});
|
||||
|
||||
// ── Change Agent State ───────────────────────────────────────
|
||||
|
||||
describe('changeAgentState', () => {
|
||||
it('should send Ready state', async () => {
|
||||
mockedAxios.post
|
||||
.mockResolvedValueOnce({ data: { token: 'mock-token', status: 'success' } })
|
||||
.mockResolvedValueOnce({ data: { status: 'success', message: 'State changed' } });
|
||||
|
||||
await service.changeAgentState({ agentId: 'global', state: 'Ready' });
|
||||
|
||||
const stateCall = mockedAxios.post.mock.calls[1];
|
||||
expect(stateCall[0]).toContain('changeAgentState');
|
||||
expect(stateCall[1]).toMatchObject({
|
||||
userName: 'test_account',
|
||||
agentId: 'global',
|
||||
state: 'Ready',
|
||||
});
|
||||
});
|
||||
|
||||
it('should include pauseReason when pausing', async () => {
|
||||
mockedAxios.post
|
||||
.mockResolvedValueOnce({ data: { token: 'mock-token', status: 'success' } })
|
||||
.mockResolvedValueOnce({ data: { status: 'success', message: 'Agent paused' } });
|
||||
|
||||
await service.changeAgentState({ agentId: 'global', state: 'Pause', pauseReason: 'Break' });
|
||||
|
||||
const stateCall = mockedAxios.post.mock.calls[1];
|
||||
expect(stateCall[1]).toMatchObject({ pauseReason: 'Break' });
|
||||
});
|
||||
});
|
||||
|
||||
// ── Token caching ────────────────────────────────────────────
|
||||
|
||||
describe('token management', () => {
|
||||
it('should cache token and reuse for subsequent calls', async () => {
|
||||
// First call generates token
|
||||
mockedAxios.post
|
||||
.mockResolvedValueOnce({ data: { token: 'cached-token', status: 'success' } })
|
||||
.mockResolvedValueOnce({ data: { status: 'success' } })
|
||||
// Second API call should reuse token
|
||||
.mockResolvedValueOnce({ data: { status: 'success' } });
|
||||
|
||||
await service.manualDial({ agentId: 'a', campaignName: 'c', customerNumber: '1' });
|
||||
await service.manualDial({ agentId: 'a', campaignName: 'c', customerNumber: '2' });
|
||||
|
||||
// Token generation should only be called once
|
||||
const tokenCalls = mockedAxios.post.mock.calls.filter(c => c[0].includes('generateToken'));
|
||||
expect(tokenCalls.length).toBe(1);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,20 +1,27 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import axios from 'axios';
|
||||
import { TelephonyConfigService } from '../config/telephony-config.service';
|
||||
|
||||
@Injectable()
|
||||
export class OzonetelAgentService {
|
||||
private readonly logger = new Logger(OzonetelAgentService.name);
|
||||
private readonly apiDomain: string;
|
||||
private readonly apiKey: string;
|
||||
private readonly accountId: string;
|
||||
private cachedToken: string | null = null;
|
||||
private tokenExpiry: number = 0;
|
||||
|
||||
constructor(private config: ConfigService) {
|
||||
this.apiDomain = config.get<string>('exotel.subdomain') ?? 'in1-ccaas-api.ozonetel.com';
|
||||
this.apiKey = config.get<string>('exotel.apiKey') ?? '';
|
||||
this.accountId = config.get<string>('exotel.accountSid') ?? '';
|
||||
constructor(private telephony: TelephonyConfigService) {}
|
||||
|
||||
// Read-through getters so admin updates to telephony.json take effect
|
||||
// immediately without a sidecar restart. The default for apiDomain is
|
||||
// preserved here because the legacy env-var path used a different default
|
||||
// ('in1-ccaas-api.ozonetel.com') than the rest of the Exotel config.
|
||||
private get apiDomain(): string {
|
||||
return this.telephony.getConfig().exotel.subdomain || 'in1-ccaas-api.ozonetel.com';
|
||||
}
|
||||
private get apiKey(): string {
|
||||
return this.telephony.getConfig().exotel.apiKey;
|
||||
}
|
||||
private get accountId(): string {
|
||||
return this.telephony.getConfig().exotel.accountSid;
|
||||
}
|
||||
|
||||
private async getToken(): Promise<string> {
|
||||
@@ -196,7 +203,7 @@ export class OzonetelAgentService {
|
||||
disposition: string;
|
||||
}): Promise<{ status: string; message?: string; details?: string }> {
|
||||
const url = `https://${this.apiDomain}/ca_apis/DispositionAPIV2`;
|
||||
const did = process.env.OZONETEL_DID ?? '918041763265';
|
||||
const did = this.telephony.getConfig().ozonetel.did;
|
||||
|
||||
this.logger.log(`Set disposition: agent=${params.agentId} ucid=${params.ucid} disposition=${params.disposition}`);
|
||||
|
||||
@@ -232,8 +239,9 @@ export class OzonetelAgentService {
|
||||
conferenceNumber?: string;
|
||||
}): Promise<{ status: string; message: string; ucid?: string }> {
|
||||
const url = `https://${this.apiDomain}/ca_apis/CallControl_V4`;
|
||||
const did = process.env.OZONETEL_DID ?? '918041763265';
|
||||
const agentPhoneName = process.env.OZONETEL_SIP_ID ?? '523590';
|
||||
const tcfg = this.telephony.getConfig().ozonetel;
|
||||
const did = tcfg.did;
|
||||
const agentPhoneName = tcfg.sipId;
|
||||
|
||||
this.logger.log(`Call control: action=${params.action} ucid=${params.ucid} conference=${params.conferenceNumber ?? 'none'}`);
|
||||
|
||||
|
||||
@@ -180,10 +180,16 @@ export class PlatformGraphqlService {
|
||||
}
|
||||
|
||||
async updateLeadWithToken(id: string, input: UpdateLeadInput, authHeader: string): Promise<LeadNode> {
|
||||
// Response fragment deliberately excludes `leadStatus` — the staging
|
||||
// platform schema has this field renamed to `status`. Selecting the
|
||||
// old name rejects the whole mutation. Callers don't use the
|
||||
// returned fragment today, so returning just the id + AI fields
|
||||
// keeps this working across both schema shapes without a wider
|
||||
// rename hotfix.
|
||||
const data = await this.queryWithAuth<{ updateLead: LeadNode }>(
|
||||
`mutation UpdateLead($id: ID!, $data: LeadUpdateInput!) {
|
||||
updateLead(id: $id, data: $data) {
|
||||
id leadStatus aiSummary aiSuggestedAction
|
||||
id aiSummary aiSuggestedAction
|
||||
}
|
||||
}`,
|
||||
{ id, data: input },
|
||||
@@ -192,6 +198,67 @@ export class PlatformGraphqlService {
|
||||
return data.updateLead;
|
||||
}
|
||||
|
||||
// Fetch a single lead by id with the caller's JWT. Used by the
|
||||
// lead-enrich flow when the agent explicitly renames a caller from
|
||||
// the appointment/enquiry form and we need to regenerate the lead's
|
||||
// AI summary against fresh identity.
|
||||
//
|
||||
// The selected fields deliberately use the staging-aligned names
|
||||
// (`status`, `source`, `lastContacted`) rather than the older
|
||||
// `leadStatus`/`leadSource`/`lastContactedAt` names — otherwise the
|
||||
// query would be rejected on staging.
|
||||
async findLeadByIdWithToken(id: string, authHeader: string): Promise<any | null> {
|
||||
try {
|
||||
const data = await this.queryWithAuth<{ lead: any }>(
|
||||
`query FindLead($id: UUID!) {
|
||||
lead(filter: { id: { eq: $id } }) {
|
||||
id
|
||||
createdAt
|
||||
contactName { firstName lastName }
|
||||
contactPhone { primaryPhoneNumber primaryPhoneCallingCode }
|
||||
source
|
||||
status
|
||||
interestedService
|
||||
contactAttempts
|
||||
lastContacted
|
||||
aiSummary
|
||||
aiSuggestedAction
|
||||
}
|
||||
}`,
|
||||
{ id },
|
||||
authHeader,
|
||||
);
|
||||
return data.lead ?? null;
|
||||
} catch {
|
||||
// Fall back to edge-style query in case the singular field
|
||||
// doesn't exist on this platform version.
|
||||
const data = await this.queryWithAuth<{ leads: { edges: { node: any }[] } }>(
|
||||
`query FindLead($id: UUID!) {
|
||||
leads(filter: { id: { eq: $id } }, first: 1) {
|
||||
edges {
|
||||
node {
|
||||
id
|
||||
createdAt
|
||||
contactName { firstName lastName }
|
||||
contactPhone { primaryPhoneNumber primaryPhoneCallingCode }
|
||||
source
|
||||
status
|
||||
interestedService
|
||||
contactAttempts
|
||||
lastContacted
|
||||
aiSummary
|
||||
aiSuggestedAction
|
||||
}
|
||||
}
|
||||
}
|
||||
}`,
|
||||
{ id },
|
||||
authHeader,
|
||||
);
|
||||
return data.leads.edges[0]?.node ?? null;
|
||||
}
|
||||
}
|
||||
|
||||
// --- Server-to-server versions (for webhooks, background jobs) ---
|
||||
|
||||
async getLeadActivities(leadId: string, limit = 3): Promise<LeadActivityNode[]> {
|
||||
|
||||
@@ -4,6 +4,7 @@ import { generateObject } from 'ai';
|
||||
import { z } from 'zod';
|
||||
import { createAiModel } from '../ai/ai-provider';
|
||||
import type { LanguageModel } from 'ai';
|
||||
import { AiConfigService } from '../config/ai-config.service';
|
||||
|
||||
const DEEPGRAM_API = 'https://api.deepgram.com/v1/listen';
|
||||
|
||||
@@ -44,9 +45,18 @@ export class RecordingsService {
|
||||
private readonly deepgramApiKey: string;
|
||||
private readonly aiModel: LanguageModel | null;
|
||||
|
||||
constructor(private config: ConfigService) {
|
||||
constructor(
|
||||
private config: ConfigService,
|
||||
private aiConfig: AiConfigService,
|
||||
) {
|
||||
this.deepgramApiKey = process.env.DEEPGRAM_API_KEY ?? '';
|
||||
this.aiModel = createAiModel(config);
|
||||
const cfg = aiConfig.getConfig();
|
||||
this.aiModel = createAiModel({
|
||||
provider: cfg.provider,
|
||||
model: cfg.model,
|
||||
anthropicApiKey: config.get<string>('ai.anthropicApiKey'),
|
||||
openaiApiKey: config.get<string>('ai.openaiApiKey'),
|
||||
});
|
||||
}
|
||||
|
||||
async analyzeRecording(recordingUrl: string): Promise<CallAnalysis> {
|
||||
@@ -225,11 +235,11 @@ The CUSTOMER typically:
|
||||
patientSatisfaction: z.string().describe('One-line assessment of patient satisfaction'),
|
||||
callOutcome: z.string().describe('One-line summary of what was accomplished'),
|
||||
}),
|
||||
system: `You are a call quality analyst for Global Hospital Bangalore.
|
||||
Analyze the following call recording transcript and provide structured insights.
|
||||
Be specific, brief, and actionable. Focus on healthcare context.
|
||||
${summary ? `\nCall summary: ${summary}` : ''}
|
||||
${topics.length > 0 ? `\nDetected topics: ${topics.join(', ')}` : ''}`,
|
||||
system: this.aiConfig.renderPrompt('recordingAnalysis', {
|
||||
hospitalName: process.env.HOSPITAL_NAME ?? 'the hospital',
|
||||
summaryBlock: summary ? `\nCall summary: ${summary}` : '',
|
||||
topicsBlock: topics.length > 0 ? `\nDetected topics: ${topics.join(', ')}` : '',
|
||||
}),
|
||||
prompt: transcript,
|
||||
maxOutputTokens: 500,
|
||||
});
|
||||
|
||||
@@ -18,10 +18,10 @@ export class CallFactsProvider implements FactProvider {
|
||||
'call.status': call.callStatus ?? null,
|
||||
'call.disposition': call.disposition ?? null,
|
||||
'call.durationSeconds': call.durationSeconds ?? call.durationSec ?? 0,
|
||||
'call.callbackStatus': call.callbackstatus ?? call.callbackStatus ?? null,
|
||||
'call.callbackStatus': call.callbackStatus ?? call.callbackStatus ?? null,
|
||||
'call.slaElapsedPercent': slaElapsedPercent,
|
||||
'call.slaBreached': slaElapsedPercent > 100,
|
||||
'call.missedCount': call.missedcallcount ?? call.missedCount ?? 0,
|
||||
'call.missedCount': call.missedCallCount ?? call.missedCount ?? 0,
|
||||
'call.taskType': taskType,
|
||||
};
|
||||
}
|
||||
|
||||
151
src/shared/doctor-utils.ts
Normal file
151
src/shared/doctor-utils.ts
Normal file
@@ -0,0 +1,151 @@
|
||||
// Shared utilities for working with the helix-engage Doctor entity
|
||||
// after the multi-clinic visit-slot rework. The doctor data model
|
||||
// changed from { clinic: RELATION, visitingHours: TEXT } to many
|
||||
// DoctorVisitSlot records (one per day-of-week × clinic), so every
|
||||
// service that fetches doctors needs to:
|
||||
//
|
||||
// 1. Query `visitSlots { dayOfWeek startTime endTime clinic { id clinicName } }`
|
||||
// instead of the legacy flat fields.
|
||||
// 2. Fold the slots back into a "where do they visit" summary string
|
||||
// and a list of unique clinics for branch-matching.
|
||||
//
|
||||
// This file provides:
|
||||
//
|
||||
// - DOCTOR_VISIT_SLOTS_FRAGMENT: a string fragment that callers can
|
||||
// splice into their `doctors { edges { node { ... } } }` query so
|
||||
// the field selection stays consistent across services.
|
||||
//
|
||||
// - normalizeDoctor(d): takes the raw GraphQL node and returns the
|
||||
// same object plus three derived fields:
|
||||
// * `clinics: { id, clinicName }[]` — unique list of clinics
|
||||
// the doctor visits, deduped by id.
|
||||
// * `clinic: { clinicName } | null` — first clinic for legacy
|
||||
// consumers that only show one (the AI prompt KB, etc.).
|
||||
// * `visitingHours: string` — pre-formatted summary like
|
||||
// "Mon 09:00-13:00 (Koramangala) · Wed 14:00-18:00 (Indiranagar)"
|
||||
// suitable for inlining into AI prompts.
|
||||
//
|
||||
// Keeping the legacy field names (`clinic`, `visitingHours`) on the
|
||||
// normalized object means call sites that previously read those
|
||||
// fields keep working — only the GraphQL query and the call to
|
||||
// normalizeDoctor need to be added.
|
||||
|
||||
export type RawDoctorVisitSlot = {
|
||||
dayOfWeek?: string | null;
|
||||
startTime?: string | null;
|
||||
endTime?: string | null;
|
||||
clinic?: { id?: string | null; clinicName?: string | null } | null;
|
||||
};
|
||||
|
||||
export type RawDoctor = {
|
||||
id?: string;
|
||||
name?: string | null;
|
||||
fullName?: { firstName?: string | null; lastName?: string | null } | null;
|
||||
department?: string | null;
|
||||
specialty?: string | null;
|
||||
visitSlots?: { edges?: Array<{ node: RawDoctorVisitSlot }> } | null;
|
||||
[key: string]: any;
|
||||
};
|
||||
|
||||
// Tightened shape — `id` and `name` are always strings (with sensible
|
||||
// fallbacks) so consumers can assign them to typed maps without
|
||||
// "string | undefined" errors. The remaining fields keep their
|
||||
// nullable nature from RawDoctor.
|
||||
export type NormalizedDoctor = Omit<RawDoctor, 'id' | 'name'> & {
|
||||
id: string;
|
||||
name: string;
|
||||
clinics: Array<{ id: string; clinicName: string }>;
|
||||
clinic: { clinicName: string } | null;
|
||||
visitingHours: string;
|
||||
};
|
||||
|
||||
// GraphQL fragment for the visit-slots reverse relation. Spliced into
|
||||
// each doctors query so all services fetch the same shape. Capped at
|
||||
// 20 slots per doctor — generous for any realistic schedule (7 days
|
||||
// × 2-3 clinics).
|
||||
export const DOCTOR_VISIT_SLOTS_FRAGMENT = `visitSlots(first: 20) {
|
||||
edges { node {
|
||||
dayOfWeek startTime endTime
|
||||
clinic { id clinicName }
|
||||
} }
|
||||
}`;
|
||||
|
||||
const DAY_ABBREV: Record<string, string> = {
|
||||
MONDAY: 'Mon',
|
||||
TUESDAY: 'Tue',
|
||||
WEDNESDAY: 'Wed',
|
||||
THURSDAY: 'Thu',
|
||||
FRIDAY: 'Fri',
|
||||
SATURDAY: 'Sat',
|
||||
SUNDAY: 'Sun',
|
||||
};
|
||||
|
||||
const formatTime = (t: string | null | undefined): string => {
|
||||
if (!t) return '';
|
||||
// Times come in as "HH:MM" or "HH:MM:SS" — strip seconds for
|
||||
// display compactness.
|
||||
return t.length > 5 ? t.slice(0, 5) : t;
|
||||
};
|
||||
|
||||
// Best-effort doctor name derivation — prefer the platform's `name`
|
||||
// field, then fall back to the composite fullName, then to a generic
|
||||
// label so consumers never see undefined.
|
||||
const deriveName = (raw: RawDoctor): string => {
|
||||
if (raw.name && raw.name.trim()) return raw.name.trim();
|
||||
const first = raw.fullName?.firstName?.trim() ?? '';
|
||||
const last = raw.fullName?.lastName?.trim() ?? '';
|
||||
const full = `${first} ${last}`.trim();
|
||||
if (full) return full;
|
||||
return 'Unknown doctor';
|
||||
};
|
||||
|
||||
export const normalizeDoctor = (raw: RawDoctor): NormalizedDoctor => {
|
||||
const slots = raw.visitSlots?.edges?.map((e) => e.node) ?? [];
|
||||
|
||||
// Unique clinics, preserving the order they were encountered.
|
||||
const seen = new Set<string>();
|
||||
const clinics: Array<{ id: string; clinicName: string }> = [];
|
||||
for (const slot of slots) {
|
||||
const id = slot.clinic?.id;
|
||||
const name = slot.clinic?.clinicName;
|
||||
if (!id || !name || seen.has(id)) continue;
|
||||
seen.add(id);
|
||||
clinics.push({ id, clinicName: name });
|
||||
}
|
||||
|
||||
// Visiting hours summary — `Day HH:MM-HH:MM (Clinic)` joined by
|
||||
// " · ". Slots without a clinic or without a day get dropped.
|
||||
const segments: string[] = [];
|
||||
for (const slot of slots) {
|
||||
const day = slot.dayOfWeek ? (DAY_ABBREV[slot.dayOfWeek] ?? slot.dayOfWeek) : null;
|
||||
const start = formatTime(slot.startTime);
|
||||
const end = formatTime(slot.endTime);
|
||||
const clinic = slot.clinic?.clinicName;
|
||||
if (!day || !start || !clinic) continue;
|
||||
segments.push(`${day} ${start}${end ? `-${end}` : ''} (${clinic})`);
|
||||
}
|
||||
|
||||
return {
|
||||
...raw,
|
||||
id: raw.id ?? '',
|
||||
name: deriveName(raw),
|
||||
clinics,
|
||||
// Bridge field — first clinic, so legacy consumers that read
|
||||
// `d.clinic.clinicName` keep working.
|
||||
clinic: clinics.length > 0 ? { clinicName: clinics[0].clinicName } : null,
|
||||
visitingHours: segments.join(' · '),
|
||||
};
|
||||
};
|
||||
|
||||
// Convenience: normalize an array of raw GraphQL nodes in one call.
|
||||
export const normalizeDoctors = (raws: RawDoctor[]): NormalizedDoctor[] => raws.map(normalizeDoctor);
|
||||
|
||||
// Branch-matching helper: a doctor "matches" a branch if any of their
|
||||
// visit slots is at a clinic whose name contains the branch substring
|
||||
// (case-insensitive). Used by widget chat tools to filter doctors by
|
||||
// the visitor's selected branch.
|
||||
export const doctorMatchesBranch = (d: NormalizedDoctor, branch: string | undefined | null): boolean => {
|
||||
if (!branch) return true;
|
||||
const needle = branch.toLowerCase();
|
||||
return d.clinics.some((c) => c.clinicName.toLowerCase().includes(needle));
|
||||
};
|
||||
@@ -1,11 +1,11 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { Module, forwardRef } from '@nestjs/common';
|
||||
import { PlatformModule } from '../platform/platform.module';
|
||||
import { OzonetelAgentModule } from '../ozonetel/ozonetel-agent.module';
|
||||
import { SupervisorController } from './supervisor.controller';
|
||||
import { SupervisorService } from './supervisor.service';
|
||||
|
||||
@Module({
|
||||
imports: [PlatformModule, OzonetelAgentModule],
|
||||
imports: [PlatformModule, forwardRef(() => OzonetelAgentModule)],
|
||||
controllers: [SupervisorController],
|
||||
providers: [SupervisorService],
|
||||
exports: [SupervisorService],
|
||||
|
||||
@@ -20,11 +20,20 @@ type AgentStateEntry = {
|
||||
timestamp: string;
|
||||
};
|
||||
|
||||
// ACW auto-dispose: if an agent has been in ACW for longer than this
|
||||
// without the frontend calling /api/ozonetel/dispose, the server
|
||||
// auto-disposes with a default disposition + autoRelease. This is the
|
||||
// Layer 3 safety net — covers browser crash, tab close, page refresh
|
||||
// where sendBeacon didn't fire, or any other frontend failure.
|
||||
const ACW_TIMEOUT_MS = 30_000; // 30 seconds
|
||||
const ACW_DEFAULT_DISPOSITION = 'General Enquiry';
|
||||
|
||||
@Injectable()
|
||||
export class SupervisorService implements OnModuleInit {
|
||||
private readonly logger = new Logger(SupervisorService.name);
|
||||
private readonly activeCalls = new Map<string, ActiveCall>();
|
||||
private readonly agentStates = new Map<string, AgentStateEntry>();
|
||||
private readonly acwTimers = new Map<string, NodeJS.Timeout>();
|
||||
readonly agentStateSubject = new Subject<{ agentId: string; state: AgentOzonetelState; timestamp: string }>();
|
||||
|
||||
constructor(
|
||||
@@ -37,6 +46,17 @@ export class SupervisorService implements OnModuleInit {
|
||||
this.logger.log('Supervisor service initialized');
|
||||
}
|
||||
|
||||
// Called by the dispose endpoint to cancel the ACW timer
|
||||
// (agent submitted disposition before the timeout)
|
||||
cancelAcwTimer(agentId: string) {
|
||||
const timer = this.acwTimers.get(agentId);
|
||||
if (timer) {
|
||||
clearTimeout(timer);
|
||||
this.acwTimers.delete(agentId);
|
||||
this.logger.log(`[ACW-TIMER] Cancelled for ${agentId} (disposition received)`);
|
||||
}
|
||||
}
|
||||
|
||||
handleCallEvent(event: any) {
|
||||
const action = event.action;
|
||||
const ucid = event.ucid ?? event.monitorUCID;
|
||||
@@ -48,6 +68,12 @@ export class SupervisorService implements OnModuleInit {
|
||||
if (!ucid) return;
|
||||
|
||||
if (action === 'Answered' || action === 'Calling') {
|
||||
// Don't show calls for offline agents (ghost calls)
|
||||
const agentState = this.agentStates.get(agentId);
|
||||
if (agentState?.state === 'offline') {
|
||||
this.logger.warn(`Ignoring call event for offline agent ${agentId} (${ucid})`);
|
||||
return;
|
||||
}
|
||||
this.activeCalls.set(ucid, {
|
||||
ucid, agentId, callerNumber,
|
||||
callType, startTime: eventTime, status: 'active',
|
||||
@@ -71,6 +97,46 @@ export class SupervisorService implements OnModuleInit {
|
||||
this.agentStates.set(agentId, { state: mapped, timestamp: eventTime });
|
||||
this.agentStateSubject.next({ agentId, state: mapped, timestamp: eventTime });
|
||||
this.logger.log(`[AGENT-STATE] Emitted: ${agentId} → ${mapped}`);
|
||||
|
||||
// Layer 3: ACW auto-dispose safety net
|
||||
if (mapped === 'acw') {
|
||||
// Find the most recent UCID for this agent
|
||||
const lastCall = Array.from(this.activeCalls.values())
|
||||
.filter(c => c.agentId === agentId)
|
||||
.pop();
|
||||
const ucid = lastCall?.ucid;
|
||||
|
||||
this.cancelAcwTimer(agentId); // clear any existing timer
|
||||
const timer = setTimeout(async () => {
|
||||
// Check if agent is STILL in ACW (they might have disposed by now)
|
||||
const current = this.agentStates.get(agentId);
|
||||
if (current?.state !== 'acw') {
|
||||
this.logger.log(`[ACW-TIMER] ${agentId} no longer in ACW — skipping auto-dispose`);
|
||||
return;
|
||||
}
|
||||
this.logger.warn(`[ACW-TIMER] ${agentId} stuck in ACW for ${ACW_TIMEOUT_MS / 1000}s — auto-disposing${ucid ? ` (UCID ${ucid})` : ''}`);
|
||||
try {
|
||||
if (ucid) {
|
||||
await this.ozonetel.setDisposition({ agentId, ucid, disposition: ACW_DEFAULT_DISPOSITION });
|
||||
} else {
|
||||
await this.ozonetel.changeAgentState({ agentId, state: 'Ready' });
|
||||
}
|
||||
this.logger.log(`[ACW-TIMER] Auto-dispose successful for ${agentId}`);
|
||||
} catch (err: any) {
|
||||
this.logger.error(`[ACW-TIMER] Auto-dispose failed for ${agentId}: ${err.message}`);
|
||||
// Last resort: try force-ready
|
||||
try {
|
||||
await this.ozonetel.changeAgentState({ agentId, state: 'Ready' });
|
||||
} catch {}
|
||||
}
|
||||
this.acwTimers.delete(agentId);
|
||||
}, ACW_TIMEOUT_MS);
|
||||
this.acwTimers.set(agentId, timer);
|
||||
this.logger.log(`[ACW-TIMER] Started ${ACW_TIMEOUT_MS / 1000}s timer for ${agentId}`);
|
||||
} else if (mapped === 'ready' || mapped === 'offline') {
|
||||
// Agent left ACW normally — cancel the timer
|
||||
this.cancelAcwTimer(agentId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -108,29 +174,64 @@ export class SupervisorService implements OnModuleInit {
|
||||
}
|
||||
|
||||
async getTeamPerformance(date: string): Promise<any> {
|
||||
// Get all agents from platform
|
||||
// Get all agents from platform. Field names are label-derived
|
||||
// camelCase on the current platform schema — see
|
||||
// agent-config.service.ts for the canonical explanation of the
|
||||
// legacy lowercase names that used to exist on staging.
|
||||
const agentData = await this.platform.query<any>(
|
||||
`{ agents(first: 20) { edges { node {
|
||||
id name ozonetelagentid npsscore
|
||||
maxidleminutes minnpsthreshold minconversionpercent
|
||||
id name ozonetelAgentId npsScore
|
||||
maxIdleMinutes minNpsThreshold minConversion
|
||||
} } } }`,
|
||||
);
|
||||
const agents = agentData?.agents?.edges?.map((e: any) => e.node) ?? [];
|
||||
|
||||
// Fetch Ozonetel time summary per agent
|
||||
// Fetch CDR for the entire account for this date (one call, not per-agent)
|
||||
let allCdr: any[] = [];
|
||||
try {
|
||||
allCdr = await this.ozonetel.fetchCDR({ date });
|
||||
} catch (err) {
|
||||
this.logger.warn(`Failed to fetch CDR for ${date}: ${err}`);
|
||||
}
|
||||
|
||||
// Fetch Ozonetel time summary per agent + compute call metrics from CDR
|
||||
const summaries = await Promise.all(
|
||||
agents.map(async (agent: any) => {
|
||||
if (!agent.ozonetelagentid) return { ...agent, timeBreakdown: null };
|
||||
if (!agent.ozonetelAgentId) return { ...agent, timeBreakdown: null, calls: null };
|
||||
try {
|
||||
const summary = await this.ozonetel.getAgentSummary(agent.ozonetelagentid, date);
|
||||
return { ...agent, timeBreakdown: summary };
|
||||
const summary = await this.ozonetel.getAgentSummary(agent.ozonetelAgentId, date);
|
||||
|
||||
// Filter CDR to this agent
|
||||
const agentCdr = allCdr.filter(
|
||||
(c: any) => c.AgentID === agent.ozonetelAgentId || c.AgentName === agent.ozonetelAgentId,
|
||||
);
|
||||
const totalCalls = agentCdr.length;
|
||||
const inbound = agentCdr.filter((c: any) => c.Type === 'InBound').length;
|
||||
const outbound = agentCdr.filter((c: any) => c.Type === 'Manual' || c.Type === 'Progressive').length;
|
||||
const answered = agentCdr.filter((c: any) => c.Status === 'Answered').length;
|
||||
const missed = agentCdr.filter((c: any) => c.Status === 'NotAnswered').length;
|
||||
|
||||
return {
|
||||
...agent,
|
||||
timeBreakdown: summary,
|
||||
calls: { total: totalCalls, inbound, outbound, answered, missed },
|
||||
};
|
||||
} catch (err) {
|
||||
this.logger.warn(`Failed to get summary for ${agent.ozonetelagentid}: ${err}`);
|
||||
return { ...agent, timeBreakdown: null };
|
||||
this.logger.warn(`Failed to get summary for ${agent.ozonetelAgentId}: ${err}`);
|
||||
return { ...agent, timeBreakdown: null, calls: null };
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
return { date, agents: summaries };
|
||||
// Aggregate team totals
|
||||
const teamTotals = {
|
||||
totalCalls: summaries.reduce((sum, a) => sum + (a.calls?.total ?? 0), 0),
|
||||
inbound: summaries.reduce((sum, a) => sum + (a.calls?.inbound ?? 0), 0),
|
||||
outbound: summaries.reduce((sum, a) => sum + (a.calls?.outbound ?? 0), 0),
|
||||
answered: summaries.reduce((sum, a) => sum + (a.calls?.answered ?? 0), 0),
|
||||
missed: summaries.reduce((sum, a) => sum + (a.calls?.missed ?? 0), 0),
|
||||
};
|
||||
|
||||
return { date, agents: summaries, teamTotals };
|
||||
}
|
||||
}
|
||||
|
||||
39
src/team/team.controller.ts
Normal file
39
src/team/team.controller.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import { Body, Controller, Get, Param, Post, Put } from '@nestjs/common';
|
||||
import {
|
||||
TeamService,
|
||||
type CreateMemberInput,
|
||||
type CreatedMember,
|
||||
type UpdateMemberInput,
|
||||
} from './team.service';
|
||||
|
||||
// REST wrapper around TeamService. Mounted at /api/team/*.
|
||||
// The Team wizard step on the frontend posts here instead of firing
|
||||
// the platform's sendInvitations mutation directly.
|
||||
|
||||
@Controller('api/team')
|
||||
export class TeamController {
|
||||
constructor(private team: TeamService) {}
|
||||
|
||||
@Post('members')
|
||||
async createMember(@Body() body: CreateMemberInput): Promise<CreatedMember> {
|
||||
return this.team.createMember(body);
|
||||
}
|
||||
|
||||
@Put('members/:id')
|
||||
async updateMember(
|
||||
@Param('id') id: string,
|
||||
@Body() body: UpdateMemberInput,
|
||||
): Promise<{ id: string }> {
|
||||
return this.team.updateMember(id, body);
|
||||
}
|
||||
|
||||
// Returns the cached plaintext temp password for a recently-created
|
||||
// member if it's still within its 24h TTL, or { password: null }
|
||||
// on cache miss. Used by the wizard's right-pane copy icon when
|
||||
// its in-browser memory was wiped by a refresh.
|
||||
@Get('members/:id/temp-password')
|
||||
async getTempPassword(@Param('id') id: string): Promise<{ password: string | null }> {
|
||||
const password = await this.team.getTempPassword(id);
|
||||
return { password };
|
||||
}
|
||||
}
|
||||
16
src/team/team.module.ts
Normal file
16
src/team/team.module.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { PlatformModule } from '../platform/platform.module';
|
||||
import { AuthModule } from '../auth/auth.module';
|
||||
import { TeamController } from './team.controller';
|
||||
import { TeamService } from './team.service';
|
||||
|
||||
// AuthModule is imported because TeamService uses SessionService for
|
||||
// its generic Redis cache (storing recently-created temp passwords
|
||||
// with a 24h TTL so the right pane's copy icon survives a reload).
|
||||
@Module({
|
||||
imports: [PlatformModule, AuthModule],
|
||||
controllers: [TeamController],
|
||||
providers: [TeamService],
|
||||
exports: [TeamService],
|
||||
})
|
||||
export class TeamModule {}
|
||||
334
src/team/team.service.ts
Normal file
334
src/team/team.service.ts
Normal file
@@ -0,0 +1,334 @@
|
||||
import { BadRequestException, Injectable, Logger } from '@nestjs/common';
|
||||
import { PlatformGraphqlService } from '../platform/platform-graphql.service';
|
||||
import { SessionService } from '../auth/session.service';
|
||||
|
||||
// Recently-created temp passwords are cached in Redis under this prefix
|
||||
// for 24 hours so the right pane's copy icon keeps working after a
|
||||
// browser refresh. The plaintext expires automatically — the assumption
|
||||
// is the employee logs in within a day, at which point the password
|
||||
// loses value anyway.
|
||||
const TEMP_PASSWORD_KEY_PREFIX = 'team:tempPassword:';
|
||||
const TEMP_PASSWORD_TTL_SECONDS = 24 * 60 * 60;
|
||||
const tempPasswordKey = (memberId: string) => `${TEMP_PASSWORD_KEY_PREFIX}${memberId}`;
|
||||
|
||||
// In-place employee creation. The platform's sendInvitations flow is
|
||||
// deliberately NOT used — hospital admins create employees from the
|
||||
// portal and hand out credentials directly (see feedback-no-invites in
|
||||
// memory).
|
||||
//
|
||||
// Chain:
|
||||
// 1. Fetch workspace invite hash (workspace-level setting) so
|
||||
// signUpInWorkspace accepts our call — this is the same hash the
|
||||
// public invite link uses but we consume it server-side.
|
||||
// 2. signUpInWorkspace(email, password, workspaceId, workspaceInviteHash)
|
||||
// — creates the core.user row + the workspaceMember row. Returns
|
||||
// a loginToken we throw away (admin has their own session).
|
||||
// 3. Look up the workspaceMember we just created, filtering by
|
||||
// userEmail (the only field we have to go on).
|
||||
// 4. updateWorkspaceMember to set firstName / lastName.
|
||||
// 5. updateWorkspaceMemberRole to assign the role the admin picked.
|
||||
// 6. (optional) updateAgent to link the new member to a SIP seat if
|
||||
// they're a CC agent.
|
||||
//
|
||||
// Errors from any step bubble up as a BadRequestException — the admin
|
||||
// sees the real GraphQL error message, which usually tells them
|
||||
// exactly what went wrong (email already exists, role not assignable,
|
||||
// etc).
|
||||
|
||||
export type CreateMemberInput = {
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
email: string;
|
||||
password: string;
|
||||
roleId: string;
|
||||
// Optional SIP seat link — set when the role is HelixEngage User
|
||||
// (CC agent). Ignored otherwise.
|
||||
agentId?: string | null;
|
||||
};
|
||||
|
||||
export type CreatedMember = {
|
||||
id: string;
|
||||
userId: string;
|
||||
userEmail: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
roleId: string;
|
||||
agentId: string | null;
|
||||
};
|
||||
|
||||
// Update payload — name + role only. Email and password are not
|
||||
// touched (they need separate flows). SIP seat reassignment goes
|
||||
// through the Telephony step's updateAgent path, not here.
|
||||
export type UpdateMemberInput = {
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
roleId: string;
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class TeamService {
|
||||
private readonly logger = new Logger(TeamService.name);
|
||||
// Workspace invite hash is stable for the lifetime of the workspace
|
||||
// — cache it after first fetch so subsequent creates skip the
|
||||
// extra round-trip.
|
||||
private cachedInviteHash: { workspaceId: string; inviteHash: string } | null = null;
|
||||
|
||||
constructor(
|
||||
private platform: PlatformGraphqlService,
|
||||
private session: SessionService,
|
||||
) {}
|
||||
|
||||
async createMember(input: CreateMemberInput): Promise<CreatedMember> {
|
||||
const email = input.email.trim().toLowerCase();
|
||||
const firstName = input.firstName.trim();
|
||||
const lastName = input.lastName.trim();
|
||||
|
||||
if (!email || !firstName || !input.password || !input.roleId) {
|
||||
throw new BadRequestException('email, firstName, password and roleId are required');
|
||||
}
|
||||
|
||||
// Step 1 — fetch workspace id + invite hash
|
||||
const ws = await this.getWorkspaceContext();
|
||||
|
||||
// Step 2 — create the user + workspace member via signUpInWorkspace
|
||||
try {
|
||||
await this.platform.query(
|
||||
`mutation SignUpInWorkspace($email: String!, $password: String!, $workspaceId: UUID!, $workspaceInviteHash: String!) {
|
||||
signUpInWorkspace(
|
||||
email: $email,
|
||||
password: $password,
|
||||
workspaceId: $workspaceId,
|
||||
workspaceInviteHash: $workspaceInviteHash,
|
||||
) {
|
||||
workspace { id }
|
||||
}
|
||||
}`,
|
||||
{
|
||||
email,
|
||||
password: input.password,
|
||||
workspaceId: ws.workspaceId,
|
||||
workspaceInviteHash: ws.inviteHash,
|
||||
},
|
||||
);
|
||||
} catch (err) {
|
||||
this.logger.warn(`signUpInWorkspace failed for ${email}: ${err}`);
|
||||
throw new BadRequestException(this.extractGraphqlMessage(err));
|
||||
}
|
||||
|
||||
// Step 3 — find the workspaceMember that just got created. We
|
||||
// filter by userEmail since that's the only handle we have.
|
||||
// Plural query + client-side pick so we don't rely on a
|
||||
// specific filter shape.
|
||||
const membersData = await this.platform.query<{
|
||||
workspaceMembers: { edges: { node: { id: string; userId: string; userEmail: string } }[] };
|
||||
}>(
|
||||
`{ workspaceMembers { edges { node { id userId userEmail } } } }`,
|
||||
);
|
||||
const member = membersData.workspaceMembers.edges
|
||||
.map((e) => e.node)
|
||||
.find((m) => (m.userEmail ?? '').toLowerCase() === email);
|
||||
if (!member) {
|
||||
throw new BadRequestException(
|
||||
'Workspace member was created but could not be located — retry in a few seconds',
|
||||
);
|
||||
}
|
||||
|
||||
// Step 4 — set their name. Note: the platform's
|
||||
// updateWorkspaceMember mutation declares its `id` arg as
|
||||
// `UUID!` (not `ID!`), and GraphQL refuses to coerce between
|
||||
// those scalars even though both hold the same string value.
|
||||
// Same applies to updateAgent below — verified via __schema
|
||||
// introspection. Pre-existing code in platform-graphql.service
|
||||
// still uses `ID!` for updateLead; that's a separate latent
|
||||
// bug that's untouched here so the diff stays focused on the
|
||||
// team-create failure.
|
||||
try {
|
||||
await this.platform.query(
|
||||
`mutation UpdateWorkspaceMember($id: UUID!, $data: WorkspaceMemberUpdateInput!) {
|
||||
updateWorkspaceMember(id: $id, data: $data) { id }
|
||||
}`,
|
||||
{
|
||||
id: member.id,
|
||||
data: {
|
||||
name: { firstName, lastName },
|
||||
},
|
||||
},
|
||||
);
|
||||
} catch (err) {
|
||||
this.logger.warn(`updateWorkspaceMember name failed for ${member.id}: ${err}`);
|
||||
// Non-fatal — the account exists, just unnamed. Surface it
|
||||
// anyway so the admin can fix in settings.
|
||||
throw new BadRequestException(this.extractGraphqlMessage(err));
|
||||
}
|
||||
|
||||
// Step 5 — assign role
|
||||
try {
|
||||
await this.platform.query(
|
||||
`mutation AssignRole($workspaceMemberId: UUID!, $roleId: UUID!) {
|
||||
updateWorkspaceMemberRole(workspaceMemberId: $workspaceMemberId, roleId: $roleId) {
|
||||
id
|
||||
}
|
||||
}`,
|
||||
{ workspaceMemberId: member.id, roleId: input.roleId },
|
||||
);
|
||||
} catch (err) {
|
||||
this.logger.warn(`updateWorkspaceMemberRole failed for ${member.id}: ${err}`);
|
||||
throw new BadRequestException(this.extractGraphqlMessage(err));
|
||||
}
|
||||
|
||||
// Step 6 — (optional) link SIP seat
|
||||
if (input.agentId) {
|
||||
try {
|
||||
await this.platform.query(
|
||||
`mutation LinkAgent($id: UUID!, $data: AgentUpdateInput!) {
|
||||
updateAgent(id: $id, data: $data) { id workspaceMemberId }
|
||||
}`,
|
||||
{
|
||||
id: input.agentId,
|
||||
data: { workspaceMemberId: member.id },
|
||||
},
|
||||
);
|
||||
} catch (err) {
|
||||
this.logger.warn(`updateAgent link failed for agent ${input.agentId}: ${err}`);
|
||||
throw new BadRequestException(this.extractGraphqlMessage(err));
|
||||
}
|
||||
}
|
||||
|
||||
// Cache the plaintext temp password in Redis (24h TTL) so the
|
||||
// wizard's right-pane copy icon keeps working after a browser
|
||||
// refresh. The password is also stored hashed on the platform
|
||||
// (used for actual login auth) — this Redis copy exists ONLY
|
||||
// so the admin can recover the plaintext to share with the
|
||||
// employee. Expires automatically; no plaintext persists past
|
||||
// 24h. Trade-off accepted because the plan is to force a
|
||||
// password reset on first login (defense in depth).
|
||||
try {
|
||||
await this.session.setCache(
|
||||
tempPasswordKey(member.id),
|
||||
input.password,
|
||||
TEMP_PASSWORD_TTL_SECONDS,
|
||||
);
|
||||
} catch (err) {
|
||||
this.logger.warn(`Failed to cache temp password for ${member.id}: ${err}`);
|
||||
// Non-fatal — admin can still copy from session memory
|
||||
// before page reload. We just lose the post-reload
|
||||
// recovery path for this one member.
|
||||
}
|
||||
|
||||
this.logger.log(
|
||||
`Created member ${email} (id=${member.id}) role=${input.roleId} agent=${input.agentId ?? 'none'}`,
|
||||
);
|
||||
|
||||
return {
|
||||
id: member.id,
|
||||
userId: member.userId,
|
||||
userEmail: email,
|
||||
firstName,
|
||||
lastName,
|
||||
roleId: input.roleId,
|
||||
agentId: input.agentId ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
// Read the cached temp password for a member, if it's still
|
||||
// within its 24h TTL. Returns null on miss (cache expired, member
|
||||
// never created via this endpoint, or Redis unreachable). The
|
||||
// wizard's copy icon falls back to this when the in-browser
|
||||
// memory was wiped by a page reload.
|
||||
async getTempPassword(memberId: string): Promise<string | null> {
|
||||
if (!memberId) return null;
|
||||
try {
|
||||
return await this.session.getCache(tempPasswordKey(memberId));
|
||||
} catch (err) {
|
||||
this.logger.warn(`Failed to read temp password cache for ${memberId}: ${err}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Update an existing workspace member — name + role only.
|
||||
// Mirrors the create path's mutation chain but skips signUp,
|
||||
// member lookup, and the SIP seat link. Errors bubble up as
|
||||
// BadRequestException so the admin sees the real GraphQL message.
|
||||
async updateMember(memberId: string, input: UpdateMemberInput): Promise<{ id: string }> {
|
||||
const firstName = input.firstName.trim();
|
||||
const lastName = input.lastName.trim();
|
||||
|
||||
if (!memberId || !firstName || !input.roleId) {
|
||||
throw new BadRequestException('memberId, firstName and roleId are required');
|
||||
}
|
||||
|
||||
// Step 1 — set their name
|
||||
try {
|
||||
await this.platform.query(
|
||||
`mutation UpdateWorkspaceMember($id: UUID!, $data: WorkspaceMemberUpdateInput!) {
|
||||
updateWorkspaceMember(id: $id, data: $data) { id }
|
||||
}`,
|
||||
{
|
||||
id: memberId,
|
||||
data: {
|
||||
name: { firstName, lastName },
|
||||
},
|
||||
},
|
||||
);
|
||||
} catch (err) {
|
||||
this.logger.warn(`updateWorkspaceMember name failed for ${memberId}: ${err}`);
|
||||
throw new BadRequestException(this.extractGraphqlMessage(err));
|
||||
}
|
||||
|
||||
// Step 2 — assign role (idempotent — same call as the create
|
||||
// path so changing role from X to X is a no-op).
|
||||
try {
|
||||
await this.platform.query(
|
||||
`mutation AssignRole($workspaceMemberId: UUID!, $roleId: UUID!) {
|
||||
updateWorkspaceMemberRole(workspaceMemberId: $workspaceMemberId, roleId: $roleId) {
|
||||
id
|
||||
}
|
||||
}`,
|
||||
{ workspaceMemberId: memberId, roleId: input.roleId },
|
||||
);
|
||||
} catch (err) {
|
||||
this.logger.warn(`updateWorkspaceMemberRole failed for ${memberId}: ${err}`);
|
||||
throw new BadRequestException(this.extractGraphqlMessage(err));
|
||||
}
|
||||
|
||||
this.logger.log(`Updated member ${memberId} (name="${firstName} ${lastName}", role=${input.roleId})`);
|
||||
return { id: memberId };
|
||||
}
|
||||
|
||||
private async getWorkspaceContext(): Promise<{ workspaceId: string; inviteHash: string }> {
|
||||
if (this.cachedInviteHash) return this.cachedInviteHash;
|
||||
const data = await this.platform.query<{
|
||||
currentWorkspace: {
|
||||
id: string;
|
||||
inviteHash: string;
|
||||
isPublicInviteLinkEnabled: boolean;
|
||||
};
|
||||
}>(`{ currentWorkspace { id inviteHash isPublicInviteLinkEnabled } }`);
|
||||
|
||||
const ws = data.currentWorkspace;
|
||||
if (!ws?.id || !ws?.inviteHash) {
|
||||
throw new BadRequestException(
|
||||
'Workspace is missing id/inviteHash — cannot create employees in-place',
|
||||
);
|
||||
}
|
||||
if (!ws.isPublicInviteLinkEnabled) {
|
||||
// signUpInWorkspace will reject us without this flag set.
|
||||
// Surface a clear error instead of the platform's opaque
|
||||
// "FORBIDDEN" response.
|
||||
throw new BadRequestException(
|
||||
'Workspace public invite link is disabled — enable it in workspace settings so the server can mint user accounts directly',
|
||||
);
|
||||
}
|
||||
this.cachedInviteHash = { workspaceId: ws.id, inviteHash: ws.inviteHash };
|
||||
return this.cachedInviteHash;
|
||||
}
|
||||
|
||||
private extractGraphqlMessage(err: unknown): string {
|
||||
const msg = (err as Error)?.message ?? 'Unknown error';
|
||||
// PlatformGraphqlService wraps errors as `GraphQL error: [{...}]`.
|
||||
// Pull out the first message so the admin sees something
|
||||
// meaningful in the toast.
|
||||
const match = msg.match(/"message":"([^"]+)"/);
|
||||
return match ? match[1] : msg;
|
||||
}
|
||||
}
|
||||
243
src/team/team.spec.ts
Normal file
243
src/team/team.spec.ts
Normal file
@@ -0,0 +1,243 @@
|
||||
/**
|
||||
* Team Service — unit tests
|
||||
*
|
||||
* Tests the in-place workspace member creation flow (no email invites):
|
||||
* 1. signUpInWorkspace → creates user + workspace member
|
||||
* 2. updateWorkspaceMember → set name
|
||||
* 3. updateWorkspaceMemberRole → assign role
|
||||
* 4. (optional) updateAgent → link SIP seat
|
||||
*
|
||||
* Platform GraphQL + SessionService are mocked.
|
||||
*/
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { TeamService, CreateMemberInput } from './team.service';
|
||||
import { PlatformGraphqlService } from '../platform/platform-graphql.service';
|
||||
import { SessionService } from '../auth/session.service';
|
||||
|
||||
describe('TeamService', () => {
|
||||
let service: TeamService;
|
||||
let platform: jest.Mocked<PlatformGraphqlService>;
|
||||
let session: jest.Mocked<SessionService>;
|
||||
|
||||
const mockWorkspace = {
|
||||
id: '42424242-1c25-4d02-bf25-6aeccf7ea419',
|
||||
inviteHash: 'test-invite-hash',
|
||||
isPublicInviteLinkEnabled: true,
|
||||
};
|
||||
|
||||
const mockMemberId = 'member-new-001';
|
||||
|
||||
beforeEach(async () => {
|
||||
const module = await Test.createTestingModule({
|
||||
providers: [
|
||||
TeamService,
|
||||
{
|
||||
provide: PlatformGraphqlService,
|
||||
useValue: {
|
||||
query: jest.fn().mockImplementation((query: string) => {
|
||||
if (query.includes('currentWorkspace')) {
|
||||
return Promise.resolve({ currentWorkspace: mockWorkspace });
|
||||
}
|
||||
if (query.includes('signUpInWorkspace')) {
|
||||
return Promise.resolve({ signUpInWorkspace: { workspace: { id: mockWorkspace.id } } });
|
||||
}
|
||||
if (query.includes('workspaceMembers')) {
|
||||
return Promise.resolve({
|
||||
workspaceMembers: {
|
||||
edges: [{
|
||||
node: {
|
||||
id: mockMemberId,
|
||||
userId: 'user-new-001',
|
||||
userEmail: 'ccagent@ramaiahcare.com',
|
||||
},
|
||||
}],
|
||||
},
|
||||
});
|
||||
}
|
||||
if (query.includes('updateWorkspaceMember')) {
|
||||
return Promise.resolve({ updateWorkspaceMember: { id: mockMemberId } });
|
||||
}
|
||||
if (query.includes('updateWorkspaceMemberRole')) {
|
||||
return Promise.resolve({ updateWorkspaceMemberRole: { id: mockMemberId } });
|
||||
}
|
||||
if (query.includes('updateAgent')) {
|
||||
return Promise.resolve({ updateAgent: { id: 'agent-001', workspaceMemberId: mockMemberId } });
|
||||
}
|
||||
return Promise.resolve({});
|
||||
}),
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: SessionService,
|
||||
useValue: {
|
||||
setCache: jest.fn().mockResolvedValue(undefined),
|
||||
getCache: jest.fn().mockResolvedValue(null),
|
||||
},
|
||||
},
|
||||
],
|
||||
}).compile();
|
||||
|
||||
service = module.get(TeamService);
|
||||
platform = module.get(PlatformGraphqlService);
|
||||
session = module.get(SessionService);
|
||||
});
|
||||
|
||||
// ── Create member (standard flow) ────────────────────────────
|
||||
|
||||
it('should create a workspace member with correct 5-step flow', async () => {
|
||||
const input: CreateMemberInput = {
|
||||
firstName: 'CC',
|
||||
lastName: 'Agent',
|
||||
email: 'ccagent@ramaiahcare.com',
|
||||
password: 'CcRamaiah@2026',
|
||||
roleId: 'role-agent-001',
|
||||
};
|
||||
|
||||
const result = await service.createMember(input);
|
||||
|
||||
expect(result.id).toBe(mockMemberId);
|
||||
expect(result.userEmail).toBe('ccagent@ramaiahcare.com');
|
||||
|
||||
// Verify the 5-step call chain
|
||||
const calls = platform.query.mock.calls.map(c => c[0] as string);
|
||||
|
||||
// Step 1: fetch workspace context (inviteHash)
|
||||
expect(calls.some(q => q.includes('currentWorkspace'))).toBe(true);
|
||||
// Step 2: signUpInWorkspace
|
||||
expect(calls.some(q => q.includes('signUpInWorkspace'))).toBe(true);
|
||||
// Step 3: find member by email
|
||||
expect(calls.some(q => q.includes('workspaceMembers'))).toBe(true);
|
||||
// Step 4: set name
|
||||
expect(calls.some(q => q.includes('updateWorkspaceMember'))).toBe(true);
|
||||
// Step 5: assign role
|
||||
expect(calls.some(q => q.includes('updateWorkspaceMemberRole'))).toBe(true);
|
||||
});
|
||||
|
||||
// ── Create member with SIP seat link ─────────────────────────
|
||||
|
||||
it('should link agent SIP seat when agentId is provided', async () => {
|
||||
const input: CreateMemberInput = {
|
||||
firstName: 'CC',
|
||||
lastName: 'Agent',
|
||||
email: 'ccagent@ramaiahcare.com',
|
||||
password: 'CcRamaiah@2026',
|
||||
roleId: 'role-agent-001',
|
||||
agentId: 'agent-sip-001',
|
||||
};
|
||||
|
||||
const result = await service.createMember(input);
|
||||
|
||||
// Step 6: updateAgent (links workspaceMemberId)
|
||||
const agentCall = platform.query.mock.calls.find(
|
||||
c => (c[0] as string).includes('updateAgent'),
|
||||
);
|
||||
expect(agentCall).toBeDefined();
|
||||
expect(agentCall![1]).toMatchObject({
|
||||
id: 'agent-sip-001',
|
||||
data: { workspaceMemberId: mockMemberId },
|
||||
});
|
||||
});
|
||||
|
||||
// ── Validation ───────────────────────────────────────────────
|
||||
|
||||
it('should reject missing required fields', async () => {
|
||||
await expect(
|
||||
service.createMember({
|
||||
firstName: '',
|
||||
lastName: 'Test',
|
||||
email: 'test@ramaiahcare.com',
|
||||
password: 'pass',
|
||||
roleId: 'role-001',
|
||||
}),
|
||||
).rejects.toThrow();
|
||||
});
|
||||
|
||||
it('should reject missing email', async () => {
|
||||
await expect(
|
||||
service.createMember({
|
||||
firstName: 'Test',
|
||||
lastName: 'User',
|
||||
email: '',
|
||||
password: 'pass',
|
||||
roleId: 'role-001',
|
||||
}),
|
||||
).rejects.toThrow();
|
||||
});
|
||||
|
||||
// ── Temp password caching ────────────────────────────────────
|
||||
|
||||
it('should cache temp password in Redis with 24h TTL', async () => {
|
||||
const input: CreateMemberInput = {
|
||||
firstName: 'CC',
|
||||
lastName: 'Agent',
|
||||
email: 'ccagent@ramaiahcare.com',
|
||||
password: 'CcRamaiah@2026',
|
||||
roleId: 'role-001',
|
||||
};
|
||||
|
||||
await service.createMember(input);
|
||||
|
||||
// Redis setCache should be called with the temp password
|
||||
expect(session.setCache).toHaveBeenCalledWith(
|
||||
expect.stringContaining('team:tempPassword:'),
|
||||
'CcRamaiah@2026',
|
||||
86400, // 24 hours
|
||||
);
|
||||
});
|
||||
|
||||
// ── Email normalization ──────────────────────────────────────
|
||||
|
||||
it('should lowercase email before signUp', async () => {
|
||||
const input: CreateMemberInput = {
|
||||
firstName: 'Test',
|
||||
lastName: 'User',
|
||||
email: 'CcAgent@RamaiahCare.COM',
|
||||
password: 'pass',
|
||||
roleId: 'role-001',
|
||||
};
|
||||
|
||||
await service.createMember(input);
|
||||
|
||||
const signUpCall = platform.query.mock.calls.find(
|
||||
c => (c[0] as string).includes('signUpInWorkspace'),
|
||||
);
|
||||
expect(signUpCall![1]?.email).toBe('ccagent@ramaiahcare.com');
|
||||
});
|
||||
|
||||
// ── Workspace context caching ────────────────────────────────
|
||||
|
||||
it('should fetch workspace context only once for multiple creates', async () => {
|
||||
let callCount = 0;
|
||||
|
||||
platform.query.mockImplementation((query: string) => {
|
||||
if (query.includes('currentWorkspace')) {
|
||||
return Promise.resolve({ currentWorkspace: mockWorkspace });
|
||||
}
|
||||
if (query.includes('signUpInWorkspace')) {
|
||||
return Promise.resolve({ signUpInWorkspace: { workspace: { id: mockWorkspace.id } } });
|
||||
}
|
||||
if (query.includes('workspaceMembers')) {
|
||||
callCount++;
|
||||
// Return matching email based on call order
|
||||
const email = callCount <= 1 ? 'a@test.com' : 'b@test.com';
|
||||
return Promise.resolve({
|
||||
workspaceMembers: {
|
||||
edges: [{ node: { id: `member-${callCount}`, userId: 'u', userEmail: email } }],
|
||||
},
|
||||
});
|
||||
}
|
||||
if (query.includes('updateWorkspaceMember')) return Promise.resolve({ updateWorkspaceMember: { id: 'member-x' } });
|
||||
if (query.includes('updateWorkspaceMemberRole')) return Promise.resolve({ updateWorkspaceMemberRole: { id: 'member-x' } });
|
||||
return Promise.resolve({});
|
||||
});
|
||||
|
||||
await service.createMember({ firstName: 'A', lastName: 'B', email: 'a@test.com', password: 'p', roleId: 'r' });
|
||||
await service.createMember({ firstName: 'C', lastName: 'D', email: 'b@test.com', password: 'p', roleId: 'r' });
|
||||
|
||||
const wsCalls = platform.query.mock.calls.filter(
|
||||
c => (c[0] as string).includes('currentWorkspace'),
|
||||
);
|
||||
// Should only fetch workspace context once (cached)
|
||||
expect(wsCalls.length).toBe(1);
|
||||
});
|
||||
});
|
||||
114
src/telephony-registration.service.ts
Normal file
114
src/telephony-registration.service.ts
Normal file
@@ -0,0 +1,114 @@
|
||||
import { Injectable, Logger, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import axios from 'axios';
|
||||
import { PlatformGraphqlService } from './platform/platform-graphql.service';
|
||||
|
||||
// On startup, registers this sidecar with the telephony dispatcher
|
||||
// so Ozonetel events are routed to the correct sidecar by agentId.
|
||||
//
|
||||
// Flow:
|
||||
// 1. Load agent list from platform (Agent entities in this workspace)
|
||||
// 2. POST /api/supervisor/register to the dispatcher
|
||||
// 3. Start heartbeat interval (every 30s)
|
||||
// 4. On shutdown, DELETE /api/supervisor/register
|
||||
|
||||
const HEARTBEAT_INTERVAL_MS = 30_000;
|
||||
|
||||
@Injectable()
|
||||
export class TelephonyRegistrationService implements OnModuleInit, OnModuleDestroy {
|
||||
private readonly logger = new Logger(TelephonyRegistrationService.name);
|
||||
private heartbeatTimer: NodeJS.Timeout | null = null;
|
||||
|
||||
constructor(
|
||||
private config: ConfigService,
|
||||
private platform: PlatformGraphqlService,
|
||||
) {}
|
||||
|
||||
private get dispatcherUrl(): string {
|
||||
return this.config.get<string>('TELEPHONY_DISPATCHER_URL') ?? '';
|
||||
}
|
||||
|
||||
private get sidecarUrl(): string {
|
||||
return this.config.get<string>('TELEPHONY_CALLBACK_URL') ?? '';
|
||||
}
|
||||
|
||||
private get workspace(): string {
|
||||
return process.env.PLATFORM_WORKSPACE_SUBDOMAIN ?? 'unknown';
|
||||
}
|
||||
|
||||
async onModuleInit() {
|
||||
if (!this.dispatcherUrl || !this.sidecarUrl) {
|
||||
this.logger.warn('TELEPHONY_DISPATCHER_URL or TELEPHONY_CALLBACK_URL not set — skipping telephony registration');
|
||||
return;
|
||||
}
|
||||
|
||||
await this.register();
|
||||
|
||||
this.heartbeatTimer = setInterval(async () => {
|
||||
try {
|
||||
await axios.post(`${this.dispatcherUrl}/api/supervisor/heartbeat`, {
|
||||
sidecarUrl: this.sidecarUrl,
|
||||
}, { timeout: 5000 });
|
||||
} catch (err: any) {
|
||||
this.logger.warn(`Heartbeat failed: ${err.message} — attempting re-registration`);
|
||||
await this.register();
|
||||
}
|
||||
}, HEARTBEAT_INTERVAL_MS);
|
||||
}
|
||||
|
||||
async onModuleDestroy() {
|
||||
if (this.heartbeatTimer) clearInterval(this.heartbeatTimer);
|
||||
|
||||
if (this.dispatcherUrl && this.sidecarUrl) {
|
||||
try {
|
||||
await axios.delete(`${this.dispatcherUrl}/api/supervisor/register`, {
|
||||
data: { sidecarUrl: this.sidecarUrl },
|
||||
timeout: 5000,
|
||||
});
|
||||
this.logger.log('Deregistered from telephony dispatcher');
|
||||
} catch {
|
||||
// Best-effort — TTL will clean up anyway
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async register() {
|
||||
try {
|
||||
const agents = await this.loadAgentIds();
|
||||
if (agents.length === 0) {
|
||||
this.logger.warn('No agents found in workspace — skipping registration');
|
||||
return;
|
||||
}
|
||||
|
||||
await axios.post(`${this.dispatcherUrl}/api/supervisor/register`, {
|
||||
sidecarUrl: this.sidecarUrl,
|
||||
workspace: this.workspace,
|
||||
agents,
|
||||
}, { timeout: 5000 });
|
||||
|
||||
this.logger.log(`Registered with telephony dispatcher: ${agents.length} agents (${agents.join(', ')})`);
|
||||
} catch (err: any) {
|
||||
this.logger.error(`Registration failed: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
private async loadAgentIds(): Promise<string[]> {
|
||||
try {
|
||||
const apiKey = this.config.get<string>('PLATFORM_API_KEY');
|
||||
if (!apiKey) return [];
|
||||
|
||||
const data = await this.platform.queryWithAuth<any>(
|
||||
`{ agents(first: 50) { edges { node { ozonetelAgentId } } } }`,
|
||||
undefined,
|
||||
`Bearer ${apiKey}`,
|
||||
);
|
||||
|
||||
return (data.agents?.edges ?? [])
|
||||
.map((e: any) => e.node.ozonetelAgentId)
|
||||
.filter((id: string) => id && id !== 'PENDING');
|
||||
} catch (err: any) {
|
||||
this.logger.warn(`Failed to load agents from platform: ${err.message}`);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
}
|
||||
46
src/widget/captcha.guard.ts
Normal file
46
src/widget/captcha.guard.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
import { CanActivate, ExecutionContext, Injectable, HttpException, Logger } from '@nestjs/common';
|
||||
|
||||
// Cloudflare Turnstile verification endpoint
|
||||
const TURNSTILE_VERIFY_URL = 'https://challenges.cloudflare.com/turnstile/v0/siteverify';
|
||||
|
||||
@Injectable()
|
||||
export class CaptchaGuard implements CanActivate {
|
||||
private readonly logger = new Logger(CaptchaGuard.name);
|
||||
private readonly secretKey: string;
|
||||
|
||||
constructor() {
|
||||
this.secretKey = process.env.RECAPTCHA_SECRET_KEY ?? '';
|
||||
}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
if (!this.secretKey) {
|
||||
this.logger.warn('RECAPTCHA_SECRET_KEY not set — captcha disabled');
|
||||
return true;
|
||||
}
|
||||
|
||||
const request = context.switchToHttp().getRequest();
|
||||
const token = request.body?.captchaToken;
|
||||
|
||||
if (!token) throw new HttpException('Captcha token required', 400);
|
||||
|
||||
try {
|
||||
const res = await fetch(TURNSTILE_VERIFY_URL, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ secret: this.secretKey, response: token }),
|
||||
});
|
||||
const data = await res.json();
|
||||
|
||||
if (!data.success) {
|
||||
this.logger.warn(`Captcha failed: success=${data.success} errors=${JSON.stringify(data['error-codes'] ?? [])}`);
|
||||
throw new HttpException('Captcha verification failed', 403);
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (err: any) {
|
||||
if (err instanceof HttpException) throw err;
|
||||
this.logger.error(`Captcha verification error: ${err.message}`);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
226
src/widget/webhooks.controller.ts
Normal file
226
src/widget/webhooks.controller.ts
Normal file
@@ -0,0 +1,226 @@
|
||||
import { Controller, Post, Get, Body, Query, Logger, HttpException } from '@nestjs/common';
|
||||
import { WidgetService } from './widget.service';
|
||||
import { createHmac } from 'crypto';
|
||||
|
||||
@Controller('api/webhook')
|
||||
export class WebhooksController {
|
||||
private readonly logger = new Logger(WebhooksController.name);
|
||||
private readonly googleWebhookKey: string;
|
||||
private readonly fbVerifyToken: string;
|
||||
|
||||
constructor(private readonly widget: WidgetService) {
|
||||
this.googleWebhookKey = process.env.GOOGLE_WEBHOOK_KEY ?? '';
|
||||
this.fbVerifyToken = process.env.FB_VERIFY_TOKEN ?? 'helix-engage-verify';
|
||||
}
|
||||
|
||||
// ─── Facebook / Instagram Lead Ads ───
|
||||
|
||||
// Webhook verification (Meta sends GET to verify endpoint)
|
||||
@Get('facebook')
|
||||
verifyFacebook(
|
||||
@Query('hub.mode') mode: string,
|
||||
@Query('hub.verify_token') token: string,
|
||||
@Query('hub.challenge') challenge: string,
|
||||
) {
|
||||
if (mode === 'subscribe' && token === this.fbVerifyToken) {
|
||||
this.logger.log('[FB] Webhook verified');
|
||||
return challenge;
|
||||
}
|
||||
throw new HttpException('Verification failed', 403);
|
||||
}
|
||||
|
||||
// Receive leads from Facebook/Instagram
|
||||
@Post('facebook')
|
||||
async facebookLead(@Body() body: any) {
|
||||
this.logger.log(`[FB] Webhook received: ${JSON.stringify(body).substring(0, 200)}`);
|
||||
|
||||
if (body.object !== 'page') {
|
||||
return { status: 'ignored', reason: 'not a page event' };
|
||||
}
|
||||
|
||||
let leadsCreated = 0;
|
||||
|
||||
for (const entry of body.entry ?? []) {
|
||||
for (const change of entry.changes ?? []) {
|
||||
if (change.field !== 'leadgen') continue;
|
||||
|
||||
const leadData = change.value;
|
||||
const leadgenId = leadData.leadgen_id;
|
||||
const formId = leadData.form_id;
|
||||
const pageId = leadData.page_id;
|
||||
|
||||
this.logger.log(`[FB] Lead received: leadgen_id=${leadgenId} form_id=${formId} page_id=${pageId}`);
|
||||
|
||||
// Fetch full lead data from Meta Graph API
|
||||
const lead = await this.fetchFacebookLead(leadgenId);
|
||||
if (!lead) {
|
||||
this.logger.warn(`[FB] Could not fetch lead data for ${leadgenId}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const name = this.extractFbField(lead, 'full_name') ?? 'Facebook Lead';
|
||||
const phone = this.extractFbField(lead, 'phone_number') ?? '';
|
||||
const email = this.extractFbField(lead, 'email') ?? '';
|
||||
|
||||
try {
|
||||
await this.widget.createLead({
|
||||
name,
|
||||
phone: phone.replace(/[^0-9+]/g, ''),
|
||||
interest: `Facebook Ad (form: ${formId})`,
|
||||
message: email ? `Email: ${email}` : undefined,
|
||||
captchaToken: 'webhook-bypass',
|
||||
});
|
||||
leadsCreated++;
|
||||
this.logger.log(`[FB] Lead created: ${name} (${phone})`);
|
||||
} catch (err: any) {
|
||||
this.logger.error(`[FB] Lead creation failed: ${err.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { status: 'ok', leadsCreated };
|
||||
}
|
||||
|
||||
private async fetchFacebookLead(leadgenId: string): Promise<any | null> {
|
||||
const accessToken = process.env.FB_PAGE_ACCESS_TOKEN;
|
||||
if (!accessToken) {
|
||||
this.logger.warn('[FB] FB_PAGE_ACCESS_TOKEN not set — cannot fetch lead details');
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch(`https://graph.facebook.com/v21.0/${leadgenId}?access_token=${accessToken}`);
|
||||
if (!res.ok) return null;
|
||||
return res.json();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private extractFbField(lead: any, fieldName: string): string | null {
|
||||
const fields = lead.field_data ?? [];
|
||||
const field = fields.find((f: any) => f.name === fieldName);
|
||||
return field?.values?.[0] ?? null;
|
||||
}
|
||||
|
||||
// ─── Google Ads Lead Form ───
|
||||
|
||||
@Post('google')
|
||||
async googleLead(@Body() body: any) {
|
||||
this.logger.log(`[GOOGLE] Webhook received: ${JSON.stringify(body).substring(0, 200)}`);
|
||||
|
||||
// Verify webhook key if configured
|
||||
if (this.googleWebhookKey && body.google_key) {
|
||||
const expected = createHmac('sha256', this.googleWebhookKey)
|
||||
.update(body.lead_id ?? '')
|
||||
.digest('hex');
|
||||
// Google sends the key directly, not as HMAC — just compare
|
||||
if (body.google_key !== this.googleWebhookKey) {
|
||||
this.logger.warn('[GOOGLE] Invalid webhook key');
|
||||
throw new HttpException('Invalid webhook key', 403);
|
||||
}
|
||||
}
|
||||
|
||||
const isTest = body.is_test === true;
|
||||
const leadId = body.lead_id;
|
||||
const campaignId = body.campaign_id;
|
||||
const formId = body.form_id;
|
||||
|
||||
// Extract user data from column data
|
||||
const userData = body.user_column_data ?? [];
|
||||
const name = this.extractGoogleField(userData, 'FULL_NAME')
|
||||
?? this.extractGoogleField(userData, 'FIRST_NAME')
|
||||
?? 'Google Ad Lead';
|
||||
const phone = this.extractGoogleField(userData, 'PHONE_NUMBER') ?? '';
|
||||
const email = this.extractGoogleField(userData, 'EMAIL') ?? '';
|
||||
const city = this.extractGoogleField(userData, 'CITY') ?? '';
|
||||
|
||||
this.logger.log(`[GOOGLE] Lead: ${name} | ${phone} | campaign=${campaignId} | test=${isTest}`);
|
||||
|
||||
try {
|
||||
const result = await this.widget.createLead({
|
||||
name,
|
||||
phone: phone.replace(/[^0-9+]/g, ''),
|
||||
interest: `Google Ad${isTest ? ' (TEST)' : ''} (campaign: ${campaignId ?? 'unknown'})`,
|
||||
message: [email, city].filter(Boolean).join(', ') || undefined,
|
||||
captchaToken: 'webhook-bypass',
|
||||
});
|
||||
|
||||
this.logger.log(`[GOOGLE] Lead created: ${result.leadId}${isTest ? ' (test)' : ''}`);
|
||||
return { status: 'ok', leadId: result.leadId, isTest };
|
||||
} catch (err: any) {
|
||||
this.logger.error(`[GOOGLE] Lead creation failed: ${err.message}`);
|
||||
throw new HttpException('Lead creation failed', 500);
|
||||
}
|
||||
}
|
||||
|
||||
private extractGoogleField(columnData: any[], fieldName: string): string | null {
|
||||
const field = columnData.find((f: any) => f.column_id === fieldName);
|
||||
return field?.string_value ?? null;
|
||||
}
|
||||
|
||||
// ─── Ozonetel WhatsApp Callback ───
|
||||
// Configure in Ozonetel: Chat Callback URL → https://engage-api.srv1477139.hstgr.cloud/api/webhook/whatsapp
|
||||
// Payload format will be adapted once Ozonetel confirms their schema
|
||||
|
||||
@Post('whatsapp')
|
||||
async whatsappLead(@Body() body: any) {
|
||||
this.logger.log(`[WHATSAPP] Webhook received: ${JSON.stringify(body).substring(0, 300)}`);
|
||||
|
||||
const phone = body.from ?? body.caller_id ?? body.phone ?? body.customerNumber ?? '';
|
||||
const name = body.name ?? body.customerName ?? '';
|
||||
const message = body.message ?? body.text ?? body.body ?? '';
|
||||
|
||||
if (!phone) {
|
||||
this.logger.warn('[WHATSAPP] No phone number in payload');
|
||||
return { status: 'ignored', reason: 'no phone number' };
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await this.widget.createLead({
|
||||
name: name || 'WhatsApp Lead',
|
||||
phone: phone.replace(/[^0-9+]/g, ''),
|
||||
interest: 'WhatsApp Enquiry',
|
||||
message: message || undefined,
|
||||
captchaToken: 'webhook-bypass',
|
||||
});
|
||||
this.logger.log(`[WHATSAPP] Lead created: ${result.leadId} (${phone})`);
|
||||
return { status: 'ok', leadId: result.leadId };
|
||||
} catch (err: any) {
|
||||
this.logger.error(`[WHATSAPP] Lead creation failed: ${err.message}`);
|
||||
return { status: 'error', message: err.message };
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Ozonetel SMS Callback ───
|
||||
// Configure in Ozonetel: SMS Callback URL → https://engage-api.srv1477139.hstgr.cloud/api/webhook/sms
|
||||
|
||||
@Post('sms')
|
||||
async smsLead(@Body() body: any) {
|
||||
this.logger.log(`[SMS] Webhook received: ${JSON.stringify(body).substring(0, 300)}`);
|
||||
|
||||
const phone = body.from ?? body.caller_id ?? body.phone ?? body.senderNumber ?? '';
|
||||
const name = body.name ?? '';
|
||||
const message = body.message ?? body.text ?? body.body ?? '';
|
||||
|
||||
if (!phone) {
|
||||
this.logger.warn('[SMS] No phone number in payload');
|
||||
return { status: 'ignored', reason: 'no phone number' };
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await this.widget.createLead({
|
||||
name: name || 'SMS Lead',
|
||||
phone: phone.replace(/[^0-9+]/g, ''),
|
||||
interest: 'SMS Enquiry',
|
||||
message: message || undefined,
|
||||
captchaToken: 'webhook-bypass',
|
||||
});
|
||||
this.logger.log(`[SMS] Lead created: ${result.leadId} (${phone})`);
|
||||
return { status: 'ok', leadId: result.leadId };
|
||||
} catch (err: any) {
|
||||
this.logger.error(`[SMS] Lead creation failed: ${err.message}`);
|
||||
return { status: 'error', message: err.message };
|
||||
}
|
||||
}
|
||||
}
|
||||
420
src/widget/widget-chat.service.ts
Normal file
420
src/widget/widget-chat.service.ts
Normal file
@@ -0,0 +1,420 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { streamText, tool, stepCountIs } from 'ai';
|
||||
import { z } from 'zod';
|
||||
import type { LanguageModel, ModelMessage } from 'ai';
|
||||
import { createAiModel, isAiConfigured, type AiProviderOpts } from '../ai/ai-provider';
|
||||
import { PlatformGraphqlService } from '../platform/platform-graphql.service';
|
||||
import { WidgetService } from './widget.service';
|
||||
import { AiConfigService } from '../config/ai-config.service';
|
||||
|
||||
@Injectable()
|
||||
export class WidgetChatService {
|
||||
private readonly logger = new Logger(WidgetChatService.name);
|
||||
private readonly apiKey: string;
|
||||
private knowledgeBase: string | null = null;
|
||||
private kbLoadedAt = 0;
|
||||
private readonly kbTtlMs = 5 * 60 * 1000;
|
||||
|
||||
constructor(
|
||||
private config: ConfigService,
|
||||
private platform: PlatformGraphqlService,
|
||||
private widget: WidgetService,
|
||||
private aiConfig: AiConfigService,
|
||||
) {
|
||||
this.apiKey = config.get<string>('platform.apiKey') ?? '';
|
||||
if (!this.hasAiModel()) {
|
||||
this.logger.warn('AI not configured — widget chat will return fallback replies');
|
||||
}
|
||||
}
|
||||
|
||||
// Build the model on demand so admin updates to provider/model take effect
|
||||
// immediately. Construction is cheap (just wraps the SDK clients).
|
||||
private aiOpts(): AiProviderOpts {
|
||||
const cfg = this.aiConfig.getConfig();
|
||||
return {
|
||||
provider: cfg.provider,
|
||||
model: cfg.model,
|
||||
anthropicApiKey: this.config.get<string>('ai.anthropicApiKey'),
|
||||
openaiApiKey: this.config.get<string>('ai.openaiApiKey'),
|
||||
};
|
||||
}
|
||||
|
||||
private buildAiModel(): LanguageModel | null {
|
||||
return createAiModel(this.aiOpts());
|
||||
}
|
||||
|
||||
private get auth() {
|
||||
return `Bearer ${this.apiKey}`;
|
||||
}
|
||||
|
||||
hasAiModel(): boolean {
|
||||
return isAiConfigured(this.aiOpts());
|
||||
}
|
||||
|
||||
// Find-or-create a lead by phone. Delegates to WidgetService so there's
|
||||
// a single source of truth for the dedup window + lead shape across
|
||||
// chat + book + contact.
|
||||
async findOrCreateLead(name: string, phone: string): Promise<string> {
|
||||
return this.widget.findOrCreateLeadByPhone(name, phone, {
|
||||
source: 'WEBSITE',
|
||||
status: 'NEW',
|
||||
interestedService: 'Website Chat',
|
||||
});
|
||||
}
|
||||
|
||||
// Fetch the first name of the lead's primary contact so we can greet the
|
||||
// visitor by name in the system prompt. Returns 'there' on any failure.
|
||||
async getLeadFirstName(leadId: string): Promise<string> {
|
||||
try {
|
||||
const data = await this.platform.queryWithAuth<any>(
|
||||
`query($id: UUID!) {
|
||||
leads(filter: { id: { eq: $id } }, first: 1) {
|
||||
edges { node { id contactName { firstName } } }
|
||||
}
|
||||
}`,
|
||||
{ id: leadId },
|
||||
this.auth,
|
||||
);
|
||||
const firstName = data?.leads?.edges?.[0]?.node?.contactName?.firstName;
|
||||
return (typeof firstName === 'string' && firstName.trim()) || 'there';
|
||||
} catch (err) {
|
||||
this.logger.warn(`Failed to fetch lead name for ${leadId}: ${err}`);
|
||||
return 'there';
|
||||
}
|
||||
}
|
||||
|
||||
// Append an exchange to the lead's activity log. One activity record per
|
||||
// user/assistant turn. Safe to call in the background (we don't block the
|
||||
// stream on this).
|
||||
async logExchange(leadId: string, userText: string, aiText: string): Promise<void> {
|
||||
const summary = `User: ${userText}\n\nAI: ${aiText}`.slice(0, 4000);
|
||||
try {
|
||||
await this.platform.queryWithAuth<any>(
|
||||
`mutation($data: LeadActivityCreateInput!) {
|
||||
createLeadActivity(data: $data) { id }
|
||||
}`,
|
||||
{
|
||||
data: {
|
||||
leadId,
|
||||
activityType: 'NOTE_ADDED',
|
||||
channel: 'SYSTEM',
|
||||
summary,
|
||||
occurredAt: new Date().toISOString(),
|
||||
performedBy: 'Website Chat',
|
||||
outcome: 'SUCCESSFUL',
|
||||
},
|
||||
},
|
||||
this.auth,
|
||||
);
|
||||
} catch (err) {
|
||||
this.logger.warn(`Failed to log chat activity for lead ${leadId}: ${err}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Build a compact knowledge base of doctor/department info for the system
|
||||
// prompt. Cached for 5 min to avoid a doctors query on every chat.
|
||||
private async getKnowledgeBase(): Promise<string> {
|
||||
const now = Date.now();
|
||||
if (this.knowledgeBase && now - this.kbLoadedAt < this.kbTtlMs) {
|
||||
return this.knowledgeBase;
|
||||
}
|
||||
|
||||
try {
|
||||
const doctors = await this.widget.getDoctors();
|
||||
const byDept = new Map<string, { name: string; visitingHours?: string; clinic?: string }[]>();
|
||||
for (const d of doctors) {
|
||||
const dept = (d.department ?? 'Other').replace(/_/g, ' ');
|
||||
if (!byDept.has(dept)) byDept.set(dept, []);
|
||||
byDept.get(dept)!.push({
|
||||
name: d.name,
|
||||
visitingHours: d.visitingHours,
|
||||
clinic: d.clinic?.clinicName,
|
||||
});
|
||||
}
|
||||
|
||||
const lines: string[] = ['DEPARTMENTS AND DOCTORS:'];
|
||||
for (const [dept, docs] of byDept) {
|
||||
lines.push(`\n${dept}:`);
|
||||
for (const doc of docs) {
|
||||
const extras: string[] = [];
|
||||
if (doc.visitingHours) extras.push(doc.visitingHours);
|
||||
if (doc.clinic) extras.push(doc.clinic);
|
||||
lines.push(` - ${doc.name}${extras.length ? ` (${extras.join(' • ')})` : ''}`);
|
||||
}
|
||||
}
|
||||
this.knowledgeBase = lines.join('\n');
|
||||
this.kbLoadedAt = now;
|
||||
} catch (err) {
|
||||
this.logger.warn(`Failed to build widget KB: ${err}`);
|
||||
this.knowledgeBase = 'DEPARTMENTS AND DOCTORS: (unavailable)';
|
||||
this.kbLoadedAt = now;
|
||||
}
|
||||
return this.knowledgeBase;
|
||||
}
|
||||
|
||||
async buildSystemPrompt(userName: string, selectedBranch: string | null): Promise<string> {
|
||||
const init = this.widget.getInitData();
|
||||
const kb = await this.getKnowledgeBase();
|
||||
|
||||
// Branch context flips the tool-usage rules: no branch = must call
|
||||
// pick_branch first; branch set = always pass it to branch-aware
|
||||
// tools. We pre-render this block since the structure is dynamic
|
||||
// and the template just slots it in via {{branchContext}}.
|
||||
const branchContext = selectedBranch
|
||||
? [
|
||||
`CURRENT BRANCH: ${selectedBranch}`,
|
||||
`The visitor is interested in the ${selectedBranch} branch. You MUST pass branch="${selectedBranch}"`,
|
||||
'to list_departments, show_clinic_timings, show_doctors, and show_doctor_slots every time.',
|
||||
].join('\n')
|
||||
: [
|
||||
'BRANCH STATUS: NOT SET',
|
||||
'The visitor has not picked a branch yet. Before calling list_departments, show_clinic_timings,',
|
||||
'show_doctors, or show_doctor_slots, you MUST call pick_branch first so the visitor can choose.',
|
||||
'Only skip this if the user asks a pure general question that does not need branch-specific data.',
|
||||
].join('\n');
|
||||
|
||||
return this.aiConfig.renderPrompt('widgetChat', {
|
||||
hospitalName: init.brand.name,
|
||||
userName,
|
||||
branchContext,
|
||||
knowledgeBase: kb,
|
||||
});
|
||||
}
|
||||
|
||||
// Streams the assistant reply as an async iterable of UIMessageChunk-shaped
|
||||
// objects. The controller writes these as SSE `data: ${json}\n\n` lines
|
||||
// over the HTTP response. Tools return structured payloads the widget
|
||||
// frontend renders as generative-UI cards.
|
||||
async *streamReply(systemPrompt: string, messages: ModelMessage[]): AsyncGenerator<any> {
|
||||
const aiModel = this.buildAiModel();
|
||||
if (!aiModel) throw new Error('AI not configured');
|
||||
|
||||
const platform = this.platform;
|
||||
const widgetSvc = this.widget;
|
||||
|
||||
// Branch-matching now uses the doctor's full `clinics` array
|
||||
// (NormalizedDoctor) since one doctor can visit multiple
|
||||
// clinics under the post-rework data model. doctorMatchesBranch
|
||||
// returns true if ANY of their visit-slot clinics matches.
|
||||
const matchesBranch = (d: any, branch: string | undefined): boolean => {
|
||||
if (!branch) return true;
|
||||
const needle = branch.toLowerCase();
|
||||
const clinics: Array<{ clinicName: string }> = d.clinics ?? [];
|
||||
return clinics.some((c) => c.clinicName.toLowerCase().includes(needle));
|
||||
};
|
||||
|
||||
const tools = {
|
||||
pick_branch: tool({
|
||||
description:
|
||||
'Show the list of hospital branches so the visitor can pick which one they are interested in. Call this BEFORE any branch-sensitive tool (list_departments, show_clinic_timings, show_doctors, show_doctor_slots) when CURRENT BRANCH is NOT SET.',
|
||||
inputSchema: z.object({}),
|
||||
execute: async () => {
|
||||
const doctors = await widgetSvc.getDoctors();
|
||||
// Branches come from the union of all doctors'
|
||||
// visit-slot clinics. Each (clinic × doctor) pair
|
||||
// counts once toward that branch's doctor count;
|
||||
// we use a Set on doctor ids to avoid double-
|
||||
// counting the same doctor against the same branch
|
||||
// when they have multiple slots there.
|
||||
const byBranch = new Map<
|
||||
string,
|
||||
{ doctorIds: Set<string>; departments: Set<string> }
|
||||
>();
|
||||
for (const d of doctors) {
|
||||
for (const c of d.clinics ?? []) {
|
||||
const name = c.clinicName?.trim();
|
||||
if (!name) continue;
|
||||
if (!byBranch.has(name)) {
|
||||
byBranch.set(name, {
|
||||
doctorIds: new Set(),
|
||||
departments: new Set(),
|
||||
});
|
||||
}
|
||||
const entry = byBranch.get(name)!;
|
||||
if (d.id) entry.doctorIds.add(d.id);
|
||||
if (d.department) entry.departments.add(String(d.department).replace(/_/g, ' '));
|
||||
}
|
||||
}
|
||||
return {
|
||||
branches: Array.from(byBranch.entries())
|
||||
.sort(([a], [b]) => a.localeCompare(b))
|
||||
.map(([name, { doctorIds, departments }]) => ({
|
||||
name,
|
||||
doctorCount: doctorIds.size,
|
||||
departmentCount: departments.size,
|
||||
})),
|
||||
};
|
||||
},
|
||||
}),
|
||||
list_departments: tool({
|
||||
description:
|
||||
'List the departments the hospital has. Use when the visitor asks what departments or specialities are available. Pass branch if CURRENT BRANCH is set.',
|
||||
inputSchema: z.object({
|
||||
branch: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe('Branch name to filter by. Pass the CURRENT BRANCH when set.'),
|
||||
}),
|
||||
execute: async ({ branch }) => {
|
||||
const doctors = await widgetSvc.getDoctors();
|
||||
const filtered = doctors.filter((d: any) => matchesBranch(d, branch));
|
||||
const deps = Array.from(
|
||||
new Set(filtered.map((d: any) => d.department).filter(Boolean)),
|
||||
) as string[];
|
||||
return {
|
||||
branch: branch ?? null,
|
||||
departments: deps.map(d => d.replace(/_/g, ' ')),
|
||||
};
|
||||
},
|
||||
}),
|
||||
show_clinic_timings: tool({
|
||||
description:
|
||||
'Show the clinic hours / visiting times for all departments with the doctors who visit during those hours. Use when the visitor asks about clinic timings, visiting hours, when the clinic is open, or what time a department is available. Pass branch if CURRENT BRANCH is set.',
|
||||
inputSchema: z.object({
|
||||
branch: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe('Branch name to filter by. Pass the CURRENT BRANCH when set.'),
|
||||
}),
|
||||
execute: async ({ branch }) => {
|
||||
const doctors = await widgetSvc.getDoctors();
|
||||
const filtered = doctors.filter((d: any) => matchesBranch(d, branch));
|
||||
const byDept = new Map<
|
||||
string,
|
||||
Array<{ name: string; hours: string; clinic: string | null }>
|
||||
>();
|
||||
for (const d of filtered) {
|
||||
const dept = (d.department ?? 'Other').replace(/_/g, ' ');
|
||||
if (!byDept.has(dept)) byDept.set(dept, []);
|
||||
if (d.visitingHours) {
|
||||
byDept.get(dept)!.push({
|
||||
name: d.name,
|
||||
hours: d.visitingHours,
|
||||
clinic: d.clinic?.clinicName ?? null,
|
||||
});
|
||||
}
|
||||
}
|
||||
return {
|
||||
branch: branch ?? null,
|
||||
departments: Array.from(byDept.entries())
|
||||
.filter(([, entries]) => entries.length > 0)
|
||||
.map(([name, entries]) => ({ name, entries })),
|
||||
};
|
||||
},
|
||||
}),
|
||||
show_doctors: tool({
|
||||
description:
|
||||
'Show the list of doctors in a specific department with their visiting hours and clinic. Use when the visitor asks about doctors in a department. Pass branch if CURRENT BRANCH is set.',
|
||||
inputSchema: z.object({
|
||||
department: z
|
||||
.string()
|
||||
.describe('Department name, e.g., "Cardiology", "ENT", "General Medicine".'),
|
||||
branch: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe('Branch name to filter by. Pass the CURRENT BRANCH when set.'),
|
||||
}),
|
||||
execute: async ({ department, branch }) => {
|
||||
const doctors = await widgetSvc.getDoctors();
|
||||
const deptKey = department.toLowerCase().replace(/\s+/g, '').replace(/_/g, '');
|
||||
const matches = doctors
|
||||
.filter((d: any) => {
|
||||
const key = String(d.department ?? '')
|
||||
.toLowerCase()
|
||||
.replace(/\s+/g, '')
|
||||
.replace(/_/g, '');
|
||||
return key.includes(deptKey) && matchesBranch(d, branch);
|
||||
})
|
||||
.map((d: any) => ({
|
||||
id: d.id,
|
||||
name: d.name,
|
||||
specialty: d.specialty ?? null,
|
||||
visitingHours: d.visitingHours ?? null,
|
||||
clinic: d.clinic?.clinicName ?? null,
|
||||
}));
|
||||
return { department, branch: branch ?? null, doctors: matches };
|
||||
},
|
||||
}),
|
||||
show_doctor_slots: tool({
|
||||
description:
|
||||
"Show today's available appointment slots for a specific doctor. Use when the visitor wants to see when a doctor is free or wants to book with a specific doctor. The date is always today — do NOT try to specify a date. Pass branch if CURRENT BRANCH is set to disambiguate doctors with the same name across branches.",
|
||||
inputSchema: z.object({
|
||||
doctorName: z
|
||||
.string()
|
||||
.describe('Full name of the doctor, e.g., "Dr. Lakshmi Reddy".'),
|
||||
branch: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe('Branch name to disambiguate. Pass the CURRENT BRANCH when set.'),
|
||||
}),
|
||||
execute: async ({ doctorName, branch }) => {
|
||||
// Always use the server's current date. Never trust anything from
|
||||
// the model here — older LLMs hallucinate their training-data
|
||||
// "today" and return slots for the wrong day.
|
||||
const targetDate = new Date().toISOString().slice(0, 10);
|
||||
const doctors = await widgetSvc.getDoctors();
|
||||
const scoped = doctors.filter((d: any) => matchesBranch(d, branch));
|
||||
// Fuzzy match: lowercase + strip "Dr." prefix + collapse spaces.
|
||||
const norm = (s: string) =>
|
||||
s.toLowerCase().replace(/^dr\.?\s*/i, '').replace(/\s+/g, ' ').trim();
|
||||
const target = norm(doctorName);
|
||||
const doc =
|
||||
scoped.find((d: any) => norm(d.name) === target) ??
|
||||
scoped.find((d: any) => norm(d.name).includes(target)) ??
|
||||
scoped.find((d: any) => target.includes(norm(d.name)));
|
||||
if (!doc) {
|
||||
return {
|
||||
doctor: null,
|
||||
date: targetDate,
|
||||
slots: [],
|
||||
error: `No doctor matching "${doctorName}"${branch ? ` at ${branch}` : ''} was found.`,
|
||||
};
|
||||
}
|
||||
const slots = await widgetSvc.getSlots(doc.id, targetDate);
|
||||
return {
|
||||
doctor: {
|
||||
id: doc.id,
|
||||
name: doc.name,
|
||||
department: doc.department ?? null,
|
||||
clinic: doc.clinic?.clinicName ?? null,
|
||||
},
|
||||
date: targetDate,
|
||||
slots,
|
||||
};
|
||||
},
|
||||
}),
|
||||
suggest_booking: tool({
|
||||
description:
|
||||
'Suggest that the visitor book an appointment. Use when the conversation is trending toward booking, the user has identified a concern, or asks "how do I book".',
|
||||
inputSchema: z.object({
|
||||
reason: z.string().describe('Short reason why booking is a good next step.'),
|
||||
department: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe('Suggested department, if known.'),
|
||||
}),
|
||||
execute: async ({ reason, department }) => {
|
||||
return { reason, department: department ?? null };
|
||||
},
|
||||
}),
|
||||
};
|
||||
|
||||
// Bookings / leads are not in scope for the AI — we only wire read/
|
||||
// suggest tools here. The CC agent/AP engineering team can book.
|
||||
void platform;
|
||||
|
||||
const result = streamText({
|
||||
model: aiModel,
|
||||
system: systemPrompt,
|
||||
messages,
|
||||
tools,
|
||||
stopWhen: stepCountIs(4),
|
||||
});
|
||||
|
||||
const uiStream = result.toUIMessageStream();
|
||||
for await (const chunk of uiStream) {
|
||||
yield chunk;
|
||||
}
|
||||
}
|
||||
}
|
||||
25
src/widget/widget-key.guard.ts
Normal file
25
src/widget/widget-key.guard.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
import { CanActivate, ExecutionContext, Injectable, HttpException } from '@nestjs/common';
|
||||
import { WidgetKeysService } from '../config/widget-keys.service';
|
||||
|
||||
@Injectable()
|
||||
export class WidgetKeyGuard implements CanActivate {
|
||||
constructor(private readonly keys: WidgetKeysService) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest();
|
||||
const key = request.query?.key ?? request.headers['x-widget-key'];
|
||||
|
||||
if (!key) throw new HttpException('Widget key required', 401);
|
||||
|
||||
const siteKey = await this.keys.validateKey(key);
|
||||
if (!siteKey) throw new HttpException('Invalid widget key', 403);
|
||||
|
||||
const origin = request.headers.origin ?? request.headers.referer;
|
||||
if (!this.keys.validateOrigin(siteKey, origin)) {
|
||||
throw new HttpException('Origin not allowed', 403);
|
||||
}
|
||||
|
||||
request.widgetSiteKey = siteKey;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
172
src/widget/widget.controller.ts
Normal file
172
src/widget/widget.controller.ts
Normal file
@@ -0,0 +1,172 @@
|
||||
import { Controller, Get, Post, Delete, Body, Query, Param, Req, Res, UseGuards, Logger, HttpException } from '@nestjs/common';
|
||||
import type { Request, Response } from 'express';
|
||||
import type { ModelMessage } from 'ai';
|
||||
import { WidgetService } from './widget.service';
|
||||
import { WidgetChatService } from './widget-chat.service';
|
||||
import { WidgetKeysService } from '../config/widget-keys.service';
|
||||
import { WidgetKeyGuard } from './widget-key.guard';
|
||||
import { CaptchaGuard } from './captcha.guard';
|
||||
import type { WidgetBookRequest, WidgetLeadRequest } from './widget.types';
|
||||
|
||||
type ChatStartBody = { name?: string; phone?: string };
|
||||
type ChatStreamBody = { leadId?: string; messages?: ModelMessage[]; branch?: string | null };
|
||||
|
||||
@Controller('api/widget')
|
||||
export class WidgetController {
|
||||
private readonly logger = new Logger(WidgetController.name);
|
||||
|
||||
constructor(
|
||||
private readonly widget: WidgetService,
|
||||
private readonly chat: WidgetChatService,
|
||||
private readonly keys: WidgetKeysService,
|
||||
) {}
|
||||
|
||||
@Get('init')
|
||||
@UseGuards(WidgetKeyGuard)
|
||||
init() {
|
||||
return this.widget.getInitData();
|
||||
}
|
||||
|
||||
@Get('doctors')
|
||||
@UseGuards(WidgetKeyGuard)
|
||||
async doctors() {
|
||||
return this.widget.getDoctors();
|
||||
}
|
||||
|
||||
@Get('slots')
|
||||
@UseGuards(WidgetKeyGuard)
|
||||
async slots(@Query('doctorId') doctorId: string, @Query('date') date: string) {
|
||||
if (!doctorId || !date) throw new HttpException('doctorId and date required', 400);
|
||||
return this.widget.getSlots(doctorId, date);
|
||||
}
|
||||
|
||||
@Post('book')
|
||||
@UseGuards(WidgetKeyGuard, CaptchaGuard)
|
||||
async book(@Body() body: WidgetBookRequest) {
|
||||
if (!body.patientName || !body.patientPhone || !body.doctorId || !body.scheduledAt) {
|
||||
throw new HttpException('patientName, patientPhone, doctorId, and scheduledAt required', 400);
|
||||
}
|
||||
return this.widget.bookAppointment(body);
|
||||
}
|
||||
|
||||
@Post('lead')
|
||||
@UseGuards(WidgetKeyGuard, CaptchaGuard)
|
||||
async lead(@Body() body: WidgetLeadRequest) {
|
||||
if (!body.name || !body.phone) {
|
||||
throw new HttpException('name and phone required', 400);
|
||||
}
|
||||
return this.widget.createLead(body);
|
||||
}
|
||||
|
||||
// Start (or resume) a chat session. Dedups by phone in the last 24h so a
|
||||
// single visitor who books + contacts + chats doesn't create three leads.
|
||||
// No CaptchaGuard: the window-level gate already verified humanity, and
|
||||
// Turnstile tokens are single-use so reusing them on every endpoint breaks
|
||||
// the multi-action flow.
|
||||
@Post('chat-start')
|
||||
@UseGuards(WidgetKeyGuard)
|
||||
async chatStart(@Body() body: ChatStartBody) {
|
||||
if (!body.name?.trim() || !body.phone?.trim()) {
|
||||
throw new HttpException('name and phone required', 400);
|
||||
}
|
||||
try {
|
||||
const leadId = await this.chat.findOrCreateLead(body.name.trim(), body.phone.trim());
|
||||
return { leadId };
|
||||
} catch (err: any) {
|
||||
this.logger.error(`chatStart failed: ${err?.message ?? err}`);
|
||||
throw new HttpException('Failed to start chat session', 500);
|
||||
}
|
||||
}
|
||||
|
||||
// Stream the AI reply. Requires an active leadId from chat-start. The
|
||||
// conversation is logged to leadActivity after the stream completes so the
|
||||
// CC agent can review the transcript when they call the visitor back.
|
||||
@Post('chat')
|
||||
@UseGuards(WidgetKeyGuard)
|
||||
async chat_(@Req() req: Request, @Res() res: Response) {
|
||||
const body = req.body as ChatStreamBody;
|
||||
const leadId = body?.leadId?.trim();
|
||||
const messages = body?.messages ?? [];
|
||||
const selectedBranch = body?.branch?.trim() || null;
|
||||
if (!leadId) {
|
||||
res.status(400).json({ error: 'leadId required' });
|
||||
return;
|
||||
}
|
||||
if (!messages.length) {
|
||||
res.status(400).json({ error: 'messages required' });
|
||||
return;
|
||||
}
|
||||
if (!this.chat.hasAiModel()) {
|
||||
res.status(503).json({ error: 'AI not configured' });
|
||||
return;
|
||||
}
|
||||
|
||||
// Find the last user message up-front so we can log it after the
|
||||
// stream finishes (reverse-walking messages is cheap).
|
||||
const lastUser = [...messages].reverse().find(m => m.role === 'user');
|
||||
const userText = typeof lastUser?.content === 'string'
|
||||
? lastUser.content
|
||||
: '';
|
||||
|
||||
// Fetch the visitor's first name from the lead so the AI can personalize.
|
||||
const userName = await this.chat.getLeadFirstName(leadId);
|
||||
|
||||
// SSE framing — each UIMessageChunk is serialized as a `data:` event.
|
||||
// See AI SDK v6 UI_MESSAGE_STREAM_HEADERS for the canonical values.
|
||||
res.setHeader('Content-Type', 'text/event-stream; charset=utf-8');
|
||||
res.setHeader('Cache-Control', 'no-cache, no-transform');
|
||||
res.setHeader('Connection', 'keep-alive');
|
||||
res.setHeader('X-Accel-Buffering', 'no');
|
||||
res.setHeader('X-Vercel-Ai-Ui-Message-Stream', 'v1');
|
||||
|
||||
let aiText = '';
|
||||
try {
|
||||
const systemPrompt = await this.chat.buildSystemPrompt(userName, selectedBranch);
|
||||
for await (const chunk of this.chat.streamReply(systemPrompt, messages)) {
|
||||
// Track accumulated text for transcript logging.
|
||||
if (chunk?.type === 'text-delta' && typeof chunk.delta === 'string') {
|
||||
aiText += chunk.delta;
|
||||
}
|
||||
res.write(`data: ${JSON.stringify(chunk)}\n\n`);
|
||||
}
|
||||
res.write('data: [DONE]\n\n');
|
||||
res.end();
|
||||
} catch (err: any) {
|
||||
this.logger.error(`Chat stream failed for lead ${leadId}: ${err?.message ?? err}`);
|
||||
if (!res.headersSent) {
|
||||
res.status(500).json({ error: 'Chat failed' });
|
||||
} else {
|
||||
res.write(`data: ${JSON.stringify({ type: 'error', errorText: 'Chat failed' })}\n\n`);
|
||||
res.end();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Fire-and-forget transcript logging. We intentionally do not await
|
||||
// this so the stream response is not delayed.
|
||||
if (userText && aiText) {
|
||||
void this.chat.logExchange(leadId, userText, aiText);
|
||||
}
|
||||
}
|
||||
|
||||
// Key management (admin endpoints)
|
||||
@Post('keys/generate')
|
||||
async generateKey(@Body() body: { hospitalName: string; allowedOrigins: string[] }) {
|
||||
if (!body.hospitalName) throw new HttpException('hospitalName required', 400);
|
||||
const { key, siteKey } = this.keys.generateKey(body.hospitalName, body.allowedOrigins ?? []);
|
||||
await this.keys.saveKey(siteKey);
|
||||
return { key, siteKey };
|
||||
}
|
||||
|
||||
@Get('keys')
|
||||
async listKeys() {
|
||||
return this.keys.listKeys();
|
||||
}
|
||||
|
||||
@Delete('keys/:siteId')
|
||||
async revokeKey(@Param('siteId') siteId: string) {
|
||||
const revoked = await this.keys.revokeKey(siteId);
|
||||
if (!revoked) throw new HttpException('Key not found', 404);
|
||||
return { status: 'revoked' };
|
||||
}
|
||||
}
|
||||
18
src/widget/widget.module.ts
Normal file
18
src/widget/widget.module.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { WidgetController } from './widget.controller';
|
||||
import { WebhooksController } from './webhooks.controller';
|
||||
import { WidgetService } from './widget.service';
|
||||
import { WidgetChatService } from './widget-chat.service';
|
||||
import { PlatformModule } from '../platform/platform.module';
|
||||
import { AuthModule } from '../auth/auth.module';
|
||||
import { ConfigThemeModule } from '../config/config-theme.module';
|
||||
|
||||
// WidgetKeysService lives in ConfigThemeModule now — injected here via the
|
||||
// module's exports. This module only owns the widget-facing API endpoints
|
||||
// (init / chat / book / lead) plus the NestJS guards that consume the keys.
|
||||
@Module({
|
||||
imports: [PlatformModule, AuthModule, ConfigThemeModule],
|
||||
controllers: [WidgetController, WebhooksController],
|
||||
providers: [WidgetService, WidgetChatService],
|
||||
})
|
||||
export class WidgetModule {}
|
||||
246
src/widget/widget.service.ts
Normal file
246
src/widget/widget.service.ts
Normal file
@@ -0,0 +1,246 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { PlatformGraphqlService } from '../platform/platform-graphql.service';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import type { WidgetInitResponse, WidgetBookRequest, WidgetLeadRequest } from './widget.types';
|
||||
import { ThemeService } from '../config/theme.service';
|
||||
import { DOCTOR_VISIT_SLOTS_FRAGMENT, normalizeDoctors, type NormalizedDoctor } from '../shared/doctor-utils';
|
||||
|
||||
// Dedup window: any lead created for this phone within the last 24h is
|
||||
// considered the same visitor's lead — chat + book + contact by the same
|
||||
// phone all roll into one record in the CRM.
|
||||
const LEAD_DEDUP_WINDOW_MS = 24 * 60 * 60 * 1000;
|
||||
|
||||
export type FindOrCreateLeadOpts = {
|
||||
source?: string;
|
||||
status?: string;
|
||||
interestedService?: string;
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class WidgetService {
|
||||
private readonly logger = new Logger(WidgetService.name);
|
||||
private readonly apiKey: string;
|
||||
|
||||
constructor(
|
||||
private platform: PlatformGraphqlService,
|
||||
private theme: ThemeService,
|
||||
private config: ConfigService,
|
||||
) {
|
||||
this.apiKey = config.get<string>('platform.apiKey') ?? '';
|
||||
}
|
||||
|
||||
private get auth() {
|
||||
return `Bearer ${this.apiKey}`;
|
||||
}
|
||||
|
||||
private normalizePhone(raw: string): string {
|
||||
return raw.replace(/[^0-9]/g, '').slice(-10);
|
||||
}
|
||||
|
||||
// Shared lead dedup: finds a lead created in the last 24h for the same
|
||||
// phone, or creates a new one. Public so WidgetChatService can reuse it.
|
||||
async findOrCreateLeadByPhone(
|
||||
name: string,
|
||||
rawPhone: string,
|
||||
opts: FindOrCreateLeadOpts = {},
|
||||
): Promise<string> {
|
||||
const phone = this.normalizePhone(rawPhone);
|
||||
if (!phone) throw new Error('Invalid phone number');
|
||||
|
||||
const since = new Date(Date.now() - LEAD_DEDUP_WINDOW_MS).toISOString();
|
||||
|
||||
try {
|
||||
const existing = await this.platform.queryWithAuth<any>(
|
||||
`query($phone: String!, $since: DateTime!) {
|
||||
leads(
|
||||
first: 1,
|
||||
filter: {
|
||||
contactPhone: { primaryPhoneNumber: { like: $phone } },
|
||||
createdAt: { gte: $since }
|
||||
},
|
||||
orderBy: [{ createdAt: DescNullsLast }]
|
||||
) { edges { node { id createdAt } } }
|
||||
}`,
|
||||
{ phone: `%${phone}`, since },
|
||||
this.auth,
|
||||
);
|
||||
const match = existing?.leads?.edges?.[0]?.node;
|
||||
if (match?.id) {
|
||||
this.logger.log(`Lead dedup: reusing ${match.id} for phone ${phone}`);
|
||||
return match.id as string;
|
||||
}
|
||||
} catch (err) {
|
||||
this.logger.warn(`Lead dedup lookup failed, falling through to create: ${err}`);
|
||||
}
|
||||
|
||||
const firstName = name.split(' ')[0] || name;
|
||||
const lastName = name.split(' ').slice(1).join(' ') || '';
|
||||
|
||||
const created = await this.platform.queryWithAuth<any>(
|
||||
`mutation($data: LeadCreateInput!) { createLead(data: $data) { id } }`,
|
||||
{
|
||||
data: {
|
||||
name,
|
||||
contactName: { firstName, lastName },
|
||||
contactPhone: { primaryPhoneNumber: `+91${phone}` },
|
||||
source: opts.source ?? 'WEBSITE',
|
||||
status: opts.status ?? 'NEW',
|
||||
interestedService: opts.interestedService ?? 'Website Enquiry',
|
||||
},
|
||||
},
|
||||
this.auth,
|
||||
);
|
||||
const id = created?.createLead?.id;
|
||||
if (!id) throw new Error('Lead creation returned no id');
|
||||
this.logger.log(`Lead dedup: created ${id} for ${name} (${phone})`);
|
||||
return id as string;
|
||||
}
|
||||
|
||||
// Upgrade a lead's status — used when an existing lead is promoted from
|
||||
// NEW/chat to APPOINTMENT_SET after the visitor books. Non-fatal on failure.
|
||||
async updateLeadStatus(leadId: string, status: string, interestedService?: string): Promise<void> {
|
||||
try {
|
||||
await this.platform.queryWithAuth<any>(
|
||||
`mutation($id: UUID!, $data: LeadUpdateInput!) {
|
||||
updateLead(id: $id, data: $data) { id }
|
||||
}`,
|
||||
{
|
||||
id: leadId,
|
||||
data: {
|
||||
status,
|
||||
...(interestedService ? { interestedService } : {}),
|
||||
},
|
||||
},
|
||||
this.auth,
|
||||
);
|
||||
} catch (err) {
|
||||
this.logger.warn(`Failed to update lead ${leadId} status → ${status}: ${err}`);
|
||||
}
|
||||
}
|
||||
|
||||
getInitData(): WidgetInitResponse {
|
||||
const t = this.theme.getTheme();
|
||||
return {
|
||||
brand: { name: t.brand.hospitalName, logo: t.brand.logo },
|
||||
colors: {
|
||||
primary: t.colors.brand['600'] ?? 'rgb(29 78 216)',
|
||||
primaryLight: t.colors.brand['50'] ?? 'rgb(219 234 254)',
|
||||
text: t.colors.brand['950'] ?? 'rgb(15 23 42)',
|
||||
textLight: t.colors.brand['400'] ?? 'rgb(100 116 139)',
|
||||
},
|
||||
captchaSiteKey: process.env.RECAPTCHA_SITE_KEY ?? '',
|
||||
};
|
||||
}
|
||||
|
||||
// Returns NormalizedDoctor[] — the raw GraphQL fields plus three
|
||||
// derived bridge fields (`clinics`, `clinic`, `visitingHours`)
|
||||
// built from the visit-slots reverse relation. See
|
||||
// shared/doctor-utils.ts for the rationale and the format of the
|
||||
// visiting-hours summary string.
|
||||
async getDoctors(): Promise<NormalizedDoctor[]> {
|
||||
const data = await this.platform.queryWithAuth<any>(
|
||||
`{ doctors(first: 50) { edges { node {
|
||||
id name fullName { firstName lastName } department specialty
|
||||
consultationFeeNew { amountMicros currencyCode }
|
||||
${DOCTOR_VISIT_SLOTS_FRAGMENT}
|
||||
} } } }`,
|
||||
undefined, this.auth,
|
||||
);
|
||||
const raws = data.doctors.edges.map((e: any) => e.node);
|
||||
return normalizeDoctors(raws);
|
||||
}
|
||||
|
||||
async getSlots(doctorId: string, date: string): Promise<any> {
|
||||
const data = await this.platform.queryWithAuth<any>(
|
||||
`{ appointments(first: 50, filter: { doctorId: { eq: "${doctorId}" }, scheduledAt: { gte: "${date}T00:00:00Z", lte: "${date}T23:59:59Z" } }) { edges { node { scheduledAt } } } }`,
|
||||
undefined, this.auth,
|
||||
);
|
||||
const booked = data.appointments.edges.map((e: any) => {
|
||||
const dt = new Date(e.node.scheduledAt);
|
||||
return `${dt.getHours().toString().padStart(2, '0')}:${dt.getMinutes().toString().padStart(2, '0')}`;
|
||||
});
|
||||
|
||||
const allSlots = ['09:00', '09:30', '10:00', '10:30', '11:00', '11:30', '14:00', '14:30', '15:00', '15:30', '16:00'];
|
||||
return allSlots.map(s => ({ time: s, available: !booked.includes(s) }));
|
||||
}
|
||||
|
||||
async bookAppointment(req: WidgetBookRequest): Promise<{ appointmentId: string; reference: string }> {
|
||||
const phone = this.normalizePhone(req.patientPhone);
|
||||
|
||||
// Find or create patient
|
||||
let patientId: string | null = null;
|
||||
try {
|
||||
const existing = await this.platform.queryWithAuth<any>(
|
||||
`{ patients(first: 1, filter: { phones: { primaryPhoneNumber: { like: "%${phone}" } } }) { edges { node { id } } } }`,
|
||||
undefined, this.auth,
|
||||
);
|
||||
patientId = existing.patients.edges[0]?.node?.id ?? null;
|
||||
} catch { /* continue */ }
|
||||
|
||||
if (!patientId) {
|
||||
const firstName = req.patientName.split(' ')[0];
|
||||
const lastName = req.patientName.split(' ').slice(1).join(' ') || '';
|
||||
const created = await this.platform.queryWithAuth<any>(
|
||||
`mutation($data: PatientCreateInput!) { createPatient(data: $data) { id } }`,
|
||||
{ data: {
|
||||
fullName: { firstName, lastName },
|
||||
phones: { primaryPhoneNumber: `+91${phone}` },
|
||||
patientType: 'NEW',
|
||||
} },
|
||||
this.auth,
|
||||
);
|
||||
patientId = created.createPatient.id;
|
||||
}
|
||||
|
||||
// Create appointment
|
||||
const appt = await this.platform.queryWithAuth<any>(
|
||||
`mutation($data: AppointmentCreateInput!) { createAppointment(data: $data) { id } }`,
|
||||
{ data: {
|
||||
scheduledAt: req.scheduledAt,
|
||||
durationMin: 30,
|
||||
appointmentType: 'CONSULTATION',
|
||||
status: 'SCHEDULED',
|
||||
doctorId: req.doctorId,
|
||||
department: req.departmentId,
|
||||
reasonForVisit: req.chiefComplaint ?? '',
|
||||
patientId,
|
||||
} },
|
||||
this.auth,
|
||||
);
|
||||
|
||||
// Find-or-create lead (dedups within 24h across chat + contact + book)
|
||||
// and upgrade its status to APPOINTMENT_SET. Non-fatal on failure —
|
||||
// we don't want to fail the booking if lead bookkeeping hiccups.
|
||||
try {
|
||||
const leadId = await this.findOrCreateLeadByPhone(req.patientName, phone, {
|
||||
source: 'WEBSITE',
|
||||
status: 'APPOINTMENT_SET',
|
||||
interestedService: req.chiefComplaint ?? 'Appointment Booking',
|
||||
});
|
||||
// Idempotent upgrade: if the lead was reused from an earlier chat/
|
||||
// contact, promote its status and reflect the new interest.
|
||||
await this.updateLeadStatus(
|
||||
leadId,
|
||||
'APPOINTMENT_SET',
|
||||
req.chiefComplaint ?? 'Appointment Booking',
|
||||
);
|
||||
} catch (err) {
|
||||
this.logger.warn(`Widget lead upsert failed during booking: ${err}`);
|
||||
}
|
||||
|
||||
const reference = appt.createAppointment.id.substring(0, 8).toUpperCase();
|
||||
this.logger.log(`Widget booking: ${req.patientName} → ${req.doctorId} at ${req.scheduledAt} (ref: ${reference})`);
|
||||
|
||||
return { appointmentId: appt.createAppointment.id, reference };
|
||||
}
|
||||
|
||||
async createLead(req: WidgetLeadRequest): Promise<{ leadId: string }> {
|
||||
const leadId = await this.findOrCreateLeadByPhone(req.name, req.phone, {
|
||||
source: 'WEBSITE',
|
||||
status: 'NEW',
|
||||
interestedService: req.interest ?? 'Website Enquiry',
|
||||
});
|
||||
this.logger.log(`Widget contact: ${req.name} (${this.normalizePhone(req.phone)}) — ${req.interest ?? 'general'}`);
|
||||
return { leadId };
|
||||
}
|
||||
}
|
||||
38
src/widget/widget.types.ts
Normal file
38
src/widget/widget.types.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
export type WidgetSiteKey = {
|
||||
siteId: string;
|
||||
hospitalName: string;
|
||||
allowedOrigins: string[];
|
||||
active: boolean;
|
||||
createdAt: string;
|
||||
};
|
||||
|
||||
export type WidgetInitResponse = {
|
||||
brand: { name: string; logo: string };
|
||||
colors: { primary: string; primaryLight: string; text: string; textLight: string };
|
||||
captchaSiteKey: string;
|
||||
};
|
||||
|
||||
export type WidgetBookRequest = {
|
||||
departmentId: string;
|
||||
doctorId: string;
|
||||
scheduledAt: string;
|
||||
patientName: string;
|
||||
patientPhone: string;
|
||||
age?: string;
|
||||
gender?: string;
|
||||
chiefComplaint?: string;
|
||||
captchaToken: string;
|
||||
};
|
||||
|
||||
export type WidgetLeadRequest = {
|
||||
name: string;
|
||||
phone: string;
|
||||
interest?: string;
|
||||
message?: string;
|
||||
captchaToken: string;
|
||||
};
|
||||
|
||||
export type WidgetChatRequest = {
|
||||
messages: Array<{ role: string; content: string }>;
|
||||
captchaToken?: string;
|
||||
};
|
||||
@@ -53,9 +53,17 @@ export class MissedCallWebhookController {
|
||||
return { received: true, processed: false };
|
||||
}
|
||||
|
||||
// Skip outbound calls — an unanswered outbound dial is NOT a
|
||||
// "missed call" in the call-center sense. Outbound call records
|
||||
// are created by the disposition flow, not the webhook.
|
||||
if (type === 'Manual' || type === 'OutBound') {
|
||||
this.logger.log(`Skipping outbound call webhook (type=${type}, status=${status})`);
|
||||
return { received: true, processed: false, reason: 'outbound' };
|
||||
}
|
||||
|
||||
// Determine call status for our platform
|
||||
const callStatus = status === 'Answered' ? 'COMPLETED' : 'MISSED';
|
||||
const direction = type === 'InBound' ? 'INBOUND' : 'OUTBOUND';
|
||||
const direction = 'INBOUND'; // only inbound reaches here now
|
||||
|
||||
// Use API key auth for server-to-server writes
|
||||
const authHeader = this.apiKey ? `Bearer ${this.apiKey}` : '';
|
||||
@@ -147,8 +155,8 @@ export class MissedCallWebhookController {
|
||||
};
|
||||
// Set callback tracking fields for missed calls so they appear in the worklist
|
||||
if (data.callStatus === 'MISSED') {
|
||||
callData.callbackstatus = 'PENDING_CALLBACK';
|
||||
callData.missedcallcount = 1;
|
||||
callData.callbackStatus = 'PENDING_CALLBACK';
|
||||
callData.missedCallCount = 1;
|
||||
}
|
||||
if (data.recordingUrl) {
|
||||
callData.recording = { primaryLinkUrl: data.recordingUrl, primaryLinkLabel: 'Recording' };
|
||||
|
||||
193
src/worklist/missed-call-webhook.spec.ts
Normal file
193
src/worklist/missed-call-webhook.spec.ts
Normal file
@@ -0,0 +1,193 @@
|
||||
/**
|
||||
* Missed Call Webhook — unit tests
|
||||
*
|
||||
* QA coverage: TC-MC-01, TC-MC-02, TC-MC-03
|
||||
*
|
||||
* Tests verify that Ozonetel webhook payloads are correctly parsed and
|
||||
* transformed into platform Call records via GraphQL mutations. The
|
||||
* platform GraphQL client is mocked — no real HTTP or database calls.
|
||||
*/
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { MissedCallWebhookController } from './missed-call-webhook.controller';
|
||||
import { PlatformGraphqlService } from '../platform/platform-graphql.service';
|
||||
import {
|
||||
WEBHOOK_INBOUND_ANSWERED,
|
||||
WEBHOOK_INBOUND_MISSED,
|
||||
WEBHOOK_OUTBOUND_ANSWERED,
|
||||
WEBHOOK_OUTBOUND_NO_ANSWER,
|
||||
} from '../__fixtures__/ozonetel-payloads';
|
||||
|
||||
describe('MissedCallWebhookController', () => {
|
||||
let controller: MissedCallWebhookController;
|
||||
let platformGql: jest.Mocked<PlatformGraphqlService>;
|
||||
|
||||
beforeEach(async () => {
|
||||
const mockPlatformGql = {
|
||||
query: jest.fn().mockResolvedValue({}),
|
||||
queryWithAuth: jest.fn().mockImplementation((query: string) => {
|
||||
// createCall → return an id
|
||||
if (query.includes('createCall')) return Promise.resolve({ createCall: { id: 'test-call-id' } });
|
||||
// leads query → return empty (no matching lead)
|
||||
if (query.includes('leads')) return Promise.resolve({ leads: { edges: [] } });
|
||||
// createLeadActivity → return id
|
||||
if (query.includes('createLeadActivity')) return Promise.resolve({ createLeadActivity: { id: 'test-activity-id' } });
|
||||
// updateCall → return id
|
||||
if (query.includes('updateCall')) return Promise.resolve({ updateCall: { id: 'test-call-id' } });
|
||||
// updateLead → return id
|
||||
if (query.includes('updateLead')) return Promise.resolve({ updateLead: { id: 'test-lead-id' } });
|
||||
return Promise.resolve({});
|
||||
}),
|
||||
};
|
||||
|
||||
const mockConfig = {
|
||||
get: jest.fn((key: string) => {
|
||||
if (key === 'platform.apiKey') return 'test-api-key';
|
||||
if (key === 'platform.graphqlUrl') return 'http://localhost:4000/graphql';
|
||||
return undefined;
|
||||
}),
|
||||
};
|
||||
|
||||
const module = await Test.createTestingModule({
|
||||
controllers: [MissedCallWebhookController],
|
||||
providers: [
|
||||
{ provide: PlatformGraphqlService, useValue: mockPlatformGql },
|
||||
{ provide: ConfigService, useValue: mockConfig },
|
||||
],
|
||||
}).compile();
|
||||
|
||||
controller = module.get(MissedCallWebhookController);
|
||||
platformGql = module.get(PlatformGraphqlService);
|
||||
});
|
||||
|
||||
// ── TC-MC-01: Inbound missed call logged ─────────────────────
|
||||
|
||||
it('TC-MC-01: should create a MISSED INBOUND call record from webhook', async () => {
|
||||
const result = await controller.handleCallWebhook(WEBHOOK_INBOUND_MISSED);
|
||||
|
||||
expect(result).toEqual(expect.objectContaining({ received: true, processed: true }));
|
||||
expect(platformGql.queryWithAuth).toHaveBeenCalled();
|
||||
|
||||
const mutationCall = platformGql.queryWithAuth.mock.calls.find(
|
||||
(c) => typeof c[0] === 'string' && c[0].includes('createCall'),
|
||||
);
|
||||
expect(mutationCall).toBeDefined();
|
||||
|
||||
// Verify the mutation variables contain correct mapped values
|
||||
const variables = mutationCall![1];
|
||||
expect(variables).toMatchObject({
|
||||
data: expect.objectContaining({
|
||||
callStatus: 'MISSED',
|
||||
direction: 'INBOUND',
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
// ── TC-MC-02: Outbound unanswered call logged ────────────────
|
||||
|
||||
it('TC-MC-02: outbound unanswered call — skipped if no CallerID (by design)', async () => {
|
||||
// Ozonetel outbound webhooks have empty CallerID — the controller
|
||||
// skips processing when CallerID is blank. This is correct behavior:
|
||||
// outbound calls are tracked via the CDR polling, not the webhook.
|
||||
const result = await controller.handleCallWebhook(WEBHOOK_OUTBOUND_NO_ANSWER);
|
||||
expect(result).toEqual({ received: true, processed: false });
|
||||
});
|
||||
|
||||
// ── Inbound answered call logged correctly ───────────────────
|
||||
|
||||
it('should create a COMPLETED INBOUND call record', async () => {
|
||||
const result = await controller.handleCallWebhook(WEBHOOK_INBOUND_ANSWERED);
|
||||
|
||||
expect(result).toEqual(expect.objectContaining({ received: true, processed: true }));
|
||||
|
||||
const mutationCall = platformGql.queryWithAuth.mock.calls.find(
|
||||
(c) => typeof c[0] === 'string' && c[0].includes('createCall'),
|
||||
);
|
||||
expect(mutationCall).toBeDefined();
|
||||
|
||||
const variables = mutationCall![1];
|
||||
expect(variables).toMatchObject({
|
||||
data: expect.objectContaining({
|
||||
callStatus: 'COMPLETED',
|
||||
direction: 'INBOUND',
|
||||
agentName: 'global',
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
// ── Outbound answered call logged correctly ──────────────────
|
||||
|
||||
it('should skip outbound answered webhook with empty CallerID', async () => {
|
||||
// Same as TC-MC-02: outbound calls have no CallerID in the webhook
|
||||
const result = await controller.handleCallWebhook(WEBHOOK_OUTBOUND_ANSWERED);
|
||||
expect(result).toEqual({ received: true, processed: false });
|
||||
});
|
||||
|
||||
// ── Duration parsing ─────────────────────────────────────────
|
||||
|
||||
it('should parse Ozonetel HH:MM:SS duration to seconds', async () => {
|
||||
await controller.handleCallWebhook(WEBHOOK_INBOUND_ANSWERED);
|
||||
|
||||
const mutationCall = platformGql.queryWithAuth.mock.calls.find(
|
||||
(c) => typeof c[0] === 'string' && c[0].includes('createCall'),
|
||||
);
|
||||
const data = mutationCall![1]?.data;
|
||||
// "00:04:00" → 240 seconds
|
||||
expect(data?.durationSec).toBe(240);
|
||||
});
|
||||
|
||||
// ── CallerID stripping (+91 prefix) ──────────────────────────
|
||||
|
||||
it('should strip +91 prefix from CallerID', async () => {
|
||||
const payload = { ...WEBHOOK_INBOUND_ANSWERED, CallerID: '+919949879837' };
|
||||
await controller.handleCallWebhook(payload);
|
||||
|
||||
const mutationCall = platformGql.queryWithAuth.mock.calls.find(
|
||||
(c) => typeof c[0] === 'string' && c[0].includes('createCall'),
|
||||
);
|
||||
const data = mutationCall![1]?.data;
|
||||
// Controller adds +91 prefix when storing
|
||||
expect(data?.callerNumber?.primaryPhoneNumber).toBe('+919949879837');
|
||||
});
|
||||
|
||||
// ── Empty CallerID skipped ───────────────────────────────────
|
||||
|
||||
it('should skip processing if no CallerID in webhook', async () => {
|
||||
const payload = { ...WEBHOOK_INBOUND_MISSED, CallerID: '' };
|
||||
const result = await controller.handleCallWebhook(payload);
|
||||
|
||||
expect(result).toEqual({ received: true, processed: false });
|
||||
});
|
||||
|
||||
// ── IST → UTC timestamp conversion ───────────────────────────
|
||||
|
||||
it('should convert IST timestamps to UTC (subtract 5:30)', async () => {
|
||||
await controller.handleCallWebhook(WEBHOOK_INBOUND_ANSWERED);
|
||||
|
||||
const mutationCall = platformGql.queryWithAuth.mock.calls.find(
|
||||
(c) => typeof c[0] === 'string' && c[0].includes('createCall'),
|
||||
);
|
||||
const data = mutationCall![1]?.data;
|
||||
|
||||
// The istToUtc function subtracts 5:30 from the parsed date.
|
||||
// Input: "2026-04-09 14:30:00" (treated as local by Date constructor,
|
||||
// then shifted by -330 min). Verify the output is an ISO string
|
||||
// that's 5:30 earlier than what Date would parse natively.
|
||||
expect(data?.startedAt).toBeDefined();
|
||||
expect(typeof data?.startedAt).toBe('string');
|
||||
// Just verify it's a valid ISO timestamp (the exact hour depends
|
||||
// on how the test machine's TZ interacts with the naive parse)
|
||||
expect(new Date(data.startedAt).toISOString()).toBe(data.startedAt);
|
||||
});
|
||||
|
||||
// ── Handles JSON-string-wrapped body (Ozonetel quirk) ────────
|
||||
|
||||
it('should handle payload wrapped in a "data" JSON string', async () => {
|
||||
const wrappedPayload = {
|
||||
data: JSON.stringify(WEBHOOK_INBOUND_MISSED),
|
||||
};
|
||||
const result = await controller.handleCallWebhook(wrappedPayload);
|
||||
|
||||
expect(result).toEqual(expect.objectContaining({ received: true, processed: true }));
|
||||
});
|
||||
});
|
||||
@@ -2,6 +2,7 @@ import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { PlatformGraphqlService } from '../platform/platform-graphql.service';
|
||||
import { OzonetelAgentService } from '../ozonetel/ozonetel-agent.service';
|
||||
import { TelephonyConfigService } from '../config/telephony-config.service';
|
||||
|
||||
// Ozonetel sends all timestamps in IST — convert to UTC for storage
|
||||
export function istToUtc(istDateStr: string | null): string | null {
|
||||
@@ -33,10 +34,16 @@ export class MissedQueueService implements OnModuleInit {
|
||||
private readonly config: ConfigService,
|
||||
private readonly platform: PlatformGraphqlService,
|
||||
private readonly ozonetel: OzonetelAgentService,
|
||||
private readonly telephony: TelephonyConfigService,
|
||||
) {
|
||||
this.pollIntervalMs = this.config.get<number>('missedQueue.pollIntervalMs', 30000);
|
||||
}
|
||||
|
||||
// Read-through so admin config changes take effect without restart
|
||||
private get ownCampaign(): string {
|
||||
return this.telephony.getConfig().ozonetel.campaignName ?? '';
|
||||
}
|
||||
|
||||
onModuleInit() {
|
||||
this.logger.log(`Starting missed call ingestion polling every ${this.pollIntervalMs}ms`);
|
||||
setInterval(() => this.ingest().catch(err => this.logger.error('Ingestion failed', err)), this.pollIntervalMs);
|
||||
@@ -61,7 +68,17 @@ export class MissedQueueService implements OnModuleInit {
|
||||
|
||||
if (!abandonCalls?.length) return { created: 0, updated: 0 };
|
||||
|
||||
for (const call of abandonCalls) {
|
||||
// Filter to this sidecar's campaign only — the Ozonetel API
|
||||
// returns ALL abandoned calls across the account.
|
||||
const filtered = this.ownCampaign
|
||||
? abandonCalls.filter((c: any) => c.campaign === this.ownCampaign)
|
||||
: abandonCalls;
|
||||
|
||||
if (filtered.length < abandonCalls.length) {
|
||||
this.logger.log(`Filtered ${abandonCalls.length - filtered.length} calls from other campaigns (own=${this.ownCampaign})`);
|
||||
}
|
||||
|
||||
for (const call of filtered) {
|
||||
const ucid = call.monitorUCID;
|
||||
if (!ucid || this.processedUcids.has(ucid)) continue;
|
||||
this.processedUcids.add(ucid);
|
||||
@@ -97,19 +114,19 @@ export class MissedQueueService implements OnModuleInit {
|
||||
|
||||
const existing = await this.platform.query<any>(
|
||||
`{ calls(first: 1, filter: {
|
||||
callbackstatus: { eq: PENDING_CALLBACK },
|
||||
callbackStatus: { eq: PENDING_CALLBACK },
|
||||
callerNumber: { primaryPhoneNumber: { eq: "${phone}" } }
|
||||
}) { edges { node { id missedcallcount } } } }`,
|
||||
}) { edges { node { id missedCallCount } } } }`,
|
||||
);
|
||||
|
||||
const existingNode = existing?.calls?.edges?.[0]?.node;
|
||||
|
||||
if (existingNode) {
|
||||
const newCount = (existingNode.missedcallcount || 1) + 1;
|
||||
const newCount = (existingNode.missedCallCount || 1) + 1;
|
||||
const updateParts = [
|
||||
`missedcallcount: ${newCount}`,
|
||||
`missedCallCount: ${newCount}`,
|
||||
`startedAt: "${callTime}"`,
|
||||
`callsourcenumber: "${did}"`,
|
||||
`callSourceNumber: "${did}"`,
|
||||
];
|
||||
if (leadId) updateParts.push(`leadId: "${leadId}"`);
|
||||
if (leadName) updateParts.push(`leadName: "${leadName}"`);
|
||||
@@ -123,9 +140,9 @@ export class MissedQueueService implements OnModuleInit {
|
||||
`callStatus: MISSED`,
|
||||
`direction: INBOUND`,
|
||||
`callerNumber: { primaryPhoneNumber: "${phone}", primaryPhoneCallingCode: "+91" }`,
|
||||
`callsourcenumber: "${did}"`,
|
||||
`callbackstatus: PENDING_CALLBACK`,
|
||||
`missedcallcount: 1`,
|
||||
`callSourceNumber: "${did}"`,
|
||||
`callbackStatus: PENDING_CALLBACK`,
|
||||
`missedCallCount: 1`,
|
||||
`startedAt: "${callTime}"`,
|
||||
];
|
||||
if (leadId) dataParts.push(`leadId: "${leadId}"`);
|
||||
@@ -160,12 +177,12 @@ export class MissedQueueService implements OnModuleInit {
|
||||
// Find oldest unassigned PENDING_CALLBACK call (empty agentName)
|
||||
let result = await this.platform.query<any>(
|
||||
`{ calls(first: 1, filter: {
|
||||
callbackstatus: { eq: PENDING_CALLBACK },
|
||||
callbackStatus: { eq: PENDING_CALLBACK },
|
||||
agentName: { eq: "" }
|
||||
}, orderBy: [{ startedAt: AscNullsLast }]) {
|
||||
edges { node {
|
||||
id callerNumber { primaryPhoneNumber }
|
||||
startedAt callsourcenumber missedcallcount
|
||||
startedAt callSourceNumber missedCallCount
|
||||
} }
|
||||
} }`,
|
||||
);
|
||||
@@ -176,12 +193,12 @@ export class MissedQueueService implements OnModuleInit {
|
||||
if (!call) {
|
||||
result = await this.platform.query<any>(
|
||||
`{ calls(first: 1, filter: {
|
||||
callbackstatus: { eq: PENDING_CALLBACK },
|
||||
callbackStatus: { eq: PENDING_CALLBACK },
|
||||
agentName: { is: NULL }
|
||||
}, orderBy: [{ startedAt: AscNullsLast }]) {
|
||||
edges { node {
|
||||
id callerNumber { primaryPhoneNumber }
|
||||
startedAt callsourcenumber missedcallcount
|
||||
startedAt callSourceNumber missedCallCount
|
||||
} }
|
||||
} }`,
|
||||
);
|
||||
@@ -209,13 +226,13 @@ export class MissedQueueService implements OnModuleInit {
|
||||
throw new Error(`Invalid status: ${status}. Must be one of: ${validStatuses.join(', ')}`);
|
||||
}
|
||||
|
||||
const dataParts: string[] = [`callbackstatus: ${status}`];
|
||||
const dataParts: string[] = [`callbackStatus: ${status}`];
|
||||
if (status === 'CALLBACK_ATTEMPTED') {
|
||||
dataParts.push(`callbackattemptedat: "${new Date().toISOString()}"`);
|
||||
dataParts.push(`callbackAttemptedAt: "${new Date().toISOString()}"`);
|
||||
}
|
||||
|
||||
return this.platform.queryWithAuth<any>(
|
||||
`mutation { updateCall(id: "${callId}", data: { ${dataParts.join(', ')} }) { id callbackstatus callbackattemptedat } }`,
|
||||
`mutation { updateCall(id: "${callId}", data: { ${dataParts.join(', ')} }) { id callbackStatus callbackAttemptedAt } }`,
|
||||
undefined,
|
||||
authHeader,
|
||||
);
|
||||
@@ -230,12 +247,12 @@ export class MissedQueueService implements OnModuleInit {
|
||||
const fields = `id name createdAt direction callStatus agentName
|
||||
callerNumber { primaryPhoneNumber }
|
||||
startedAt endedAt durationSec disposition leadId
|
||||
callbackstatus callsourcenumber missedcallcount callbackattemptedat`;
|
||||
callbackStatus callSourceNumber missedCallCount callbackAttemptedAt`;
|
||||
|
||||
const buildQuery = (status: string) => `{ calls(first: 50, filter: {
|
||||
agentName: { eq: "${agentName}" },
|
||||
callStatus: { eq: MISSED },
|
||||
callbackstatus: { eq: ${status} }
|
||||
callbackStatus: { eq: ${status} }
|
||||
}, orderBy: [{ startedAt: AscNullsLast }]) { edges { node { ${fields} } } } }`;
|
||||
|
||||
try {
|
||||
|
||||
178
src/worklist/missed-queue.spec.ts
Normal file
178
src/worklist/missed-queue.spec.ts
Normal file
@@ -0,0 +1,178 @@
|
||||
/**
|
||||
* Missed Queue Service — unit tests
|
||||
*
|
||||
* QA coverage: TC-MC-03 (missed calls appear in pending section)
|
||||
*
|
||||
* Tests the abandon call polling + ingestion logic:
|
||||
* - Fetches from Ozonetel getAbandonCalls
|
||||
* - Deduplicates by UCID
|
||||
* - Creates Call records with callbackstatus=PENDING_CALLBACK
|
||||
* - Normalizes phone numbers
|
||||
* - Converts IST→UTC timestamps
|
||||
*/
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { MissedQueueService, istToUtc, normalizePhone } from './missed-queue.service';
|
||||
import { PlatformGraphqlService } from '../platform/platform-graphql.service';
|
||||
import { OzonetelAgentService } from '../ozonetel/ozonetel-agent.service';
|
||||
import { TelephonyConfigService } from '../config/telephony-config.service';
|
||||
import { ABANDON_CALL_RECORD } from '../__fixtures__/ozonetel-payloads';
|
||||
|
||||
describe('MissedQueueService', () => {
|
||||
let service: MissedQueueService;
|
||||
let platform: jest.Mocked<PlatformGraphqlService>;
|
||||
let ozonetel: jest.Mocked<OzonetelAgentService>;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module = await Test.createTestingModule({
|
||||
providers: [
|
||||
MissedQueueService,
|
||||
{
|
||||
provide: ConfigService,
|
||||
useValue: {
|
||||
get: jest.fn((key: string, defaultVal?: any) => {
|
||||
if (key === 'missedQueue.pollIntervalMs') return 999999; // don't actually poll
|
||||
if (key === 'platform.apiKey') return 'test-key';
|
||||
return defaultVal;
|
||||
}),
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: PlatformGraphqlService,
|
||||
useValue: {
|
||||
query: jest.fn().mockResolvedValue({}),
|
||||
queryWithAuth: jest.fn().mockImplementation((query: string) => {
|
||||
if (query.includes('createCall')) {
|
||||
return Promise.resolve({ createCall: { id: 'call-missed-001' } });
|
||||
}
|
||||
if (query.includes('calls')) {
|
||||
return Promise.resolve({ calls: { edges: [] } }); // no existing calls
|
||||
}
|
||||
return Promise.resolve({});
|
||||
}),
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: OzonetelAgentService,
|
||||
useValue: {
|
||||
getAbandonCalls: jest.fn().mockResolvedValue([ABANDON_CALL_RECORD]),
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: TelephonyConfigService,
|
||||
useValue: {
|
||||
getConfig: () => ({
|
||||
ozonetel: { campaignName: 'Inbound_918041763400', agentId: '', agentPassword: '', did: '918041763400', sipId: '' },
|
||||
sip: { domain: 'test', wsPort: '444' },
|
||||
exotel: { apiKey: '', accountSid: '', subdomain: '' },
|
||||
}),
|
||||
},
|
||||
},
|
||||
],
|
||||
}).compile();
|
||||
|
||||
service = module.get(MissedQueueService);
|
||||
platform = module.get(PlatformGraphqlService);
|
||||
ozonetel = module.get(OzonetelAgentService);
|
||||
});
|
||||
|
||||
// ── Utility functions ────────────────────────────────────────
|
||||
|
||||
describe('istToUtc', () => {
|
||||
it('should subtract 5:30 from a valid IST timestamp', () => {
|
||||
const result = istToUtc('2026-04-09 14:30:00');
|
||||
expect(result).toBeDefined();
|
||||
const d = new Date(result!);
|
||||
expect(d.toISOString()).toBeTruthy();
|
||||
});
|
||||
|
||||
it('should return null for null input', () => {
|
||||
expect(istToUtc(null)).toBeNull();
|
||||
});
|
||||
|
||||
it('should return null for invalid date string', () => {
|
||||
expect(istToUtc('not-a-date')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('normalizePhone', () => {
|
||||
it('should strip +91 and format to +91XXXXXXXXXX', () => {
|
||||
expect(normalizePhone('+919949879837')).toBe('+919949879837');
|
||||
});
|
||||
|
||||
it('should strip 0091 prefix', () => {
|
||||
expect(normalizePhone('00919949879837')).toBe('+919949879837');
|
||||
});
|
||||
|
||||
it('should strip leading 0', () => {
|
||||
expect(normalizePhone('09949879837')).toBe('+919949879837');
|
||||
});
|
||||
|
||||
it('should handle raw 10-digit number', () => {
|
||||
expect(normalizePhone('9949879837')).toBe('+919949879837');
|
||||
});
|
||||
|
||||
it('should strip non-digits', () => {
|
||||
expect(normalizePhone('+91-994-987-9837')).toBe('+919949879837');
|
||||
});
|
||||
});
|
||||
|
||||
// ── Ingestion ────────────────────────────────────────────────
|
||||
|
||||
describe('ingest', () => {
|
||||
it('TC-MC-03: should create MISSED call with PENDING_CALLBACK status', async () => {
|
||||
const result = await service.ingest();
|
||||
|
||||
expect(result.created).toBeGreaterThanOrEqual(0);
|
||||
|
||||
// Verify createCall was called
|
||||
const createCalls = platform.queryWithAuth.mock.calls.filter(
|
||||
c => typeof c[0] === 'string' && c[0].includes('createCall'),
|
||||
);
|
||||
|
||||
if (createCalls.length > 0) {
|
||||
const data = createCalls[0][1]?.data;
|
||||
expect(data).toMatchObject(
|
||||
expect.objectContaining({
|
||||
callStatus: 'MISSED',
|
||||
direction: 'INBOUND',
|
||||
callbackstatus: 'PENDING_CALLBACK',
|
||||
}),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it('should deduplicate by UCID on second ingest', async () => {
|
||||
await service.ingest();
|
||||
const firstCallCount = platform.queryWithAuth.mock.calls.filter(
|
||||
c => typeof c[0] === 'string' && c[0].includes('createCall'),
|
||||
).length;
|
||||
|
||||
// Same UCID on second ingest
|
||||
await service.ingest();
|
||||
const secondCallCount = platform.queryWithAuth.mock.calls.filter(
|
||||
c => typeof c[0] === 'string' && c[0].includes('createCall'),
|
||||
).length;
|
||||
|
||||
// Should not create duplicate — count stays the same
|
||||
expect(secondCallCount).toBe(firstCallCount);
|
||||
});
|
||||
|
||||
it('should handle empty abandon list gracefully', async () => {
|
||||
ozonetel.getAbandonCalls.mockResolvedValueOnce([]);
|
||||
|
||||
const result = await service.ingest();
|
||||
|
||||
expect(result.created).toBe(0);
|
||||
expect(result.updated).toBe(0);
|
||||
});
|
||||
|
||||
it('should handle Ozonetel API failure gracefully', async () => {
|
||||
ozonetel.getAbandonCalls.mockRejectedValueOnce(new Error('API timeout'));
|
||||
|
||||
const result = await service.ingest();
|
||||
|
||||
expect(result.created).toBe(0);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -3,6 +3,7 @@ import { PlatformModule } from '../platform/platform.module';
|
||||
import { OzonetelAgentModule } from '../ozonetel/ozonetel-agent.module';
|
||||
import { AuthModule } from '../auth/auth.module';
|
||||
import { RulesEngineModule } from '../rules-engine/rules-engine.module';
|
||||
import { TelephonyConfigService } from '../config/telephony-config.service';
|
||||
import { WorklistController } from './worklist.controller';
|
||||
import { WorklistService } from './worklist.service';
|
||||
import { MissedQueueService } from './missed-queue.service';
|
||||
@@ -12,7 +13,7 @@ import { KookooCallbackController } from './kookoo-callback.controller';
|
||||
@Module({
|
||||
imports: [PlatformModule, forwardRef(() => OzonetelAgentModule), forwardRef(() => AuthModule), RulesEngineModule],
|
||||
controllers: [WorklistController, MissedCallWebhookController, KookooCallbackController],
|
||||
providers: [WorklistService, MissedQueueService],
|
||||
providers: [WorklistService, MissedQueueService, TelephonyConfigService],
|
||||
exports: [MissedQueueService],
|
||||
})
|
||||
export class WorklistModule {}
|
||||
|
||||
@@ -97,13 +97,13 @@ export class WorklistService {
|
||||
try {
|
||||
// FIFO ordering (AscNullsLast) — oldest first. No agentName filter — missed calls are a shared queue.
|
||||
const data = await this.platform.queryWithAuth<any>(
|
||||
`{ calls(first: 20, filter: { callStatus: { eq: MISSED }, callbackstatus: { in: [PENDING_CALLBACK, CALLBACK_ATTEMPTED] } }, orderBy: [{ startedAt: AscNullsLast }]) { edges { node {
|
||||
`{ calls(first: 20, filter: { callStatus: { eq: MISSED }, callbackStatus: { in: [PENDING_CALLBACK, CALLBACK_ATTEMPTED] } }, orderBy: [{ startedAt: AscNullsLast }]) { edges { node {
|
||||
id name createdAt
|
||||
direction callStatus agentName
|
||||
callerNumber { primaryPhoneNumber }
|
||||
startedAt endedAt durationSec
|
||||
disposition leadId
|
||||
callbackstatus callsourcenumber missedcallcount callbackattemptedat
|
||||
callbackStatus callSourceNumber missedCallCount callbackAttemptedAt
|
||||
} } } }`,
|
||||
undefined,
|
||||
authHeader,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
|
||||
"exclude": ["node_modules", "test", "dist", "widget-src", "public", "data", "**/*spec.ts"]
|
||||
}
|
||||
|
||||
@@ -21,5 +21,6 @@
|
||||
"noImplicitAny": true,
|
||||
"strictBindCallApply": true,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
}
|
||||
},
|
||||
"exclude": ["widget-src", "public", "data"]
|
||||
}
|
||||
|
||||
1
widget-src/.gitignore
vendored
Normal file
1
widget-src/.gitignore
vendored
Normal file
@@ -0,0 +1 @@
|
||||
node_modules
|
||||
2070
widget-src/package-lock.json
generated
Normal file
2070
widget-src/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
18
widget-src/package.json
Normal file
18
widget-src/package.json
Normal file
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"name": "helix-engage-widget",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"preact": "^10.25.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@preact/preset-vite": "^2.9.0",
|
||||
"typescript": "^5.7.0",
|
||||
"vite": "^6.0.0"
|
||||
}
|
||||
}
|
||||
75
widget-src/src/api.ts
Normal file
75
widget-src/src/api.ts
Normal file
@@ -0,0 +1,75 @@
|
||||
import type { WidgetConfig, Doctor, TimeSlot } from './types';
|
||||
|
||||
let baseUrl = '';
|
||||
let widgetKey = '';
|
||||
|
||||
export const initApi = (url: string, key: string) => {
|
||||
baseUrl = url;
|
||||
widgetKey = key;
|
||||
};
|
||||
|
||||
const headers = () => ({
|
||||
'Content-Type': 'application/json',
|
||||
'X-Widget-Key': widgetKey,
|
||||
});
|
||||
|
||||
export const fetchInit = async (): Promise<WidgetConfig> => {
|
||||
const res = await fetch(`${baseUrl}/api/widget/init?key=${widgetKey}`);
|
||||
if (!res.ok) throw new Error('Widget init failed');
|
||||
return res.json();
|
||||
};
|
||||
|
||||
export const fetchDoctors = async (): Promise<Doctor[]> => {
|
||||
const res = await fetch(`${baseUrl}/api/widget/doctors?key=${widgetKey}`);
|
||||
if (!res.ok) throw new Error('Failed to load doctors');
|
||||
return res.json();
|
||||
};
|
||||
|
||||
export const fetchSlots = async (doctorId: string, date: string): Promise<TimeSlot[]> => {
|
||||
const res = await fetch(`${baseUrl}/api/widget/slots?key=${widgetKey}&doctorId=${doctorId}&date=${date}`);
|
||||
if (!res.ok) throw new Error('Failed to load slots');
|
||||
return res.json();
|
||||
};
|
||||
|
||||
export const submitBooking = async (data: any): Promise<{ appointmentId: string; reference: string }> => {
|
||||
const res = await fetch(`${baseUrl}/api/widget/book?key=${widgetKey}`, {
|
||||
method: 'POST', headers: headers(), body: JSON.stringify(data),
|
||||
});
|
||||
if (!res.ok) throw new Error('Booking failed');
|
||||
return res.json();
|
||||
};
|
||||
|
||||
export const submitLead = async (data: any): Promise<{ leadId: string }> => {
|
||||
const res = await fetch(`${baseUrl}/api/widget/lead?key=${widgetKey}`, {
|
||||
method: 'POST', headers: headers(), body: JSON.stringify(data),
|
||||
});
|
||||
if (!res.ok) throw new Error('Submission failed');
|
||||
return res.json();
|
||||
};
|
||||
|
||||
export const startChatSession = async (name: string, phone: string): Promise<{ leadId: string }> => {
|
||||
const res = await fetch(`${baseUrl}/api/widget/chat-start?key=${widgetKey}`, {
|
||||
method: 'POST', headers: headers(),
|
||||
body: JSON.stringify({ name, phone }),
|
||||
});
|
||||
if (!res.ok) throw new Error('Chat start failed');
|
||||
return res.json();
|
||||
};
|
||||
|
||||
// Send the simplified {role, content: string}[] history to the backend.
|
||||
// Backend responds with an SSE stream of UIMessageChunk events.
|
||||
// branch (when set) is injected into the system prompt so the AI scopes
|
||||
// tool calls to that branch.
|
||||
type OutboundMessage = { role: 'user' | 'assistant'; content: string };
|
||||
export const streamChat = async (
|
||||
leadId: string,
|
||||
messages: OutboundMessage[],
|
||||
branch: string | null,
|
||||
): Promise<ReadableStream<Uint8Array>> => {
|
||||
const res = await fetch(`${baseUrl}/api/widget/chat?key=${widgetKey}`, {
|
||||
method: 'POST', headers: headers(),
|
||||
body: JSON.stringify({ leadId, messages, branch }),
|
||||
});
|
||||
if (!res.ok || !res.body) throw new Error('Chat failed');
|
||||
return res.body;
|
||||
};
|
||||
330
widget-src/src/booking.tsx
Normal file
330
widget-src/src/booking.tsx
Normal file
@@ -0,0 +1,330 @@
|
||||
import { useState, useEffect, useMemo } from 'preact/hooks';
|
||||
import { fetchSlots, submitBooking } from './api';
|
||||
import { departmentIcon } from './icons';
|
||||
import { IconSpan } from './icon-span';
|
||||
import { useWidgetStore } from './store';
|
||||
import type { Doctor, TimeSlot } from './types';
|
||||
|
||||
type Step = 'branch' | 'department' | 'doctor' | 'datetime' | 'details' | 'success';
|
||||
|
||||
export const Booking = () => {
|
||||
const {
|
||||
visitor,
|
||||
updateVisitor,
|
||||
captchaToken,
|
||||
bookingPrefill,
|
||||
setBookingPrefill,
|
||||
doctors,
|
||||
doctorsLoading,
|
||||
doctorsError,
|
||||
branches,
|
||||
selectedBranch,
|
||||
setSelectedBranch,
|
||||
} = useWidgetStore();
|
||||
|
||||
// Start on the branch step only if the visitor actually has a choice to
|
||||
// make. Single-branch hospitals and chat-prefilled sessions skip it.
|
||||
const needsBranchStep = branches.length > 1 && !selectedBranch;
|
||||
const [step, setStep] = useState<Step>(needsBranchStep ? 'branch' : 'department');
|
||||
const [selectedDept, setSelectedDept] = useState('');
|
||||
const [selectedDoctor, setSelectedDoctor] = useState<Doctor | null>(null);
|
||||
const [selectedDate, setSelectedDate] = useState('');
|
||||
const [slots, setSlots] = useState<TimeSlot[]>([]);
|
||||
const [selectedSlot, setSelectedSlot] = useState('');
|
||||
const [complaint, setComplaint] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [reference, setReference] = useState('');
|
||||
|
||||
// Scope the roster to the selected branch up front. Every downstream
|
||||
// derivation (departments list, doctor filter) works off this.
|
||||
const branchDoctors = useMemo(() => {
|
||||
if (!selectedBranch) return doctors;
|
||||
const needle = selectedBranch.toLowerCase();
|
||||
return doctors.filter(d =>
|
||||
String(d.clinic?.clinicName ?? '').toLowerCase().includes(needle),
|
||||
);
|
||||
}, [doctors, selectedBranch]);
|
||||
|
||||
// Derive department list from the branch-scoped roster.
|
||||
const departments = useMemo(
|
||||
() => [...new Set(branchDoctors.map(d => d.department).filter(Boolean))] as string[],
|
||||
[branchDoctors],
|
||||
);
|
||||
|
||||
const filteredDoctors = selectedDept
|
||||
? branchDoctors.filter(d => d.department === selectedDept)
|
||||
: [];
|
||||
|
||||
// Surface a doctors-load error if the roster failed to fetch.
|
||||
useEffect(() => {
|
||||
if (doctorsError) setError(doctorsError);
|
||||
}, [doctorsError]);
|
||||
|
||||
// Consume any booking prefill from chat → jump straight to the details form.
|
||||
// Also locks the branch to the picked doctor's clinic so the visitor sees
|
||||
// the right header badge when they land here.
|
||||
useEffect(() => {
|
||||
if (!bookingPrefill || doctors.length === 0) return;
|
||||
const doc = doctors.find(d => d.id === bookingPrefill.doctorId);
|
||||
if (!doc) return;
|
||||
if (doc.clinic?.clinicName && !selectedBranch) {
|
||||
setSelectedBranch(doc.clinic.clinicName);
|
||||
}
|
||||
setSelectedDept(doc.department);
|
||||
setSelectedDoctor(doc);
|
||||
setSelectedDate(bookingPrefill.date);
|
||||
setSelectedSlot(bookingPrefill.time);
|
||||
setStep('details');
|
||||
setBookingPrefill(null);
|
||||
}, [bookingPrefill, doctors]);
|
||||
|
||||
const handleDoctorSelect = (doc: Doctor) => {
|
||||
setSelectedDoctor(doc);
|
||||
setSelectedDate(new Date().toISOString().split('T')[0]);
|
||||
setStep('datetime');
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedDoctor && selectedDate) {
|
||||
fetchSlots(selectedDoctor.id, selectedDate).then(setSlots).catch(() => {});
|
||||
}
|
||||
}, [selectedDoctor, selectedDate]);
|
||||
|
||||
const handleBook = async () => {
|
||||
if (!selectedDoctor || !selectedSlot || !visitor.name.trim() || !visitor.phone.trim()) return;
|
||||
setLoading(true);
|
||||
setError('');
|
||||
try {
|
||||
const scheduledAt = `${selectedDate}T${selectedSlot}:00`;
|
||||
const result = await submitBooking({
|
||||
departmentId: selectedDept,
|
||||
doctorId: selectedDoctor.id,
|
||||
scheduledAt,
|
||||
patientName: visitor.name.trim(),
|
||||
patientPhone: visitor.phone.trim(),
|
||||
chiefComplaint: complaint,
|
||||
captchaToken,
|
||||
});
|
||||
setReference(result.reference);
|
||||
setStep('success');
|
||||
} catch {
|
||||
setError('Booking failed. Please try again.');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Progress bar step count is dynamic: 5 dots if we need the branch step,
|
||||
// 4 otherwise. The current position is derived from the flow we're in.
|
||||
const flowSteps: Step[] = needsBranchStep
|
||||
? ['branch', 'department', 'doctor', 'datetime', 'details']
|
||||
: ['department', 'doctor', 'datetime', 'details'];
|
||||
const currentStep = flowSteps.indexOf(step);
|
||||
|
||||
return (
|
||||
<div>
|
||||
{step !== 'success' && (
|
||||
<div class="widget-steps">
|
||||
{flowSteps.map((_, i) => (
|
||||
<div key={i} class={`widget-step ${i < currentStep ? 'done' : i === currentStep ? 'active' : ''}`} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && <div class="widget-error">{error}</div>}
|
||||
|
||||
{step === 'branch' && (
|
||||
<div>
|
||||
<div class="widget-section-title">Select Branch</div>
|
||||
{doctorsLoading && branches.length === 0 && (
|
||||
<div class="widget-section-sub">Loading…</div>
|
||||
)}
|
||||
{branches.map(branch => (
|
||||
<button
|
||||
key={branch}
|
||||
class="widget-row-btn"
|
||||
onClick={() => {
|
||||
setSelectedBranch(branch);
|
||||
setStep('department');
|
||||
}}
|
||||
>
|
||||
<IconSpan class="widget-row-icon" name="hospital" size={20} />
|
||||
<span class="widget-row-label">{branch}</span>
|
||||
<IconSpan class="widget-row-chevron" name="arrow-right" size={14} />
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === 'department' && (
|
||||
<div>
|
||||
<div class="widget-section-title">
|
||||
{selectedBranch && (
|
||||
<>
|
||||
<IconSpan class="widget-row-icon" name="hospital" size={16} />
|
||||
{selectedBranch} —
|
||||
</>
|
||||
)}
|
||||
Select Department
|
||||
</div>
|
||||
{doctorsLoading && departments.length === 0 && (
|
||||
<div class="widget-section-sub">Loading…</div>
|
||||
)}
|
||||
{departments.map(dept => (
|
||||
<button
|
||||
key={dept}
|
||||
class="widget-row-btn"
|
||||
onClick={() => { setSelectedDept(dept); setStep('doctor'); }}
|
||||
>
|
||||
<IconSpan class="widget-row-icon" name={departmentIcon(dept)} size={20} />
|
||||
<span class="widget-row-label">{dept.replace(/_/g, ' ')}</span>
|
||||
<IconSpan class="widget-row-chevron" name="arrow-right" size={14} />
|
||||
</button>
|
||||
))}
|
||||
{branches.length > 1 && (
|
||||
<button
|
||||
class="widget-btn widget-btn-secondary widget-btn-with-icon"
|
||||
style={{ marginTop: '8px' }}
|
||||
onClick={() => setStep('branch')}
|
||||
>
|
||||
<IconSpan name="arrow-left" size={14} />
|
||||
Change branch
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === 'doctor' && (
|
||||
<div>
|
||||
<div class="widget-section-title">
|
||||
<IconSpan class="widget-row-icon" name={departmentIcon(selectedDept)} size={16} />
|
||||
{selectedDept.replace(/_/g, ' ')}
|
||||
</div>
|
||||
{filteredDoctors.map(doc => (
|
||||
<button
|
||||
key={doc.id}
|
||||
class="widget-row-btn widget-row-btn-stack"
|
||||
onClick={() => handleDoctorSelect(doc)}
|
||||
>
|
||||
<div class="widget-row-main">
|
||||
<div class="widget-row-label">{doc.name}</div>
|
||||
<div class="widget-row-sub">
|
||||
{doc.visitingHours ?? ''} {doc.clinic?.clinicName ? `• ${doc.clinic.clinicName}` : ''}
|
||||
</div>
|
||||
</div>
|
||||
<IconSpan class="widget-row-chevron" name="arrow-right" size={14} />
|
||||
</button>
|
||||
))}
|
||||
<button class="widget-btn widget-btn-secondary widget-btn-with-icon" style={{ marginTop: '8px' }} onClick={() => setStep('department')}>
|
||||
<IconSpan name="arrow-left" size={14} />
|
||||
Back
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === 'datetime' && (
|
||||
<div>
|
||||
<div class="widget-section-title">{selectedDoctor?.name} — Pick Date & Time</div>
|
||||
<div class="widget-field">
|
||||
<label class="widget-label">Date</label>
|
||||
<input
|
||||
class="widget-input"
|
||||
type="date"
|
||||
value={selectedDate}
|
||||
min={new Date().toISOString().split('T')[0]}
|
||||
onInput={(e: any) => { setSelectedDate(e.target.value); setSelectedSlot(''); }}
|
||||
/>
|
||||
</div>
|
||||
{slots.length > 0 && (
|
||||
<div>
|
||||
<label class="widget-label">Available Slots</label>
|
||||
<div class="widget-slots">
|
||||
{slots.map(s => (
|
||||
<button
|
||||
key={s.time}
|
||||
class={`widget-slot ${s.time === selectedSlot ? 'selected' : ''} ${!s.available ? 'unavailable' : ''}`}
|
||||
onClick={() => s.available && setSelectedSlot(s.time)}
|
||||
disabled={!s.available}
|
||||
>
|
||||
{s.time}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div class="widget-btn-row">
|
||||
<button class="widget-btn widget-btn-secondary widget-btn-with-icon" onClick={() => setStep('doctor')}>
|
||||
<IconSpan name="arrow-left" size={14} />
|
||||
Back
|
||||
</button>
|
||||
<button class="widget-btn widget-btn-with-icon" disabled={!selectedSlot} onClick={() => setStep('details')}>
|
||||
Next
|
||||
<IconSpan name="arrow-right" size={14} color="#fff" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === 'details' && (
|
||||
<div>
|
||||
<div class="widget-section-title">Your Details</div>
|
||||
<div class="widget-field">
|
||||
<label class="widget-label">Full Name *</label>
|
||||
<input
|
||||
class="widget-input"
|
||||
placeholder="Your name"
|
||||
value={visitor.name}
|
||||
onInput={(e: any) => updateVisitor({ name: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<div class="widget-field">
|
||||
<label class="widget-label">Phone Number *</label>
|
||||
<input
|
||||
class="widget-input"
|
||||
placeholder="+91 9876543210"
|
||||
value={visitor.phone}
|
||||
onInput={(e: any) => updateVisitor({ phone: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<div class="widget-field">
|
||||
<label class="widget-label">Chief Complaint</label>
|
||||
<textarea
|
||||
class="widget-input widget-textarea"
|
||||
placeholder="Describe your concern..."
|
||||
value={complaint}
|
||||
onInput={(e: any) => setComplaint(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div class="widget-btn-row">
|
||||
<button class="widget-btn widget-btn-secondary widget-btn-with-icon" onClick={() => setStep('datetime')}>
|
||||
<IconSpan name="arrow-left" size={14} />
|
||||
Back
|
||||
</button>
|
||||
<button
|
||||
class="widget-btn"
|
||||
disabled={!visitor.name.trim() || !visitor.phone.trim() || loading}
|
||||
onClick={handleBook}
|
||||
>
|
||||
{loading ? 'Booking...' : 'Book Appointment'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === 'success' && (
|
||||
<div class="widget-success">
|
||||
<div class="widget-success-icon">
|
||||
<IconSpan name="circle-check" size={56} color="#059669" />
|
||||
</div>
|
||||
<div class="widget-success-title">Appointment Booked!</div>
|
||||
<div class="widget-success-text">
|
||||
Reference: <strong>{reference}</strong><br />
|
||||
{selectedDoctor?.name} • {selectedDate} at {selectedSlot}<br /><br />
|
||||
We'll send a confirmation SMS to your phone.
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
164
widget-src/src/captcha.tsx
Normal file
164
widget-src/src/captcha.tsx
Normal file
@@ -0,0 +1,164 @@
|
||||
import { useEffect, useRef, useState } from 'preact/hooks';
|
||||
|
||||
// Cloudflare Turnstile integration.
|
||||
//
|
||||
// Rendering strategy: Turnstile injects its layout stylesheet into document.head,
|
||||
// which does NOT cascade into our shadow DOM. When rendered inside our shadow DOM
|
||||
// the iframe exists with correct attributes but paints as zero pixels because the
|
||||
// wrapper Turnstile creates has no resolved styles. To work around this we mount
|
||||
// Turnstile into a portal div appended to document.body (light DOM), then use
|
||||
// getBoundingClientRect on the in-shadow placeholder to keep the portal visually
|
||||
// overlaid on top of the captcha gate area.
|
||||
|
||||
type TurnstileOptions = {
|
||||
sitekey: string;
|
||||
callback?: (token: string) => void;
|
||||
'error-callback'?: () => void;
|
||||
'expired-callback'?: () => void;
|
||||
theme?: 'light' | 'dark' | 'auto';
|
||||
size?: 'normal' | 'compact' | 'flexible' | 'invisible';
|
||||
appearance?: 'always' | 'execute' | 'interaction-only';
|
||||
};
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
turnstile?: {
|
||||
render: (container: HTMLElement, opts: TurnstileOptions) => string;
|
||||
remove: (widgetId: string) => void;
|
||||
reset: (widgetId?: string) => void;
|
||||
};
|
||||
__helixTurnstileLoading?: Promise<void>;
|
||||
}
|
||||
}
|
||||
|
||||
const SCRIPT_URL = 'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit';
|
||||
|
||||
export const loadTurnstile = (): Promise<void> => {
|
||||
if (typeof window === 'undefined') return Promise.resolve();
|
||||
if (window.turnstile) return Promise.resolve();
|
||||
if (window.__helixTurnstileLoading) return window.__helixTurnstileLoading;
|
||||
|
||||
window.__helixTurnstileLoading = new Promise<void>((resolve, reject) => {
|
||||
const script = document.createElement('script');
|
||||
script.src = SCRIPT_URL;
|
||||
script.async = true;
|
||||
script.defer = true;
|
||||
script.onload = () => {
|
||||
const poll = () => {
|
||||
if (window.turnstile) resolve();
|
||||
else setTimeout(poll, 50);
|
||||
};
|
||||
poll();
|
||||
};
|
||||
script.onerror = () => reject(new Error('Turnstile failed to load'));
|
||||
document.head.appendChild(script);
|
||||
});
|
||||
return window.__helixTurnstileLoading;
|
||||
};
|
||||
|
||||
type CaptchaProps = {
|
||||
siteKey: string;
|
||||
onToken: (token: string) => void;
|
||||
onError?: () => void;
|
||||
};
|
||||
|
||||
export const Captcha = ({ siteKey, onToken, onError }: CaptchaProps) => {
|
||||
const placeholderRef = useRef<HTMLDivElement | null>(null);
|
||||
const portalRef = useRef<HTMLDivElement | null>(null);
|
||||
const widgetIdRef = useRef<string | null>(null);
|
||||
const onTokenRef = useRef(onToken);
|
||||
const onErrorRef = useRef(onError);
|
||||
const [status, setStatus] = useState<'loading' | 'ready' | 'error'>('loading');
|
||||
|
||||
onTokenRef.current = onToken;
|
||||
onErrorRef.current = onError;
|
||||
|
||||
useEffect(() => {
|
||||
if (!siteKey || !placeholderRef.current) return;
|
||||
let cancelled = false;
|
||||
|
||||
// Light-DOM portal so Turnstile's document.head styles actually apply.
|
||||
const portal = document.createElement('div');
|
||||
portal.setAttribute('data-helix-turnstile', '');
|
||||
portal.style.cssText = [
|
||||
'position:fixed',
|
||||
'z-index:2147483647',
|
||||
'width:300px',
|
||||
'height:65px',
|
||||
'pointer-events:auto',
|
||||
].join(';');
|
||||
document.body.appendChild(portal);
|
||||
portalRef.current = portal;
|
||||
|
||||
const updatePosition = () => {
|
||||
if (!placeholderRef.current || !portalRef.current) return;
|
||||
const rect = placeholderRef.current.getBoundingClientRect();
|
||||
portalRef.current.style.top = `${rect.top}px`;
|
||||
portalRef.current.style.left = `${rect.left}px`;
|
||||
};
|
||||
|
||||
updatePosition();
|
||||
window.addEventListener('resize', updatePosition);
|
||||
window.addEventListener('scroll', updatePosition, true);
|
||||
|
||||
// Reposition on animation frame while the gate is mounted, so the portal
|
||||
// tracks the placeholder through panel open animation and any layout shifts.
|
||||
let rafId = 0;
|
||||
const trackLoop = () => {
|
||||
updatePosition();
|
||||
rafId = requestAnimationFrame(trackLoop);
|
||||
};
|
||||
rafId = requestAnimationFrame(trackLoop);
|
||||
|
||||
loadTurnstile()
|
||||
.then(() => {
|
||||
if (cancelled || !portalRef.current || !window.turnstile) return;
|
||||
try {
|
||||
widgetIdRef.current = window.turnstile.render(portalRef.current, {
|
||||
sitekey: siteKey,
|
||||
callback: (token) => onTokenRef.current(token),
|
||||
'error-callback': () => {
|
||||
setStatus('error');
|
||||
onErrorRef.current?.();
|
||||
},
|
||||
'expired-callback': () => onTokenRef.current(''),
|
||||
theme: 'light',
|
||||
size: 'normal',
|
||||
});
|
||||
setStatus('ready');
|
||||
} catch {
|
||||
setStatus('error');
|
||||
onErrorRef.current?.();
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
setStatus('error');
|
||||
onErrorRef.current?.();
|
||||
});
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
cancelAnimationFrame(rafId);
|
||||
window.removeEventListener('resize', updatePosition);
|
||||
window.removeEventListener('scroll', updatePosition, true);
|
||||
if (widgetIdRef.current && window.turnstile) {
|
||||
try {
|
||||
window.turnstile.remove(widgetIdRef.current);
|
||||
} catch {
|
||||
// ignore — widget may already be gone
|
||||
}
|
||||
widgetIdRef.current = null;
|
||||
}
|
||||
portal.remove();
|
||||
portalRef.current = null;
|
||||
};
|
||||
}, [siteKey]);
|
||||
|
||||
return (
|
||||
<div class="widget-captcha">
|
||||
<div class="widget-captcha-mount" ref={placeholderRef} />
|
||||
{status === 'loading' && <div class="widget-captcha-status">Loading verification…</div>}
|
||||
{status === 'error' && <div class="widget-captcha-status widget-captcha-error">Verification failed to load. Please refresh.</div>}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
61
widget-src/src/chat-stream.ts
Normal file
61
widget-src/src/chat-stream.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
// Minimal SSE + UIMessageChunk parser. The backend writes
|
||||
// data: ${JSON.stringify(chunk)}\n\n
|
||||
// for each AI SDK UIMessageChunk, plus a final `data: [DONE]\n\n`.
|
||||
// We reconstruct events by buffering stream text and splitting on blank lines.
|
||||
|
||||
export type UIMessageChunk =
|
||||
| { type: 'start'; messageId?: string }
|
||||
| { type: 'start-step' }
|
||||
| { type: 'finish-step' }
|
||||
| { type: 'finish' }
|
||||
| { type: 'error'; errorText: string }
|
||||
| { type: 'text-start'; id: string }
|
||||
| { type: 'text-delta'; id: string; delta: string }
|
||||
| { type: 'text-end'; id: string }
|
||||
| { type: 'tool-input-start'; toolCallId: string; toolName: string }
|
||||
| { type: 'tool-input-delta'; toolCallId: string; inputTextDelta: string }
|
||||
| { type: 'tool-input-available'; toolCallId: string; toolName: string; input: any }
|
||||
| { type: 'tool-output-available'; toolCallId: string; output: any }
|
||||
| { type: 'tool-output-error'; toolCallId: string; errorText: string }
|
||||
| { type: string; [key: string]: any };
|
||||
|
||||
// Reads the SSE body byte stream and yields UIMessageChunk objects.
|
||||
export async function* readChatStream(
|
||||
body: ReadableStream<Uint8Array>,
|
||||
): AsyncGenerator<UIMessageChunk> {
|
||||
const reader = body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let buffer = '';
|
||||
|
||||
try {
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
buffer += decoder.decode(value, { stream: true });
|
||||
|
||||
// Each SSE event is terminated by a blank line. Split off complete
|
||||
// events and keep the trailing partial in buffer.
|
||||
let sep: number;
|
||||
while ((sep = buffer.indexOf('\n\n')) !== -1) {
|
||||
const rawEvent = buffer.slice(0, sep);
|
||||
buffer = buffer.slice(sep + 2);
|
||||
|
||||
// Grab lines starting with "data:" (there may be comments or
|
||||
// event: lines too — we ignore them).
|
||||
const lines = rawEvent.split('\n');
|
||||
for (const line of lines) {
|
||||
if (!line.startsWith('data:')) continue;
|
||||
const payload = line.slice(5).trimStart();
|
||||
if (!payload || payload === '[DONE]') continue;
|
||||
try {
|
||||
yield JSON.parse(payload) as UIMessageChunk;
|
||||
} catch {
|
||||
// Bad JSON — skip this event rather than crash the stream.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
reader.releaseLock();
|
||||
}
|
||||
}
|
||||
274
widget-src/src/chat-widgets.tsx
Normal file
274
widget-src/src/chat-widgets.tsx
Normal file
@@ -0,0 +1,274 @@
|
||||
import { IconSpan } from './icon-span';
|
||||
import { departmentIcon } from './icons';
|
||||
import type { BookingPrefill, ChatToolPart, ToolOutputs } from './types';
|
||||
|
||||
type WidgetProps = {
|
||||
part: ChatToolPart;
|
||||
onDepartmentClick: (department: string) => void;
|
||||
onShowDoctorSlots: (doctorName: string) => void;
|
||||
onSuggestBooking: () => void;
|
||||
onPickSlot: (prefill: BookingPrefill) => void;
|
||||
onPickBranch: (branch: string) => void;
|
||||
};
|
||||
|
||||
// Dispatcher — renders the right widget for a tool part based on its name and state.
|
||||
export const ChatToolWidget = ({
|
||||
part,
|
||||
onDepartmentClick,
|
||||
onShowDoctorSlots,
|
||||
onSuggestBooking,
|
||||
onPickSlot,
|
||||
onPickBranch,
|
||||
}: WidgetProps) => {
|
||||
if (part.state === 'input-streaming' || part.state === 'input-available') {
|
||||
return <ToolLoadingRow toolName={part.toolName} />;
|
||||
}
|
||||
if (part.state === 'output-error') {
|
||||
return <div class="chat-widget-error">Couldn't load: {part.errorText ?? 'unknown error'}</div>;
|
||||
}
|
||||
|
||||
switch (part.toolName) {
|
||||
case 'pick_branch': {
|
||||
const out = part.output as ToolOutputs['pick_branch'] | undefined;
|
||||
if (!out?.branches?.length) return null;
|
||||
return <BranchPickerWidget branches={out.branches} onPick={onPickBranch} />;
|
||||
}
|
||||
case 'list_departments': {
|
||||
const out = part.output as ToolOutputs['list_departments'] | undefined;
|
||||
if (!out?.departments?.length) return null;
|
||||
return <DepartmentListWidget departments={out.departments} onPick={onDepartmentClick} />;
|
||||
}
|
||||
case 'show_clinic_timings': {
|
||||
const out = part.output as ToolOutputs['show_clinic_timings'] | undefined;
|
||||
if (!out?.departments?.length) return null;
|
||||
return <ClinicTimingsWidget departments={out.departments} />;
|
||||
}
|
||||
case 'show_doctors': {
|
||||
const out = part.output as ToolOutputs['show_doctors'] | undefined;
|
||||
if (!out?.doctors?.length) {
|
||||
return (
|
||||
<div class="chat-widget-empty">
|
||||
No doctors found in {out?.department ?? 'this department'}.
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<DoctorsListWidget
|
||||
department={out.department}
|
||||
doctors={out.doctors}
|
||||
onPickDoctor={onShowDoctorSlots}
|
||||
/>
|
||||
);
|
||||
}
|
||||
case 'show_doctor_slots': {
|
||||
const out = part.output as ToolOutputs['show_doctor_slots'] | undefined;
|
||||
if (!out) return null;
|
||||
if (out.error || !out.doctor) {
|
||||
return <div class="chat-widget-empty">{out.error ?? 'Doctor not found.'}</div>;
|
||||
}
|
||||
return <DoctorSlotsWidget data={out} onPickSlot={onPickSlot} />;
|
||||
}
|
||||
case 'suggest_booking': {
|
||||
const out = part.output as ToolOutputs['suggest_booking'] | undefined;
|
||||
return (
|
||||
<BookingSuggestionWidget
|
||||
reason={out?.reason ?? 'Book an appointment.'}
|
||||
department={out?.department ?? null}
|
||||
onBook={onSuggestBooking}
|
||||
/>
|
||||
);
|
||||
}
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const TOOL_LABELS: Record<string, string> = {
|
||||
pick_branch: 'Fetching branches…',
|
||||
list_departments: 'Looking up departments…',
|
||||
show_clinic_timings: 'Fetching clinic hours…',
|
||||
show_doctors: 'Looking up doctors…',
|
||||
show_doctor_slots: 'Checking availability…',
|
||||
suggest_booking: 'Thinking about booking options…',
|
||||
};
|
||||
|
||||
const ToolLoadingRow = ({ toolName }: { toolName: string }) => (
|
||||
<div class="chat-widget-loading">
|
||||
<span class="chat-typing-dots" aria-hidden="true">
|
||||
<span /><span /><span />
|
||||
</span>
|
||||
<span class="chat-widget-loading-label">{TOOL_LABELS[toolName] ?? 'Working…'}</span>
|
||||
</div>
|
||||
);
|
||||
|
||||
type BranchPickerProps = {
|
||||
branches: ToolOutputs['pick_branch']['branches'];
|
||||
onPick: (branch: string) => void;
|
||||
};
|
||||
|
||||
const BranchPickerWidget = ({ branches, onPick }: BranchPickerProps) => (
|
||||
<div class="chat-widget chat-widget-branches">
|
||||
<div class="chat-widget-title">Which branch?</div>
|
||||
{branches.map(b => (
|
||||
<button key={b.name} class="chat-widget-branch-card" onClick={() => onPick(b.name)}>
|
||||
<div class="chat-widget-branch-name">{b.name}</div>
|
||||
<div class="chat-widget-branch-meta">
|
||||
{b.doctorCount} {b.doctorCount === 1 ? 'doctor' : 'doctors'}
|
||||
{b.departmentCount > 0 ? ` • ${b.departmentCount} ${b.departmentCount === 1 ? 'department' : 'departments'}` : ''}
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
|
||||
type DepartmentListProps = {
|
||||
departments: string[];
|
||||
onPick: (department: string) => void;
|
||||
};
|
||||
|
||||
const DepartmentListWidget = ({ departments, onPick }: DepartmentListProps) => (
|
||||
<div class="chat-widget chat-widget-departments">
|
||||
<div class="chat-widget-title">Departments</div>
|
||||
<div class="chat-widget-dept-grid">
|
||||
{departments.map(dept => (
|
||||
<button
|
||||
key={dept}
|
||||
class="chat-widget-dept-chip"
|
||||
onClick={() => onPick(dept)}
|
||||
title={`Show doctors in ${dept}`}
|
||||
>
|
||||
<IconSpan name={departmentIcon(dept)} size={16} />
|
||||
<span>{dept}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
type ClinicTimingsProps = {
|
||||
departments: ToolOutputs['show_clinic_timings']['departments'];
|
||||
};
|
||||
|
||||
const ClinicTimingsWidget = ({ departments }: ClinicTimingsProps) => (
|
||||
<div class="chat-widget chat-widget-timings">
|
||||
<div class="chat-widget-title">
|
||||
<IconSpan name="calendar" size={14} /> Clinic hours
|
||||
</div>
|
||||
{departments.map(dept => (
|
||||
<div key={dept.name} class="chat-widget-timing-dept">
|
||||
<div class="chat-widget-timing-dept-name">
|
||||
<IconSpan name={departmentIcon(dept.name)} size={14} />
|
||||
<span>{dept.name}</span>
|
||||
</div>
|
||||
{dept.entries.map(entry => (
|
||||
<div key={`${dept.name}-${entry.name}`} class="chat-widget-timing-row">
|
||||
<div class="chat-widget-timing-doctor">{entry.name}</div>
|
||||
<div class="chat-widget-timing-hours">{entry.hours}</div>
|
||||
{entry.clinic && (
|
||||
<div class="chat-widget-timing-clinic">{entry.clinic}</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
|
||||
type DoctorsListProps = {
|
||||
department: string;
|
||||
doctors: ToolOutputs['show_doctors']['doctors'];
|
||||
onPickDoctor: (doctorName: string) => void;
|
||||
};
|
||||
|
||||
const DoctorsListWidget = ({ department, doctors, onPickDoctor }: DoctorsListProps) => (
|
||||
<div class="chat-widget chat-widget-doctors">
|
||||
<div class="chat-widget-title">
|
||||
<IconSpan name={departmentIcon(department)} size={14} /> {department}
|
||||
</div>
|
||||
{doctors.map(doc => (
|
||||
<div key={doc.id} class="chat-widget-doctor-card">
|
||||
<div class="chat-widget-doctor-name">{doc.name}</div>
|
||||
{doc.specialty && <div class="chat-widget-doctor-meta">{doc.specialty}</div>}
|
||||
{doc.visitingHours && <div class="chat-widget-doctor-meta">{doc.visitingHours}</div>}
|
||||
{doc.clinic && <div class="chat-widget-doctor-meta">{doc.clinic}</div>}
|
||||
<button
|
||||
class="chat-widget-doctor-action"
|
||||
onClick={() => onPickDoctor(doc.name)}
|
||||
>
|
||||
<IconSpan name="calendar" size={12} /> See available appointments
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
|
||||
type DoctorSlotsProps = {
|
||||
data: ToolOutputs['show_doctor_slots'];
|
||||
onPickSlot: (prefill: BookingPrefill) => void;
|
||||
};
|
||||
|
||||
const DoctorSlotsWidget = ({ data, onPickSlot }: DoctorSlotsProps) => {
|
||||
if (!data.doctor) return null;
|
||||
const doctor = data.doctor;
|
||||
const available = data.slots.filter(s => s.available);
|
||||
const hasAny = available.length > 0;
|
||||
|
||||
return (
|
||||
<div class="chat-widget chat-widget-slots">
|
||||
<div class="chat-widget-title">
|
||||
<IconSpan name="calendar" size={14} /> Available slots
|
||||
</div>
|
||||
<div class="chat-widget-slots-doctor">{doctor.name}</div>
|
||||
<div class="chat-widget-slots-meta">
|
||||
{formatDate(data.date)}
|
||||
{doctor.clinic ? ` • ${doctor.clinic}` : ''}
|
||||
</div>
|
||||
{hasAny ? (
|
||||
<div class="chat-widget-slots-grid">
|
||||
{data.slots.map(s => (
|
||||
<button
|
||||
key={s.time}
|
||||
class={`chat-widget-slot-btn ${s.available ? '' : 'unavailable'}`}
|
||||
disabled={!s.available}
|
||||
onClick={() =>
|
||||
s.available &&
|
||||
onPickSlot({ doctorId: doctor.id, date: data.date, time: s.time })
|
||||
}
|
||||
>
|
||||
{s.time}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div class="chat-widget-empty">No slots available on this date.</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const formatDate = (iso: string): string => {
|
||||
// iso is YYYY-MM-DD from the backend. Render as e.g. "Mon, 6 Apr".
|
||||
const d = new Date(iso + 'T00:00:00');
|
||||
if (isNaN(d.getTime())) return iso;
|
||||
return d.toLocaleDateString(undefined, { weekday: 'short', day: 'numeric', month: 'short' });
|
||||
};
|
||||
|
||||
type BookingSuggestionProps = {
|
||||
reason: string;
|
||||
department: string | null;
|
||||
onBook: () => void;
|
||||
};
|
||||
|
||||
const BookingSuggestionWidget = ({ reason, department, onBook }: BookingSuggestionProps) => (
|
||||
<div class="chat-widget chat-widget-booking">
|
||||
<div class="chat-widget-booking-icon">
|
||||
<IconSpan name="calendar" size={28} />
|
||||
</div>
|
||||
<div class="chat-widget-booking-body">
|
||||
<div class="chat-widget-booking-title">Book an appointment</div>
|
||||
<div class="chat-widget-booking-reason">{reason}</div>
|
||||
{department && <div class="chat-widget-booking-dept">Suggested: {department}</div>}
|
||||
<button class="widget-btn" onClick={onBook}>Book now</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
435
widget-src/src/chat.tsx
Normal file
435
widget-src/src/chat.tsx
Normal file
@@ -0,0 +1,435 @@
|
||||
import { useState, useRef, useEffect } from 'preact/hooks';
|
||||
import { startChatSession, streamChat } from './api';
|
||||
import { readChatStream } from './chat-stream';
|
||||
import { IconSpan } from './icon-span';
|
||||
import { ChatToolWidget } from './chat-widgets';
|
||||
import { useWidgetStore } from './store';
|
||||
import type {
|
||||
BookingPrefill,
|
||||
ChatMessage,
|
||||
ChatPart,
|
||||
ChatTextPart,
|
||||
ChatToolPart,
|
||||
} from './types';
|
||||
|
||||
const QUICK_ACTIONS = [
|
||||
'What departments do you have?',
|
||||
'Show me cardiologists',
|
||||
'Clinic timings',
|
||||
'How do I book?',
|
||||
];
|
||||
|
||||
type ChatProps = {
|
||||
// Switches the widget to the Book tab. Chat-level handler that lives in
|
||||
// the parent so slot picks can seed bookingPrefill + swap tabs atomically.
|
||||
onRequestBooking: (prefill?: BookingPrefill) => void;
|
||||
};
|
||||
|
||||
const textOf = (msg: ChatMessage): string =>
|
||||
msg.parts
|
||||
.filter((p): p is ChatTextPart => p.type === 'text')
|
||||
.map(p => p.text)
|
||||
.join('');
|
||||
|
||||
const updateMessage = (
|
||||
setMessages: (updater: (msgs: ChatMessage[]) => ChatMessage[]) => void,
|
||||
id: string,
|
||||
mutator: (msg: ChatMessage) => ChatMessage,
|
||||
) => {
|
||||
setMessages(prev => prev.map(m => (m.id === id ? mutator(m) : m)));
|
||||
};
|
||||
|
||||
const appendTextDelta = (parts: ChatPart[], delta: string, state: 'streaming' | 'done'): ChatPart[] => {
|
||||
const last = parts[parts.length - 1];
|
||||
if (last?.type === 'text') {
|
||||
return [...parts.slice(0, -1), { type: 'text', text: last.text + delta, state }];
|
||||
}
|
||||
return [...parts, { type: 'text', text: delta, state }];
|
||||
};
|
||||
|
||||
const upsertToolPart = (
|
||||
parts: ChatPart[],
|
||||
toolCallId: string,
|
||||
update: Partial<ChatToolPart>,
|
||||
fallback: ChatToolPart,
|
||||
): ChatPart[] => {
|
||||
const idx = parts.findIndex(p => p.type === 'tool' && p.toolCallId === toolCallId);
|
||||
if (idx >= 0) {
|
||||
const existing = parts[idx] as ChatToolPart;
|
||||
const merged: ChatToolPart = { ...existing, ...update };
|
||||
return [...parts.slice(0, idx), merged, ...parts.slice(idx + 1)];
|
||||
}
|
||||
return [...parts, { ...fallback, ...update }];
|
||||
};
|
||||
|
||||
const genId = () => `m_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
|
||||
|
||||
export const Chat = ({ onRequestBooking }: ChatProps) => {
|
||||
const {
|
||||
visitor,
|
||||
updateVisitor,
|
||||
leadId,
|
||||
setLeadId,
|
||||
setBookingPrefill,
|
||||
selectedBranch,
|
||||
setSelectedBranch,
|
||||
} = useWidgetStore();
|
||||
|
||||
const [messages, setMessages] = useState<ChatMessage[]>([]);
|
||||
const [input, setInput] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [formSubmitting, setFormSubmitting] = useState(false);
|
||||
const [formError, setFormError] = useState('');
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (scrollRef.current) {
|
||||
scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
|
||||
}
|
||||
}, [messages]);
|
||||
|
||||
const submitLeadForm = async () => {
|
||||
const name = visitor.name.trim();
|
||||
const phone = visitor.phone.trim();
|
||||
if (!name || !phone) return;
|
||||
setFormSubmitting(true);
|
||||
setFormError('');
|
||||
try {
|
||||
const { leadId: newLeadId } = await startChatSession(name, phone);
|
||||
setLeadId(newLeadId);
|
||||
} catch {
|
||||
setFormError('Could not start chat. Please try again.');
|
||||
} finally {
|
||||
setFormSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const sendMessage = async (text: string, branchOverride?: string | null) => {
|
||||
if (!text.trim() || loading || !leadId) return;
|
||||
|
||||
const userMsg: ChatMessage = {
|
||||
id: genId(),
|
||||
role: 'user',
|
||||
parts: [{ type: 'text', text: text.trim(), state: 'done' }],
|
||||
};
|
||||
const assistantId = genId();
|
||||
const assistantMsg: ChatMessage = { id: assistantId, role: 'assistant', parts: [] };
|
||||
|
||||
const historyForBackend = [...messages, userMsg].map(m => ({
|
||||
role: m.role,
|
||||
content: textOf(m),
|
||||
}));
|
||||
|
||||
setMessages(prev => [...prev, userMsg, assistantMsg]);
|
||||
setInput('');
|
||||
setLoading(true);
|
||||
|
||||
// Branch can be provided explicitly to bypass the stale closure value
|
||||
// when the caller just set it (e.g., handleBranchPick immediately after
|
||||
// setSelectedBranch).
|
||||
const effectiveBranch =
|
||||
branchOverride !== undefined ? branchOverride : selectedBranch;
|
||||
|
||||
try {
|
||||
const stream = await streamChat(leadId, historyForBackend, effectiveBranch);
|
||||
|
||||
for await (const chunk of readChatStream(stream)) {
|
||||
switch (chunk.type) {
|
||||
case 'text-delta':
|
||||
if (typeof chunk.delta === 'string') {
|
||||
updateMessage(setMessages, assistantId, m => ({
|
||||
...m,
|
||||
parts: appendTextDelta(m.parts, chunk.delta, 'streaming'),
|
||||
}));
|
||||
}
|
||||
break;
|
||||
case 'text-end':
|
||||
updateMessage(setMessages, assistantId, m => ({
|
||||
...m,
|
||||
parts: m.parts.map(p =>
|
||||
p.type === 'text' ? { ...p, state: 'done' } : p,
|
||||
),
|
||||
}));
|
||||
break;
|
||||
case 'tool-input-start':
|
||||
updateMessage(setMessages, assistantId, m => ({
|
||||
...m,
|
||||
parts: upsertToolPart(
|
||||
m.parts,
|
||||
chunk.toolCallId,
|
||||
{ state: 'input-streaming', toolName: chunk.toolName },
|
||||
{
|
||||
type: 'tool',
|
||||
toolCallId: chunk.toolCallId,
|
||||
toolName: chunk.toolName,
|
||||
state: 'input-streaming',
|
||||
},
|
||||
),
|
||||
}));
|
||||
break;
|
||||
case 'tool-input-available':
|
||||
updateMessage(setMessages, assistantId, m => ({
|
||||
...m,
|
||||
parts: upsertToolPart(
|
||||
m.parts,
|
||||
chunk.toolCallId,
|
||||
{ state: 'input-available', toolName: chunk.toolName, input: chunk.input },
|
||||
{
|
||||
type: 'tool',
|
||||
toolCallId: chunk.toolCallId,
|
||||
toolName: chunk.toolName,
|
||||
state: 'input-available',
|
||||
input: chunk.input,
|
||||
},
|
||||
),
|
||||
}));
|
||||
break;
|
||||
case 'tool-output-available':
|
||||
updateMessage(setMessages, assistantId, m => ({
|
||||
...m,
|
||||
parts: upsertToolPart(
|
||||
m.parts,
|
||||
chunk.toolCallId,
|
||||
{ state: 'output-available', output: chunk.output },
|
||||
{
|
||||
type: 'tool',
|
||||
toolCallId: chunk.toolCallId,
|
||||
toolName: 'unknown',
|
||||
state: 'output-available',
|
||||
output: chunk.output,
|
||||
},
|
||||
),
|
||||
}));
|
||||
break;
|
||||
case 'tool-output-error':
|
||||
updateMessage(setMessages, assistantId, m => ({
|
||||
...m,
|
||||
parts: upsertToolPart(
|
||||
m.parts,
|
||||
chunk.toolCallId,
|
||||
{ state: 'output-error', errorText: chunk.errorText },
|
||||
{
|
||||
type: 'tool',
|
||||
toolCallId: chunk.toolCallId,
|
||||
toolName: 'unknown',
|
||||
state: 'output-error',
|
||||
errorText: chunk.errorText,
|
||||
},
|
||||
),
|
||||
}));
|
||||
break;
|
||||
case 'error':
|
||||
updateMessage(setMessages, assistantId, m => ({
|
||||
...m,
|
||||
parts: [
|
||||
...m.parts,
|
||||
{
|
||||
type: 'text',
|
||||
text: 'Sorry, I encountered an error. Please try again.',
|
||||
state: 'done',
|
||||
},
|
||||
],
|
||||
}));
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
updateMessage(setMessages, assistantId, m => ({
|
||||
...m,
|
||||
parts: [
|
||||
...m.parts,
|
||||
{
|
||||
type: 'text',
|
||||
text: 'Sorry, I encountered an error. Please try again.',
|
||||
state: 'done',
|
||||
},
|
||||
],
|
||||
}));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSlotPick = (prefill: BookingPrefill) => {
|
||||
setBookingPrefill(prefill);
|
||||
onRequestBooking(prefill);
|
||||
};
|
||||
|
||||
const handleBranchPick = (branch: string) => {
|
||||
// Store the selection so every subsequent request carries it, then
|
||||
// echo the visitor's choice as a user message so the AI re-runs the
|
||||
// branch-gated tool it was about to call. We pass branch explicitly
|
||||
// to sidestep the stale-closure selectedBranch inside sendMessage.
|
||||
setSelectedBranch(branch);
|
||||
sendMessage(`I'm interested in the ${branch} branch.`, branch);
|
||||
};
|
||||
|
||||
// Pre-chat gate — only shown if we don't yet have an active lead. Name/phone
|
||||
// inputs bind to the shared store so anything typed here is immediately
|
||||
// available to the Book and Contact forms too.
|
||||
if (!leadId) {
|
||||
return (
|
||||
<div class="chat-intro">
|
||||
<div class="chat-empty-icon">
|
||||
<IconSpan name="hand-wave" size={40} color="#f59e0b" />
|
||||
</div>
|
||||
<div class="chat-empty-title">Hi! How can we help?</div>
|
||||
<div class="chat-empty-text">
|
||||
Share your name and phone so we can follow up if needed.
|
||||
</div>
|
||||
{formError && <div class="widget-error">{formError}</div>}
|
||||
<div class="widget-field">
|
||||
<label class="widget-label">Full Name *</label>
|
||||
<input
|
||||
class="widget-input"
|
||||
placeholder="Your name"
|
||||
value={visitor.name}
|
||||
onInput={(e: any) => updateVisitor({ name: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<div class="widget-field">
|
||||
<label class="widget-label">Phone Number *</label>
|
||||
<input
|
||||
class="widget-input"
|
||||
placeholder="+91 9876543210"
|
||||
value={visitor.phone}
|
||||
onInput={(e: any) => updateVisitor({ phone: e.target.value })}
|
||||
onKeyDown={(e: any) => e.key === 'Enter' && submitLeadForm()}
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
class="widget-btn"
|
||||
onClick={submitLeadForm}
|
||||
disabled={!visitor.name.trim() || !visitor.phone.trim() || formSubmitting}
|
||||
>
|
||||
{formSubmitting ? 'Starting…' : 'Start Chat'}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
|
||||
<div class="chat-messages" ref={scrollRef}>
|
||||
{messages.length === 0 && (
|
||||
<div class="chat-empty">
|
||||
<div class="chat-empty-icon">
|
||||
<IconSpan name="hand-wave" size={40} color="#f59e0b" />
|
||||
</div>
|
||||
<div class="chat-empty-title">
|
||||
Hi {visitor.name.split(' ')[0] || 'there'}, how can we help?
|
||||
</div>
|
||||
<div class="chat-empty-text">
|
||||
Ask about doctors, clinics, packages, or book an appointment.
|
||||
</div>
|
||||
<div class="quick-actions">
|
||||
{QUICK_ACTIONS.map(q => (
|
||||
<button key={q} class="quick-action" onClick={() => sendMessage(q)}>
|
||||
{q}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{messages.map(msg => (
|
||||
<MessageRow
|
||||
key={msg.id}
|
||||
msg={msg}
|
||||
onDepartmentClick={dept => sendMessage(`Show me doctors in ${dept}`)}
|
||||
onShowDoctorSlots={doctorName =>
|
||||
sendMessage(`Show available appointments for ${doctorName}`)
|
||||
}
|
||||
onSuggestBooking={() => onRequestBooking()}
|
||||
onPickSlot={handleSlotPick}
|
||||
onPickBranch={handleBranchPick}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<div class="chat-input-row">
|
||||
<input
|
||||
class="widget-input chat-input"
|
||||
placeholder="Type a message..."
|
||||
value={input}
|
||||
onInput={(e: any) => setInput(e.target.value)}
|
||||
onKeyDown={(e: any) => e.key === 'Enter' && sendMessage(input)}
|
||||
disabled={loading}
|
||||
/>
|
||||
<button
|
||||
class="chat-send"
|
||||
onClick={() => sendMessage(input)}
|
||||
disabled={loading || !input.trim()}
|
||||
aria-label="Send message"
|
||||
>
|
||||
<IconSpan name="paper-plane-top" size={16} color="#fff" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
type MessageRowProps = {
|
||||
msg: ChatMessage;
|
||||
onDepartmentClick: (dept: string) => void;
|
||||
onShowDoctorSlots: (doctorName: string) => void;
|
||||
onSuggestBooking: () => void;
|
||||
onPickSlot: (prefill: BookingPrefill) => void;
|
||||
onPickBranch: (branch: string) => void;
|
||||
};
|
||||
|
||||
const MessageRow = ({
|
||||
msg,
|
||||
onDepartmentClick,
|
||||
onShowDoctorSlots,
|
||||
onSuggestBooking,
|
||||
onPickSlot,
|
||||
onPickBranch,
|
||||
}: MessageRowProps) => {
|
||||
const isEmptyAssistant = msg.role === 'assistant' && msg.parts.length === 0;
|
||||
|
||||
// If any tool parts exist, hide text parts from the same turn to avoid
|
||||
// models restating the widget's contents in prose.
|
||||
const hasToolParts = msg.parts.some(p => p.type === 'tool');
|
||||
const visibleParts = hasToolParts
|
||||
? msg.parts.filter(p => p.type === 'tool')
|
||||
: msg.parts;
|
||||
|
||||
return (
|
||||
<div class={`chat-msg ${msg.role}`}>
|
||||
<div class="chat-msg-stack">
|
||||
{isEmptyAssistant && (
|
||||
<div class="chat-bubble">
|
||||
<TypingDots />
|
||||
</div>
|
||||
)}
|
||||
{visibleParts.map((part, i) => {
|
||||
if (part.type === 'text') {
|
||||
return (
|
||||
<div key={i} class="chat-bubble">
|
||||
{part.text || <TypingDots />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<ChatToolWidget
|
||||
key={i}
|
||||
part={part}
|
||||
onDepartmentClick={onDepartmentClick}
|
||||
onShowDoctorSlots={onShowDoctorSlots}
|
||||
onSuggestBooking={onSuggestBooking}
|
||||
onPickSlot={onPickSlot}
|
||||
onPickBranch={onPickBranch}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const TypingDots = () => (
|
||||
<span class="chat-typing-dots" aria-label="Assistant is typing">
|
||||
<span /><span /><span />
|
||||
</span>
|
||||
);
|
||||
104
widget-src/src/contact.tsx
Normal file
104
widget-src/src/contact.tsx
Normal file
@@ -0,0 +1,104 @@
|
||||
import { useState } from 'preact/hooks';
|
||||
import { submitLead } from './api';
|
||||
import { IconSpan } from './icon-span';
|
||||
import { useWidgetStore } from './store';
|
||||
|
||||
export const Contact = () => {
|
||||
const { visitor, updateVisitor, captchaToken } = useWidgetStore();
|
||||
|
||||
const [interest, setInterest] = useState('');
|
||||
const [message, setMessage] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [success, setSuccess] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!visitor.name.trim() || !visitor.phone.trim()) return;
|
||||
setLoading(true);
|
||||
setError('');
|
||||
try {
|
||||
await submitLead({
|
||||
name: visitor.name.trim(),
|
||||
phone: visitor.phone.trim(),
|
||||
interest: interest.trim() || undefined,
|
||||
message: message.trim() || undefined,
|
||||
captchaToken,
|
||||
});
|
||||
setSuccess(true);
|
||||
} catch {
|
||||
setError('Submission failed. Please try again.');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (success) {
|
||||
return (
|
||||
<div class="widget-success">
|
||||
<div class="widget-success-icon">
|
||||
<IconSpan name="hands-praying" size={56} color="#059669" />
|
||||
</div>
|
||||
<div class="widget-success-title">Thank you!</div>
|
||||
<div class="widget-success-text">
|
||||
An agent will call you shortly on {visitor.phone}.<br />
|
||||
We typically respond within 30 minutes during business hours.
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div class="widget-section-title">Get in touch</div>
|
||||
<div class="widget-section-sub">Leave your details and we'll call you back.</div>
|
||||
|
||||
{error && <div class="widget-error">{error}</div>}
|
||||
|
||||
<div class="widget-field">
|
||||
<label class="widget-label">Full Name *</label>
|
||||
<input
|
||||
class="widget-input"
|
||||
placeholder="Your name"
|
||||
value={visitor.name}
|
||||
onInput={(e: any) => updateVisitor({ name: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<div class="widget-field">
|
||||
<label class="widget-label">Phone Number *</label>
|
||||
<input
|
||||
class="widget-input"
|
||||
placeholder="+91 9876543210"
|
||||
value={visitor.phone}
|
||||
onInput={(e: any) => updateVisitor({ phone: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<div class="widget-field">
|
||||
<label class="widget-label">Interested In</label>
|
||||
<select class="widget-select" value={interest} onChange={(e: any) => setInterest(e.target.value)}>
|
||||
<option value="">Select (optional)</option>
|
||||
<option value="Consultation">General Consultation</option>
|
||||
<option value="Health Checkup">Health Checkup</option>
|
||||
<option value="Surgery">Surgery</option>
|
||||
<option value="Second Opinion">Second Opinion</option>
|
||||
<option value="Other">Other</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="widget-field">
|
||||
<label class="widget-label">Message</label>
|
||||
<textarea
|
||||
class="widget-input widget-textarea"
|
||||
placeholder="How can we help? (optional)"
|
||||
value={message}
|
||||
onInput={(e: any) => setMessage(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
class="widget-btn"
|
||||
disabled={!visitor.name.trim() || !visitor.phone.trim() || loading}
|
||||
onClick={handleSubmit}
|
||||
>
|
||||
{loading ? 'Sending...' : 'Send Message'}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
15
widget-src/src/icon-span.tsx
Normal file
15
widget-src/src/icon-span.tsx
Normal file
@@ -0,0 +1,15 @@
|
||||
import { icon, type IconName } from './icons';
|
||||
|
||||
type IconSpanProps = {
|
||||
name: IconName;
|
||||
size?: number;
|
||||
color?: string;
|
||||
class?: string;
|
||||
};
|
||||
|
||||
// Safe: the SVG strings in icons.ts are hard-coded FontAwesome Pro paths bundled at
|
||||
// compile time. No user input flows through here — nothing to sanitize.
|
||||
export const IconSpan = ({ name, size = 16, color = 'currentColor', class: className }: IconSpanProps) => {
|
||||
const html = icon(name, size, color);
|
||||
return <span class={className} dangerouslySetInnerHTML={{ __html: html }} />;
|
||||
};
|
||||
83
widget-src/src/icons.ts
Normal file
83
widget-src/src/icons.ts
Normal file
@@ -0,0 +1,83 @@
|
||||
// FontAwesome Pro 7.1.0 Duotone SVGs — bundled as inline strings
|
||||
// License: https://fontawesome.com/license (Commercial License)
|
||||
// Paths use fill="currentColor" so color is inherited from the <svg> element.
|
||||
|
||||
export const icons = {
|
||||
// Navigation / UI
|
||||
'message-dots': `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path opacity=".4" fill="currentColor" d="M0 128L0 352c0 53 43 96 96 96l32 0 0 72c0 13.3 10.7 24 24 24 5.2 0 10.2-1.7 14.4-4.8l115.2-86.4c4.2-3.1 9.2-4.8 14.4-4.8l120 0c53 0 96-43 96-96l0-224c0-53-43-96-96-96L96 32C43 32 0 75 0 128zM160 240a32 32 0 1 1 -64 0 32 32 0 1 1 64 0zm128 0a32 32 0 1 1 -64 0 32 32 0 1 1 64 0zm128 0a32 32 0 1 1 -64 0 32 32 0 1 1 64 0z"/><path fill="currentColor" d="M96 240a32 32 0 1 1 64 0 32 32 0 1 1 -64 0zm128 0a32 32 0 1 1 64 0 32 32 0 1 1 -64 0zm160-32a32 32 0 1 1 0 64 32 32 0 1 1 0-64z"/></svg>`,
|
||||
|
||||
calendar: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><path opacity=".4" fill="currentColor" d="M0 160l448 0 0 272c0 26.5-21.5 48-48 48L48 480c-26.5 0-48-21.5-48-48L0 160z"/><path fill="currentColor" d="M160 32c0-17.7-14.3-32-32-32S96 14.3 96 32l0 32-48 0C21.5 64 0 85.5 0 112l0 48 448 0 0-48c0-26.5-21.5-48-48-48l-48 0 0-32c0-17.7-14.3-32-32-32s-32 14.3-32 32l0 32-128 0 0-32z"/></svg>`,
|
||||
|
||||
phone: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path opacity=".4" fill="currentColor" d="M86.8 90l19 47c5 12.3 19 18.2 31.2 13.3s18.2-19 13.3-31.2l-19-47c-5-12.3-19-18.2-31.2-13.3-12.3 5-18.2 19-13.3 31.2zm275 285c-5 12.3 1 26.3 13.3 31.2l47 19c12.3 5 26.3-1 31.2-13.3s-1-26.3-13.3-31.2l-47-19c-12.3-5-26.3 1-31.2 13.3z"/><path fill="currentColor" d="M112.1 1.4c19.7-5.4 40.3 4.7 48.1 23.5l40.5 97.3c6.9 16.5 2.1 35.6-11.8 47l-44.1 36.1c32.5 71.6 89 130 159.3 164.9L342.8 323c11.3-13.9 30.4-18.6 47-11.8L487 351.8c18.8 7.8 28.9 28.4 23.5 48.1l-1.5 5.5C491.4 470.1 428.9 525.3 352.6 509.2 177.6 472.1 39.9 334.4 2.8 159.4-13.3 83.1 41.9 20.6 106.5 2.9l5.5-1.5zM131.3 72c-5-12.3-19-18.2-31.2-13.3S81.8 77.7 86.8 90l19 47c5 12.3 19 18.2 31.2 13.3s18.2-19 13.3-31.2l-19-47zM393 361.7c-12.3-5-26.3 1-31.2 13.3s1 26.3 13.3 31.2l47 19c12.3 5 26.3-1 31.2-13.3s-1-26.3-13.3-31.2l-47-19z"/></svg>`,
|
||||
|
||||
'paper-plane-top': `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512"><path opacity=".4" fill="currentColor" d="M32 479c0 18.1 14.7 33 32.8 33 4.7 0 9.4-1 13.7-3L554.2 290c13.3-6.1 21.8-19.4 21.8-34l-448 0-93.2 209.6C33 469.8 32 474.4 32 479z"/><path fill="currentColor" d="M78.5 3L554.2 222c13.3 6.1 21.8 19.4 21.8 34L128 256 34.8 46.4C33 42.2 32 37.6 32 33 32 14.8 46.7 0 64.8 0 69.5 0 74.2 1 78.5 3z"/></svg>`,
|
||||
|
||||
xmark: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 384 512"><path fill="currentColor" d="M55.1 73.4c-12.5-12.5-32.8-12.5-45.3 0s-12.5 32.8 0 45.3L147.2 256 9.9 393.4c-12.5 12.5-12.5 32.8 0 45.3s32.8 12.5 45.3 0L192.5 301.3 329.9 438.6c12.5 12.5 32.8 12.5 45.3 0s12.5-32.8 0-45.3L237.8 256 375.1 118.6c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0L192.5 210.7 55.1 73.4z"/></svg>`,
|
||||
|
||||
'circle-check': `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path opacity=".4" fill="currentColor" d="M0 256a256 256 0 1 0 512 0 256 256 0 1 0 -512 0zm135.1 7.1c9.4-9.4 24.6-9.4 33.9 0L221.1 315.2 340.5 151c7.8-10.7 22.8-13.1 33.5-5.3s13.1 22.8 5.3 33.5L243.4 366.1c-4.1 5.7-10.5 9.3-17.5 9.8s-13.9-2-18.8-7l-72-72c-9.4-9.4-9.4-24.6 0-33.9z"/><path fill="currentColor" d="M340.5 151c7.8-10.7 22.8-13.1 33.5-5.3s13.1 22.8 5.3 33.5L243.4 366.1c-4.1 5.7-10.5 9.3-17.5 9.8s-13.9-2-18.8-7l-72-72c-9.4-9.4-9.4-24.6 0-33.9s24.6-9.4 33.9 0L221.1 315.2 340.5 151z"/></svg>`,
|
||||
|
||||
sparkles: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512"><path opacity=".4" fill="currentColor" d="M352 448c0 4.8 3 9.1 7.5 10.8L416 480 437.2 536.5c1.7 4.5 6 7.5 10.8 7.5s9.1-3 10.8-7.5L480 480 536.5 458.8c4.5-1.7 7.5-6 7.5-10.8s-3-9.1-7.5-10.8L480 416 458.8 359.5c-1.7-4.5-6-7.5-10.8-7.5s-9.1 3-10.8 7.5L416 416 359.5 437.2c-4.5 1.7-7.5 6-7.5 10.8zM384 64c0 4.8 3 9.1 7.5 10.8L448 96 469.2 152.5c1.7 4.5 6 7.5 10.8 7.5s9.1-3 10.8-7.5L512 96 568.5 74.8c4.5-1.7 7.5-6 7.5-10.8s-3-9.1-7.5-10.8L512 32 490.8-24.5c-1.7-4.5-6-7.5-10.8-7.5s-9.1 3-10.8 7.5L448 32 391.5 53.2c-4.5 1.7-7.5 6-7.5 10.8z"/><path fill="currentColor" d="M205.1 73.3c-2.6-5.7-8.3-9.3-14.5-9.3s-11.9 3.6-14.5 9.3L123.4 187.4 9.3 240C3.6 242.6 0 248.3 0 254.6s3.6 11.9 9.3 14.5L123.4 321.8 176 435.8c2.6 5.7 8.3 9.3 14.5 9.3s11.9-3.6 14.5-9.3l52.7-114.1 114.1-52.7c5.7-2.6 9.3-8.3 9.3-14.5s-3.6-11.9-9.3-14.5L257.8 187.4 205.1 73.3z"/></svg>`,
|
||||
|
||||
'hands-praying': `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 512"><path opacity=".4" fill="currentColor" d="M352 224l0 119.6c0 57.2 37.9 107.4 92.8 123.1l154.4 44.1c9.7 2.8 20 .8 28.1-5.2S640 490 640 480l0-96c0-13.8-8.8-26-21.9-30.4l-58.1-19.4 0-110.7c0-29-9.3-57.3-26.5-80.7L440.2 16.3C427.1-1.5 402.1-5.3 384.3 7.8s-21.6 38.1-8.5 55.9L464 183.4 464 296c0 13.3-10.7 24-24 24s-24-10.7-24-24l0-72c0-17.7-14.3-32-32-32s-32 14.3-32 32z"/><path fill="currentColor" d="M200 320c13.3 0 24-10.7 24-24l0-72c0-17.7 14.3-32 32-32s32 14.3 32 32l0 119.6c0 57.2-37.9 107.4-92.8 123.1L40.8 510.8c-9.7 2.8-20 .8-28.1-5.2S0 490 0 480l0-96c0-13.8 8.8-26 21.9-30.4L80 334.3 80 223.6c0-29 9.3-57.3 26.5-80.7L199.8 16.3c13.1-17.8 38.1-21.6 55.9-8.5s21.6 38.1 8.5 55.9L176 183.4 176 296c0 13.3 10.7 24 24 24z"/></svg>`,
|
||||
|
||||
'hand-wave': `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512"><path opacity=".4" fill="currentColor" d="M73.4 265.4c-12.5 12.5-12.5 32.8 0 45.3 8.8 8.8 55.2 55.2 139.1 139.1l4.9 4.9c22.2 22.2 49.2 36.9 77.6 44.1 58 17 122.8 6.6 173.6-32.7 47.6-36.8 75.5-93.5 75.5-153.7L544 136c0-22.1-17.9-40-40-40s-40 17.9-40 40l0 77.7c0 4.7-6 7-9.4 3.7l-192-192c-12.5-12.5-32.8-12.5-45.3 0s-12.5 32.8 0 45.3L344 197.3c5.2 5.2 5.2 13.6 0 18.7s-13.6 5.2-18.7 0L182.6 73.4c-12.5-12.5-32.8-12.5-45.3 0s-12.5 32.8 0 45.3L280 261.3c5.2 5.2 5.2 13.6 0 18.7s-13.6 5.2-18.7 0L134.6 153.4c-12.5-12.5-32.8-12.5-45.3 0s-12.5 32.8 0 45.3L216 325.3c5.2 5.2 5.2 13.6 0 18.7s-13.6 5.2-18.7 0c-33.5-33.5-59.8-59.8-78.6-78.6-12.5-12.5-32.8-12.5-45.3 0z"/><path fill="currentColor" d="M392.2 67.4c1.9 13.1 14 22.2 27.2 20.4s22.2-14 20.4-27.2l-1.2-8.5c-5.5-38.7-36-69.1-74.7-74.7l-8.5-1.2c-13.1-1.9-25.3 7.2-27.2 20.4s7.2 25.3 20.4 27.2l8.5 1.2c17.6 2.5 31.4 16.3 33.9 33.9l1.2 8.5zM55.8 380.6c-1.9-13.1-14-22.2-27.2-20.4s-22.2 14-20.4 27.2l1.2 8.5c5.5 38.7 36 69.1 74.7 74.7l8.5 1.2c13.1 1.9 25.3-7.2 27.2-20.4s-7.2-25.3-20.4-27.2L90.9 423c-17.6-2.5-31.4-16.3-33.9-33.9l-1.2-8.5z"/></svg>`,
|
||||
|
||||
'shield-check': `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path opacity=".4" fill="currentColor" d="M16 140c.5 99.2 41.3 280.7 213.6 363.2 16.7 8 36.1 8 52.7 0 172.4-82.5 213.2-263.9 213.7-363.2 .1-26.2-16.3-47.9-38.3-57.2L269.4 2.9C265.3 1 260.7 0 256.1 0s-9.2 1-13.4 2.9L54.3 82.8c-22 9.3-38.4 31-38.3 57.2zM166.8 293.5c-9.2-9.5-9-24.7 .6-33.9 9.5-9.2 24.7-9 33.9 .6 8.8 9.1 17.7 18.3 26.5 27.4 28.5-39.2 57.1-78.5 85.6-117.7 7.8-10.7 22.8-13.1 33.5-5.3s13.1 22.8 5.3 33.5c-34.1 46.9-68.3 93.9-102.4 140.8-4.2 5.7-10.7 9.4-17.8 9.8s-14-2.2-18.9-7.3c-15.5-16-30.9-32-46.4-48z"/><path fill="currentColor" d="M313.4 169.9c7.8-10.7 22.8-13.1 33.5-5.3s13.1 22.8 5.3 33.5L249.8 338.9c-4.2 5.7-10.7 9.4-17.8 9.8s-14-2.2-18.9-7.3l-46.4-48c-9.2-9.5-9-24.7 .6-33.9s24.7-8.9 33.9 .6l26.5 27.4 85.6-117.7z"/></svg>`,
|
||||
|
||||
'arrow-left': `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path opacity=".4" fill="currentColor" d="M77.3 256l32 32 370.7 0c17.7 0 32-14.3 32-32s-14.3-32-32-32l-370.7 0-32 32z"/><path fill="currentColor" d="M9.4 278.6c-12.5-12.5-12.5-32.8 0-45.3l160-160c12.5-12.5 32.8-12.5 45.3 0s12.5 32.8 0 45.3L77.3 256 214.6 393.4c12.5 12.5 12.5 32.8 0 45.3s-32.8 12.5-45.3 0l-160-160z"/></svg>`,
|
||||
|
||||
'arrow-right': `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path opacity=".4" fill="currentColor" d="M0 256c0 17.7 14.3 32 32 32l370.7 0 32-32-32-32-370.7 0c-17.7 0-32 14.3-32 32z"/><path fill="currentColor" d="M502.6 233.4c12.5 12.5 12.5 32.8 0 45.3l-160 160c-12.5 12.5-32.8 12.5-45.3 0s-12.5-32.8 0-45.3L434.7 256 297.4 118.6c-12.5-12.5-12.5-32.8 0-45.3s32.8-12.5 45.3 0l160 160z"/></svg>`,
|
||||
|
||||
'up-right-and-down-left-from-center': `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path opacity=".4" fill="currentColor" d="M0 344L0 488c0 13.3 10.7 24 24 24l144 0c9.7 0 18.5-5.8 22.2-14.8s1.7-19.3-5.2-26.2l-39-39 87-87c9.4-9.4 9.4-24.6 0-33.9l-32-32c-9.4-9.4-24.6-9.4-33.9 0l-87 87-39-39c-6.9-6.9-17.2-8.9-26.2-5.2S0 334.3 0 344z"/><path fill="currentColor" d="M488 0L344 0c-9.7 0-18.5 5.8-22.2 14.8S320.2 34.1 327 41l39 39-87 87c-9.4 9.4-9.4 24.6 0 33.9l32 32c9.4 9.4 24.6 9.4 33.9 0l87-87 39 39c6.9 6.9 17.2 8.9 26.2 5.2S512 177.7 512 168l0-144c0-13.3-10.7-24-24-24z"/></svg>`,
|
||||
|
||||
'down-left-and-up-right-to-center': `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path opacity=".4" fill="currentColor" d="M7.5 439c-9.4 9.4-9.4 24.6 0 33.9l32 32c9.4 9.4 24.6 9.4 33.9 0l87-87 39 39c6.9 6.9 17.2 8.9 26.2 5.2s14.8-12.5 14.8-22.2l0-144c0-13.3-10.7-24-24-24l-144 0c-9.7 0-18.5 5.8-22.2 14.8s-1.7 19.3 5.2 26.2l39 39-87 87z"/><path fill="currentColor" d="M473.5 7c-9.4-9.4-24.6-9.4-33.9 0l-87 87-39-39c-6.9-6.9-17.2-8.9-26.2-5.2S272.5 62.3 272.5 72l0 144c0 13.3 10.7 24 24 24l144 0c9.7 0 18.5-5.8 22.2-14.8s1.7-19.3-5.2-26.2l-39-39 87-87c9.4-9.4 9.4-24.6 0-33.9l-32-32z"/></svg>`,
|
||||
|
||||
// Branch / location
|
||||
hospital: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512"><path opacity=".4" fill="currentColor" d="M0 192L0 448c0 35.3 28.7 64 64 64l176 0 0-112c0-17.7 14.3-32 32-32l32 0c17.7 0 32 14.3 32 32l0 112 176 0c35.3 0 64-28.7 64-64l0-256c0-35.3-28.7-64-64-64l-64 0 0-64c0-35.3-28.7-64-64-64L192 0c-35.3 0-64 28.7-64 64l0 64-64 0c-35.3 0-64 28.7-64 64zm64 16c0-8.8 7.2-16 16-16l32 0c8.8 0 16 7.2 16 16l0 32c0 8.8-7.2 16-16 16l-32 0c-8.8 0-16-7.2-16-16l0-32zm0 128c0-8.8 7.2-16 16-16l32 0c8.8 0 16 7.2 16 16l0 32c0 8.8-7.2 16-16 16l-32 0c-8.8 0-16-7.2-16-16l0-32zM216 152c0-8.8 7.2-16 16-16l32 0 0-32c0-8.8 7.2-16 16-16l16 0c8.8 0 16 7.2 16 16l0 32 32 0c8.8 0 16 7.2 16 16l0 16c0 8.8-7.2 16-16 16l-32 0 0 32c0 8.8-7.2 16-16 16l-16 0c-8.8 0-16-7.2-16-16l0-32-32 0c-8.8 0-16-7.2-16-16l0-16zm232 56c0-8.8 7.2-16 16-16l32 0c8.8 0 16 7.2 16 16l0 32c0 8.8-7.2 16-16 16l-32 0c-8.8 0-16-7.2-16-16l0-32zm0 128c0-8.8 7.2-16 16-16l32 0c8.8 0 16 7.2 16 16l0 32c0 8.8-7.2 16-16 16l-32 0c-8.8 0-16-7.2-16-16l0-32z"/><path fill="currentColor" d="M264 104c0-8.8 7.2-16 16-16l16 0c8.8 0 16 7.2 16 16l0 32 32 0c8.8 0 16 7.2 16 16l0 16c0 8.8-7.2 16-16 16l-32 0 0 32c0 8.8-7.2 16-16 16l-16 0c-8.8 0-16-7.2-16-16l0-32-32 0c-8.8 0-16-7.2-16-16l0-16c0-8.8 7.2-16 16-16l32 0 0-32zM112 256l-32 0c-8.8 0-16-7.2-16-16l0-32c0-8.8 7.2-16 16-16l32 0c8.8 0 16 7.2 16 16l0 32c0 8.8-7.2 16-16 16zm16 112c0 8.8-7.2 16-16 16l-32 0c-8.8 0-16-7.2-16-16l0-32c0-8.8 7.2-16 16-16l32 0c8.8 0 16 7.2 16 16l0 32zm112 32c0-17.7 14.3-32 32-32l32 0c17.7 0 32 14.3 32 32l0 112-96 0 0-112zm272-32c0 8.8-7.2 16-16 16l-32 0c-8.8 0-16-7.2-16-16l0-32c0-8.8 7.2-16 16-16l32 0c8.8 0 16 7.2 16 16l0 32zM496 256l-32 0c-8.8 0-16-7.2-16-16l0-32c0-8.8 7.2-16 16-16l32 0c8.8 0 16 7.2 16 16l0 32c0 8.8-7.2 16-16 16z"/></svg>`,
|
||||
|
||||
'location-dot': `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 384 512"><path opacity=".4" fill="currentColor" d="M0 188.6c0 119.3 120.2 262.3 170.4 316.8 11.8 12.8 31.5 12.8 43.3 0 50.2-54.5 170.4-197.5 170.4-316.8 0-104.1-86-188.6-192-188.6S0 84.4 0 188.6zM256 192a64 64 0 1 1 -128 0 64 64 0 1 1 128 0z"/><path fill="currentColor" d="M128 192a64 64 0 1 1 128 0 64 64 0 1 1 -64 0z"/></svg>`,
|
||||
|
||||
// Medical departments
|
||||
stethoscope: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512"><path opacity=".4" fill="currentColor" d="M160 348.8c10.3 2.1 21 3.2 32 3.2s21.7-1.1 32-3.2l0 19.2c0 61.9 50.1 112 112 112s112-50.1 112-112l0-85.5c10 3.5 20.8 5.5 32 5.5s22-1.9 32-5.5l0 85.5c0 97.2-78.8 176-176 176S160 465.2 160 368l0-19.2z"/><path fill="currentColor" d="M80 0C53.5 0 32 21.5 32 48l0 144c0 88.4 71.6 160 160 160s160-71.6 160-160l0-144c0-26.5-21.5-48-48-48L256 0c-17.7 0-32 14.3-32 32s14.3 32 32 32l32 0 0 128c0 53-43 96-96 96s-96-43-96-96l0-128 32 0c17.7 0 32-14.3 32-32S145.7 0 128 0L80 0zM448 192a32 32 0 1 1 64 0 32 32 0 1 1 -64 0zm128 0a96 96 0 1 0 -192 0 96 96 0 1 0 192 0z"/></svg>`,
|
||||
|
||||
'heart-pulse': `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path opacity=".4" fill="currentColor" d="M0 165.1l0 2.6c0 23.6 6.2 48 16.6 72.3l106 0c3.2 0 6.1-1.9 7.4-4.9l31.8-76.3c3.7-8.8 12.3-14.6 21.8-14.8s18.3 5.4 22.2 14.1l51.3 113.9 41.4-82.8c4.1-8.1 12.4-13.3 21.5-13.3s17.4 5.1 21.5 13.3l23.2 46.3c1.4 2.7 4.1 4.4 7.2 4.4l123.6 0c10.5-24.3 16.6-48.7 16.6-72.3l0-2.6C512 91.6 452.4 32 378.9 32 336.2 32 296 52.5 271 87.1l-15 20.7-15-20.7C216 52.5 175.9 32 133.1 32 59.6 32 0 91.6 0 165.1zM42.5 288c47.2 73.8 123 141.7 170.4 177.9 12.4 9.4 27.6 14.1 43.1 14.1s30.8-4.6 43.1-14.1C346.6 429.7 422.4 361.8 469.6 288l-97.8 0c-21.2 0-40.6-12-50.1-31l-1.7-3.4-42.5 85.1c-4.1 8.3-12.7 13.5-22 13.3s-17.6-5.7-21.4-14.1l-49.3-109.5-10.5 25.2c-8.7 20.9-29.1 34.5-51.7 34.5l-80.2 0z"/><path fill="currentColor" d="M42.5 288c-10.1-15.8-18.9-31.9-25.8-48l106 0c3.2 0 6.1-1.9 7.4-4.9l31.8-76.3c3.7-8.8 12.3-14.6 21.8-14.8s18.3 5.4 22.2 14.1l51.3 113.9 41.4-82.8c4.1-8.1 12.4-13.3 21.5-13.3s17.4 5.1 21.5 13.3l23.2 46.3c1.4 2.7 4.1 4.4 7.2 4.4l123.6 0c-6.9 16.1-15.7 32.2-25.8 48l-97.8 0c-21.2 0-40.6-12-50.1-31l-1.7-3.4-42.5 85.1c-4.1 8.3-12.7 13.5-22 13.3s-17.6-5.7-21.4-14.1l-49.3-109.5-10.5 25.2c-8.7 20.9-29.1 34.5-51.7 34.5l-80.2 0z"/></svg>`,
|
||||
|
||||
bone: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 512"><path fill="currentColor" d="M197.4 160c-3.9 0-7.2-2.8-8.1-6.6-10.2-42.1-48.1-73.4-93.3-73.4-53 0-96 43-96 96 0 29.1 12.9 55.1 33.3 72.7 4.3 3.7 4.3 10.8 0 14.5-20.4 17.6-33.3 43.7-33.3 72.7 0 53 43 96 96 96 45.2 0 83.1-31.3 93.3-73.4 .9-3.8 4.2-6.6 8.1-6.6l245.1 0c3.9 0 7.2 2.8 8.1 6.6 10.2 42.1 48.1 73.4 93.3 73.4 53 0 96-43 96-96 0-29.1-12.9-55.1-33.3-72.7-4.3-3.7-4.3-10.8 0-14.5 20.4-17.6 33.3-43.7 33.3-72.7 0-53-43-96-96-96-45.2 0-83.1 31.3-93.3 73.4-.9 3.8-4.2 6.6-8.1 6.6l-245.1 0z"/></svg>`,
|
||||
|
||||
'person-pregnant': `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 384 512"><path opacity=".4" fill="currentColor" d="M136 24a56 56 0 1 0 112 0 56 56 0 1 0 -112 0z"/><path fill="currentColor" d="M74.6 305.8l29-43.5-30.5 113.5c-2.6 9.6-.6 19.9 5.5 27.8S94 416 104 416l8 0 0 96c0 17.7 14.3 32 32 32s32-14.3 32-32l0-96 32 0 0 96c0 17.7 14.3 32 32 32s32-14.3 32-32l0-110.8c8.6-4.5 16.8-10 24.3-16.5l4-3.4c22.6-19.4 35.7-47.7 35.7-77.6 0-35.9-18.8-69.1-49.6-87.6l-30.4-18.2 0-1.8c0-46.5-37.7-84.1-84.1-84.1-28.1 0-54.4 14.1-70 37.5L21.4 270.2c-9.8 14.7-5.8 34.6 8.9 44.4s34.6 5.8 44.4-8.9z"/></svg>`,
|
||||
|
||||
ear: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 384 512"><path opacity=".4" fill="currentColor" d="M0 192L0 384c0 70.7 57.3 128 128 128l9.3 0c52.3 0 99.4-31.9 118.8-80.5l20.1-50.2c5.5-13.7 15.8-24.8 27.8-33.4 48.4-34.9 80-91.7 80-156 0-106-86-192-192-192S0 86 0 192zm64 0c0-70.7 57.3-128 128-128s128 57.3 128 128l0 8c0 13.3-10.7 24-24 24s-24-10.7-24-24l0-8c0-44.2-35.8-80-80-80s-80 35.8-80 80l0 16.4c36 4 64 34.5 64 71.6 0 39.8-32.2 72-72 72l-16 0c-13.3 0-24-10.7-24-24s10.7-24 24-24l16 0c13.3 0 24-10.7 24-24s-10.7-24-24-24l-16 0c-13.3 0-24-10.7-24-24l0-40z"/><path fill="currentColor" d="M192 112c-44.2 0-80 35.8-80 80l0 16.4c36 4 64 34.5 64 71.6 0 39.8-32.2 72-72 72l-16 0c-13.3 0-24-10.7-24-24s10.7-24 24-24l16 0c13.3 0 24-10.7 24-24s-10.7-24-24-24l-16 0c-13.3 0-24-10.7-24-24l0-40c0-70.7 57.3-128 128-128s128 57.3 128 128l0 8c0 13.3-10.7 24-24 24s-24-10.7-24-24l0-8c0-44.2-35.8-80-80-80z"/></svg>`,
|
||||
|
||||
baby: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 384 512"><path opacity=".4" fill="currentColor" d="M7.7 144.5c13-17.9 38-21.8 55.9-8.8L99.8 162c26.8 19.5 59.1 30 92.2 30s65.4-10.5 92.2-30l36.2-26.4c17.9-13 42.9-9 55.9 8.8s9 42.9-8.8 55.9l-36.2 26.4c-13.6 9.9-28.1 18.2-43.3 25l0 36.3-192 0 0-36.3c-15.2-6.7-29.7-15.1-43.3-25L16.5 200.3c-17.9-13-21.8-38-8.8-55.9zM47.2 401.1l50.2-71.8c20.2 17.7 40.4 35.3 60.6 53l-26 37.2 24.3 24.3c15.6 15.6 15.6 40.9 0 56.6s-40.9 15.6-56.6 0l-48-48C38 438.6 36.1 417 47.2 401.1zM264 88a72 72 0 1 1 -144 0 72 72 0 1 1 144 0zM226 382.3c20.2-17.7 40.4-35.3 60.6-53l50.2 71.8c11.1 15.9 9.2 37.5-4.5 51.2l-48 48c-15.6 15.6-40.9 15.6-56.6 0s-15.6-40.9 0-56.6l24.3-24.3-26-37.2z"/><path fill="currentColor" d="M160 384l-64-56 0-40 192 0 0 40-64 56-64 0z"/></svg>`,
|
||||
|
||||
brain: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path opacity=".4" fill="currentColor" d="M8 272c0 26.2 12.6 49.4 32 64-10 13.4-16 30-16 48 0 44.2 35.8 80 80 80 .7 0 1.3 0 2 0 7.1 27.6 32.2 48 62 48l32 0c17.7 0 32-14.3 32-32l0-448c0-17.7-14.3-32-32-32L176 0c-30.9 0-56 25.1-56 56l0 24c-44.2 0-80 35.8-80 80 0 15 4.1 29 11.2 40.9-25.7 13.3-43.2 40.1-43.2 71.1zM280 32l0 448c0 17.7 14.3 32 32 32l32 0c29.8 0 54.9-20.4 62-48 .7 0 1.3 0 2 0 44.2 0 80-35.8 80-80 0-18-6-34.6-16-48 19.4-14.6 32-37.8 32-64 0-30.9-17.6-57.8-43.2-71.1 7.1-12 11.2-26 11.2-40.9 0-44.2-35.8-80-80-80l0-24c0-30.9-25.1-56-56-56L312 0c-17.7 0-32 14.3-32 32z"/><path fill="currentColor" d="M232 32l48 0 0 448-48 0 0-448z"/></svg>`,
|
||||
|
||||
eye: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512"><path opacity=".4" fill="currentColor" d="M2.5 243.7c-3.3 7.9-3.3 16.7 0 24.6 14.9 35.7 46.2 87.7 93 131.1 47.1 43.7 111.8 80.6 192.6 80.6s145.5-36.8 192.6-80.6c46.8-43.5 78.1-95.4 93-131.1 3.3-7.9 3.3-16.7 0-24.6-14.9-35.7-46.2-87.7-93-131.1-47.1-43.7-111.8-80.6-192.6-80.6S142.5 68.8 95.4 112.6C48.6 156 17.3 208 2.5 243.7zM432 256a144 144 0 1 1 -288 0 144 144 0 1 1 288 0z"/><path fill="currentColor" d="M288 192c0 35.3-28.7 64-64 64-11.5 0-22.3-3-31.7-8.4-1 10.9-.1 22.1 2.9 33.2 13.7 51.2 66.4 81.6 117.6 67.9s81.6-66.4 67.9-117.6c-12.2-45.7-55.5-74.8-101.1-70.8 5.3 9.3 8.4 20.1 8.4 31.7z"/></svg>`,
|
||||
|
||||
tooth: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><path fill="currentColor" d="M145 5.7L224 32 303 5.7C314.3 1.9 326 0 337.9 0 398.7 0 448 49.3 448 110.1l0 68.5c0 29.4-9.5 58.1-27.2 81.6l-1.1 1.5c-12.9 17.2-21.3 37.4-24.3 58.7L373.7 471.9c-3.3 23-23 40.1-46.2 40.1-22.8 0-42.3-16.5-46-39L261.3 351.6c-3-18.2-18.8-31.6-37.3-31.6s-34.2 13.4-37.3 31.6L166.5 473c-3.8 22.5-23.2 39-46 39-23.2 0-42.9-17.1-46.2-40.1L52.6 320.5c-3-21.3-11.4-41.5-24.3-58.7l-1.1-1.5C9.5 236.7 0 208.1 0 178.7l0-68.5C0 49.3 49.3 0 110.1 0 122 0 133.7 1.9 145 5.7z"/></svg>`,
|
||||
};
|
||||
|
||||
export type IconName = keyof typeof icons;
|
||||
|
||||
// Render an icon as an HTML string with given size and color.
|
||||
// Color cascades to paths via fill="currentColor".
|
||||
export const icon = (name: IconName, size = 16, color = 'currentColor'): string => {
|
||||
return icons[name].replace(
|
||||
'<svg',
|
||||
`<svg width="${size}" height="${size}" style="vertical-align:middle;color:${color};flex-shrink:0"`,
|
||||
);
|
||||
};
|
||||
|
||||
// Map a department name to a medical icon. Keyword-based with stethoscope fallback.
|
||||
export const departmentIcon = (department: string): IconName => {
|
||||
const key = department.toLowerCase().replace(/_/g, ' ');
|
||||
if (key.includes('cardio') || key.includes('heart')) return 'heart-pulse';
|
||||
if (key.includes('ortho') || key.includes('bone') || key.includes('spine')) return 'bone';
|
||||
if (key.includes('gyn') || key.includes('obstet') || key.includes('maternity') || key.includes('pregnan')) return 'person-pregnant';
|
||||
if (key.includes('ent') || key.includes('otolaryn') || key.includes('ear') || key.includes('nose') || key.includes('throat')) return 'ear';
|
||||
if (key.includes('pediatric') || key.includes('paediatric') || key.includes('child') || key.includes('neonat')) return 'baby';
|
||||
if (key.includes('neuro') || key.includes('psych') || key.includes('mental')) return 'brain';
|
||||
if (key.includes('ophthal') || key.includes('eye') || key.includes('vision') || key.includes('retina')) return 'eye';
|
||||
if (key.includes('dental') || key.includes('dent') || key.includes('tooth')) return 'tooth';
|
||||
return 'stethoscope';
|
||||
};
|
||||
50
widget-src/src/main.tsx
Normal file
50
widget-src/src/main.tsx
Normal file
@@ -0,0 +1,50 @@
|
||||
import { render } from 'preact';
|
||||
import { initApi, fetchInit } from './api';
|
||||
import { loadTurnstile } from './captcha';
|
||||
import { Widget } from './widget';
|
||||
import type { WidgetConfig } from './types';
|
||||
|
||||
const init = async () => {
|
||||
const script = document.querySelector('script[data-key]') as HTMLScriptElement | null;
|
||||
if (!script) { console.error('[HelixWidget] Missing data-key attribute'); return; }
|
||||
|
||||
const key = script.getAttribute('data-key') ?? '';
|
||||
const baseUrl = script.src.replace(/\/widget\.js.*$/, '');
|
||||
|
||||
initApi(baseUrl, key);
|
||||
|
||||
let config: WidgetConfig;
|
||||
try {
|
||||
config = await fetchInit();
|
||||
} catch (err) {
|
||||
console.error('[HelixWidget] Init failed:', err);
|
||||
return;
|
||||
}
|
||||
|
||||
// Preload Turnstile script so the captcha gate renders quickly on first open.
|
||||
// No-op if siteKey is empty (dev mode — backend fails open).
|
||||
if (config.captchaSiteKey) {
|
||||
loadTurnstile().catch(() => {
|
||||
console.warn('[HelixWidget] Turnstile preload failed — gate will retry on open');
|
||||
});
|
||||
}
|
||||
|
||||
// Create shadow DOM host
|
||||
// No font-family here — we want the widget to inherit from the host page.
|
||||
const host = document.createElement('div');
|
||||
host.id = 'helix-widget-host';
|
||||
host.style.cssText = 'position:fixed;bottom:20px;right:20px;z-index:999999;';
|
||||
document.body.appendChild(host);
|
||||
|
||||
const shadow = host.attachShadow({ mode: 'open' });
|
||||
const mountPoint = document.createElement('div');
|
||||
shadow.appendChild(mountPoint);
|
||||
|
||||
render(<Widget config={config} shadow={shadow} />, mountPoint);
|
||||
};
|
||||
|
||||
if (document.readyState === 'loading') {
|
||||
document.addEventListener('DOMContentLoaded', init);
|
||||
} else {
|
||||
init();
|
||||
}
|
||||
142
widget-src/src/store.tsx
Normal file
142
widget-src/src/store.tsx
Normal file
@@ -0,0 +1,142 @@
|
||||
import { createContext } from 'preact';
|
||||
import { useCallback, useContext, useEffect, useMemo, useState } from 'preact/hooks';
|
||||
import type { ComponentChildren } from 'preact';
|
||||
import { fetchDoctors } from './api';
|
||||
import type { BookingPrefill, Doctor } from './types';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Centralized widget state.
|
||||
//
|
||||
// One source of truth for everything that's shared across the three tabs
|
||||
// (chat, book, contact): visitor identity, active lead, captcha token,
|
||||
// booking prefill handoff, and the doctors roster. Tab-local state (wizard
|
||||
// steps, message lists, form drafts for tab-specific fields) stays in its
|
||||
// own component.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export type Visitor = { name: string; phone: string };
|
||||
|
||||
type WidgetStore = {
|
||||
// Visitor identity — populated by whichever form the user fills first.
|
||||
// Name/phone inputs in every tab bind directly to this.
|
||||
visitor: Visitor;
|
||||
updateVisitor: (patch: Partial<Visitor>) => void;
|
||||
|
||||
// Lead lifecycle. Set after the first backend call that commits the
|
||||
// visitor (chat-start, book, or contact — chat-start is the common case).
|
||||
// When non-null, the chat pre-chat gate auto-skips.
|
||||
leadId: string | null;
|
||||
setLeadId: (id: string | null) => void;
|
||||
|
||||
// Cloudflare Turnstile token from the window-level gate. Consumed by
|
||||
// booking + contact submit flows (chat uses WidgetKeyGuard only).
|
||||
captchaToken: string;
|
||||
setCaptchaToken: (t: string) => void;
|
||||
|
||||
// Transient handoff: when the user picks a slot in the chat widget, this
|
||||
// carries the doctor/date/time into the Book tab so it lands on the
|
||||
// details form with everything preselected. Booking clears it after consuming.
|
||||
bookingPrefill: BookingPrefill | null;
|
||||
setBookingPrefill: (p: BookingPrefill | null) => void;
|
||||
|
||||
// Doctors roster — fetched once when the provider mounts. Replaces the
|
||||
// per-component fetch that used to live in booking.tsx.
|
||||
doctors: Doctor[];
|
||||
doctorsLoading: boolean;
|
||||
doctorsError: string;
|
||||
|
||||
// Unique branch names derived from the doctors roster (via doctor.clinic.clinicName).
|
||||
branches: string[];
|
||||
|
||||
// Currently selected branch. Session-only, shared across chat + book.
|
||||
// Auto-set on mount if exactly one branch exists. Cleared on session end.
|
||||
selectedBranch: string | null;
|
||||
setSelectedBranch: (branch: string | null) => void;
|
||||
};
|
||||
|
||||
const WidgetStoreContext = createContext<WidgetStore | null>(null);
|
||||
|
||||
type ProviderProps = { children: ComponentChildren };
|
||||
|
||||
export const WidgetStoreProvider = ({ children }: ProviderProps) => {
|
||||
const [visitor, setVisitor] = useState<Visitor>({ name: '', phone: '' });
|
||||
const [leadId, setLeadId] = useState<string | null>(null);
|
||||
const [captchaToken, setCaptchaToken] = useState('');
|
||||
const [bookingPrefill, setBookingPrefill] = useState<BookingPrefill | null>(null);
|
||||
const [doctors, setDoctors] = useState<Doctor[]>([]);
|
||||
const [doctorsLoading, setDoctorsLoading] = useState(false);
|
||||
const [doctorsError, setDoctorsError] = useState('');
|
||||
const [selectedBranch, setSelectedBranch] = useState<string | null>(null);
|
||||
|
||||
const updateVisitor = useCallback((patch: Partial<Visitor>) => {
|
||||
setVisitor(prev => ({ ...prev, ...patch }));
|
||||
}, []);
|
||||
|
||||
// Unique branches derived from the doctors roster. Memoized so stable
|
||||
// references flow down to components that depend on it.
|
||||
const branches = useMemo(() => {
|
||||
const set = new Set<string>();
|
||||
for (const d of doctors) {
|
||||
const name = d.clinic?.clinicName?.trim();
|
||||
if (name) set.add(name);
|
||||
}
|
||||
return Array.from(set).sort();
|
||||
}, [doctors]);
|
||||
|
||||
// Single-branch hospitals get silent auto-select. Multi-branch ones leave
|
||||
// selectedBranch null and rely on the chat/booking flows to prompt.
|
||||
useEffect(() => {
|
||||
if (selectedBranch) return;
|
||||
if (branches.length === 1) setSelectedBranch(branches[0]);
|
||||
}, [branches, selectedBranch]);
|
||||
|
||||
// Fetch the doctors roster once on mount. We intentionally don't refetch
|
||||
// unless the widget is fully reloaded — the roster doesn't change during
|
||||
// a single visitor session.
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
setDoctorsLoading(true);
|
||||
setDoctorsError('');
|
||||
fetchDoctors()
|
||||
.then(docs => {
|
||||
if (cancelled) return;
|
||||
setDoctors(docs);
|
||||
setDoctorsLoading(false);
|
||||
})
|
||||
.catch(() => {
|
||||
if (cancelled) return;
|
||||
setDoctorsError('Failed to load doctors');
|
||||
setDoctorsLoading(false);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const store: WidgetStore = {
|
||||
visitor,
|
||||
updateVisitor,
|
||||
leadId,
|
||||
setLeadId,
|
||||
captchaToken,
|
||||
setCaptchaToken,
|
||||
bookingPrefill,
|
||||
setBookingPrefill,
|
||||
doctors,
|
||||
doctorsLoading,
|
||||
doctorsError,
|
||||
branches,
|
||||
selectedBranch,
|
||||
setSelectedBranch,
|
||||
};
|
||||
|
||||
return <WidgetStoreContext.Provider value={store}>{children}</WidgetStoreContext.Provider>;
|
||||
};
|
||||
|
||||
export const useWidgetStore = (): WidgetStore => {
|
||||
const store = useContext(WidgetStoreContext);
|
||||
if (!store) {
|
||||
throw new Error('useWidgetStore must be used inside a WidgetStoreProvider');
|
||||
}
|
||||
return store;
|
||||
};
|
||||
462
widget-src/src/styles.ts
Normal file
462
widget-src/src/styles.ts
Normal file
@@ -0,0 +1,462 @@
|
||||
import type { WidgetConfig } from './types';
|
||||
|
||||
export const getStyles = (config: WidgetConfig) => `
|
||||
/* all: initial isolates the widget from host-page style bleed, but we then
|
||||
explicitly re-enable font-family inheritance so the widget picks up the
|
||||
host page's font stack instead of falling back to system default. */
|
||||
:host {
|
||||
all: initial;
|
||||
font-family: inherit;
|
||||
font-size: 14px;
|
||||
line-height: 1.4;
|
||||
color: #1f2937;
|
||||
}
|
||||
|
||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
input, select, textarea, button { font-family: inherit; font-size: inherit; color: inherit; }
|
||||
|
||||
.widget-bubble {
|
||||
width: 56px; height: 56px; border-radius: 50%;
|
||||
background: #fff; color: ${config.colors.primary};
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
cursor: pointer; border: 1px solid #e5e7eb;
|
||||
box-shadow: 0 6px 20px rgba(17, 24, 39, 0.15), 0 2px 4px rgba(17, 24, 39, 0.08);
|
||||
transition: transform 0.2s, box-shadow 0.2s; outline: none;
|
||||
}
|
||||
.widget-bubble:hover {
|
||||
transform: scale(1.08);
|
||||
box-shadow: 0 10px 28px rgba(17, 24, 39, 0.2), 0 4px 8px rgba(17, 24, 39, 0.1);
|
||||
}
|
||||
.widget-bubble img { width: 32px; height: 32px; border-radius: 6px; }
|
||||
.widget-bubble svg { width: 26px; height: 26px; }
|
||||
|
||||
.widget-panel {
|
||||
width: 380px; height: 520px; border-radius: 16px;
|
||||
background: #fff; box-shadow: 0 8px 32px rgba(0,0,0,0.12);
|
||||
display: flex; flex-direction: column; overflow: hidden;
|
||||
border: 1px solid #e5e7eb; position: absolute; bottom: 68px; right: 0;
|
||||
animation: slideUp 0.25s ease-out;
|
||||
transition: width 0.25s ease, height 0.25s ease, border-radius 0.25s ease;
|
||||
}
|
||||
@keyframes slideUp {
|
||||
from { opacity: 0; transform: translateY(12px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
@keyframes widgetFadeIn {
|
||||
from { opacity: 0; }
|
||||
to { opacity: 1; }
|
||||
}
|
||||
|
||||
/* Maximized modal mode */
|
||||
.widget-backdrop {
|
||||
position: fixed; inset: 0;
|
||||
background: rgba(17, 24, 39, 0.55);
|
||||
backdrop-filter: blur(2px);
|
||||
animation: widgetFadeIn 0.2s ease-out;
|
||||
z-index: 1;
|
||||
}
|
||||
.widget-panel-maximized {
|
||||
position: fixed;
|
||||
top: 50%; left: 50%; right: auto; bottom: auto;
|
||||
transform: translate(-50%, -50%);
|
||||
width: min(960px, 92vw);
|
||||
height: min(720px, 88vh);
|
||||
max-width: 92vw; max-height: 88vh;
|
||||
border-radius: 20px;
|
||||
box-shadow: 0 24px 64px rgba(0,0,0,0.25);
|
||||
z-index: 2;
|
||||
animation: widgetFadeIn 0.2s ease-out;
|
||||
}
|
||||
|
||||
.widget-header {
|
||||
display: flex; align-items: center; gap: 10px;
|
||||
padding: 14px 16px; background: ${config.colors.primary}; color: #fff;
|
||||
}
|
||||
.widget-header img { width: 32px; height: 32px; border-radius: 8px; }
|
||||
.widget-header-text { flex: 1; min-width: 0; }
|
||||
.widget-header-name { font-size: 14px; font-weight: 600; }
|
||||
.widget-header-sub { font-size: 11px; opacity: 0.85; }
|
||||
.widget-header-branch {
|
||||
display: inline-flex; align-items: center; gap: 3px;
|
||||
font-weight: 500;
|
||||
}
|
||||
.widget-header-btn {
|
||||
background: none; border: none; color: #fff; cursor: pointer;
|
||||
padding: 6px; opacity: 0.8; display: flex; align-items: center;
|
||||
justify-content: center; border-radius: 6px; margin-left: 2px;
|
||||
transition: background 0.15s, opacity 0.15s;
|
||||
}
|
||||
.widget-header-btn:hover { opacity: 1; background: rgba(255,255,255,0.15); }
|
||||
|
||||
.widget-tabs {
|
||||
display: flex; border-bottom: 1px solid #e5e7eb; background: #fafafa;
|
||||
}
|
||||
.widget-tab {
|
||||
flex: 1; padding: 10px 0; text-align: center; font-size: 12px;
|
||||
font-weight: 500; cursor: pointer; border: none; background: none;
|
||||
color: #6b7280; border-bottom: 2px solid transparent;
|
||||
transition: all 0.15s; display: inline-flex; align-items: center;
|
||||
justify-content: center; gap: 6px;
|
||||
}
|
||||
.widget-tab.active {
|
||||
color: ${config.colors.primary}; border-bottom-color: ${config.colors.primary};
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.widget-body { flex: 1; overflow-y: auto; padding: 16px; }
|
||||
.widget-panel-maximized .widget-body { padding: 24px 32px; }
|
||||
.widget-panel-maximized .widget-tabs { padding: 0 16px; }
|
||||
.widget-panel-maximized .widget-tab { padding: 14px 0; font-size: 13px; }
|
||||
|
||||
.widget-input {
|
||||
width: 100%; padding: 10px 12px; border: 1px solid #d1d5db;
|
||||
border-radius: 8px; font-size: 13px; outline: none;
|
||||
transition: border-color 0.15s;
|
||||
}
|
||||
.widget-input:focus { border-color: ${config.colors.primary}; }
|
||||
.widget-textarea { resize: vertical; min-height: 60px; font-family: inherit; }
|
||||
.widget-select {
|
||||
width: 100%; padding: 10px 12px; border: 1px solid #d1d5db;
|
||||
border-radius: 8px; font-size: 13px; background: #fff; outline: none;
|
||||
}
|
||||
.widget-label { font-size: 12px; font-weight: 500; color: #374151; margin-bottom: 4px; display: block; }
|
||||
.widget-field { margin-bottom: 12px; }
|
||||
|
||||
.widget-section-title {
|
||||
font-size: 13px; font-weight: 600; color: #1f2937;
|
||||
margin-bottom: 10px; display: flex; align-items: center; gap: 8px;
|
||||
}
|
||||
.widget-section-sub {
|
||||
font-size: 12px; color: #6b7280; margin-bottom: 16px;
|
||||
}
|
||||
.widget-error {
|
||||
color: #dc2626; font-size: 12px; margin-bottom: 8px;
|
||||
padding: 8px 10px; background: #fef2f2; border-radius: 6px;
|
||||
border: 1px solid #fecaca;
|
||||
}
|
||||
|
||||
.widget-btn {
|
||||
width: 100%; padding: 10px 16px; border: none; border-radius: 8px;
|
||||
font-size: 13px; font-weight: 600; cursor: pointer;
|
||||
transition: opacity 0.15s; color: #fff; background: ${config.colors.primary};
|
||||
}
|
||||
.widget-btn:hover { opacity: 0.9; }
|
||||
.widget-btn:disabled { opacity: 0.5; cursor: not-allowed; }
|
||||
.widget-btn-secondary { background: #f3f4f6; color: #374151; }
|
||||
.widget-btn-with-icon {
|
||||
display: inline-flex; align-items: center; justify-content: center; gap: 6px;
|
||||
}
|
||||
.widget-btn-row {
|
||||
display: flex; gap: 8px; margin-top: 12px;
|
||||
}
|
||||
.widget-btn-row > .widget-btn { flex: 1; }
|
||||
|
||||
/* Row buttons — department list, doctor list, etc. */
|
||||
.widget-row-btn {
|
||||
width: 100%; display: flex; align-items: center; gap: 12px;
|
||||
padding: 12px 14px; margin-bottom: 6px; border: 1px solid #e5e7eb;
|
||||
border-radius: 10px; background: #fff; cursor: pointer;
|
||||
text-align: left; color: #1f2937; transition: all 0.15s;
|
||||
font-family: inherit;
|
||||
}
|
||||
.widget-row-btn:hover {
|
||||
border-color: ${config.colors.primary};
|
||||
background: ${config.colors.primaryLight};
|
||||
}
|
||||
.widget-row-btn.widget-row-btn-stack { align-items: flex-start; }
|
||||
.widget-row-icon {
|
||||
display: inline-flex; align-items: center; justify-content: center;
|
||||
width: 32px; height: 32px; border-radius: 8px;
|
||||
background: ${config.colors.primaryLight}; color: ${config.colors.primary};
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.widget-row-main { flex: 1; min-width: 0; }
|
||||
.widget-row-label { font-size: 13px; font-weight: 600; color: #1f2937; }
|
||||
.widget-row-sub { font-size: 11px; color: #6b7280; margin-top: 2px; }
|
||||
.widget-row-chevron {
|
||||
display: inline-flex; color: #9ca3af; flex-shrink: 0;
|
||||
}
|
||||
.widget-row-btn:hover .widget-row-chevron { color: ${config.colors.primary}; }
|
||||
|
||||
.widget-slots {
|
||||
display: grid; grid-template-columns: repeat(3, 1fr); gap: 6px; margin: 8px 0;
|
||||
}
|
||||
.widget-slot {
|
||||
padding: 8px; text-align: center; font-size: 12px; border-radius: 6px;
|
||||
border: 1px solid #e5e7eb; cursor: pointer; background: #fff;
|
||||
transition: all 0.15s;
|
||||
}
|
||||
.widget-slot:hover { border-color: ${config.colors.primary}; }
|
||||
.widget-slot.selected { background: ${config.colors.primary}; color: #fff; border-color: ${config.colors.primary}; }
|
||||
.widget-slot.unavailable { opacity: 0.4; cursor: not-allowed; text-decoration: line-through; }
|
||||
|
||||
.widget-success {
|
||||
text-align: center; padding: 32px 16px;
|
||||
display: flex; flex-direction: column; align-items: center;
|
||||
}
|
||||
.widget-success-icon {
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
width: 80px; height: 80px; border-radius: 50%;
|
||||
background: #ecfdf5; margin-bottom: 16px;
|
||||
}
|
||||
.widget-success-title { font-size: 16px; font-weight: 600; color: #059669; margin-bottom: 8px; }
|
||||
.widget-success-text { font-size: 13px; color: #6b7280; line-height: 1.6; }
|
||||
|
||||
/* Chat empty state */
|
||||
.chat-empty {
|
||||
text-align: center; padding: 32px 8px 16px;
|
||||
}
|
||||
.chat-intro {
|
||||
padding: 24px 4px 8px;
|
||||
display: flex; flex-direction: column;
|
||||
}
|
||||
.chat-intro .chat-empty-icon { align-self: center; }
|
||||
.chat-intro .chat-empty-title { text-align: center; font-size: 15px; font-weight: 600; color: #1f2937; margin-bottom: 6px; }
|
||||
.chat-intro .chat-empty-text { text-align: center; font-size: 12px; color: #6b7280; margin-bottom: 20px; line-height: 1.5; }
|
||||
.chat-empty-icon {
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
.chat-empty-title {
|
||||
font-size: 15px; font-weight: 600; color: #1f2937; margin-bottom: 6px;
|
||||
}
|
||||
.chat-empty-text {
|
||||
font-size: 12px; color: #6b7280; margin-bottom: 18px; line-height: 1.5;
|
||||
}
|
||||
|
||||
.chat-messages { flex: 1; overflow-y: auto; padding: 12px 0; }
|
||||
.chat-msg { margin-bottom: 10px; display: flex; }
|
||||
.chat-msg.user { justify-content: flex-end; }
|
||||
.chat-msg.assistant { justify-content: flex-start; }
|
||||
.chat-msg-stack {
|
||||
display: flex; flex-direction: column; gap: 6px;
|
||||
max-width: 85%;
|
||||
}
|
||||
.chat-msg.user .chat-msg-stack { align-items: flex-end; }
|
||||
.chat-msg.assistant .chat-msg-stack { align-items: flex-start; }
|
||||
.chat-bubble {
|
||||
padding: 10px 14px; border-radius: 12px;
|
||||
font-size: 13px; line-height: 1.5; white-space: pre-wrap; word-break: break-word;
|
||||
}
|
||||
.chat-msg.user .chat-bubble { background: ${config.colors.primary}; color: #fff; border-bottom-right-radius: 4px; }
|
||||
.chat-msg.assistant .chat-bubble { background: #f3f4f6; color: #1f2937; border-bottom-left-radius: 4px; }
|
||||
|
||||
/* Typing indicator (animated dots) */
|
||||
.chat-typing-dots {
|
||||
display: inline-flex; gap: 4px; align-items: center;
|
||||
padding: 2px 0;
|
||||
}
|
||||
.chat-typing-dots > span {
|
||||
width: 6px; height: 6px; border-radius: 50%;
|
||||
background: #9ca3af; display: inline-block;
|
||||
animation: chatDot 1.4s ease-in-out infinite both;
|
||||
}
|
||||
.chat-typing-dots > span:nth-child(2) { animation-delay: 0.16s; }
|
||||
.chat-typing-dots > span:nth-child(3) { animation-delay: 0.32s; }
|
||||
@keyframes chatDot {
|
||||
0%, 80%, 100% { transform: translateY(0); opacity: 0.35; }
|
||||
40% { transform: translateY(-4px); opacity: 1; }
|
||||
}
|
||||
|
||||
/* Generic chat widget (tool UI) container */
|
||||
.chat-widget {
|
||||
background: #fff; border: 1px solid #e5e7eb; border-radius: 12px;
|
||||
padding: 12px; font-size: 12px; color: #1f2937;
|
||||
width: 100%; max-width: 300px;
|
||||
}
|
||||
.chat-widget-title {
|
||||
font-size: 12px; font-weight: 600; color: #374151;
|
||||
display: flex; align-items: center; gap: 6px;
|
||||
margin-bottom: 8px; text-transform: uppercase; letter-spacing: 0.03em;
|
||||
}
|
||||
.chat-widget-loading {
|
||||
display: inline-flex; align-items: center; gap: 8px;
|
||||
padding: 8px 12px; background: #f3f4f6; border-radius: 10px;
|
||||
font-size: 12px; color: #6b7280;
|
||||
}
|
||||
.chat-widget-loading-label { font-style: italic; }
|
||||
.chat-widget-empty { font-size: 12px; color: #6b7280; font-style: italic; }
|
||||
.chat-widget-error { font-size: 12px; color: #dc2626; padding: 8px 12px; background: #fef2f2; border-radius: 8px; border: 1px solid #fecaca; }
|
||||
|
||||
/* Branch picker cards */
|
||||
.chat-widget-branches .chat-widget-branch-card {
|
||||
width: 100%; display: block; text-align: left;
|
||||
padding: 10px 12px; margin-bottom: 6px;
|
||||
background: #fff; border: 1px solid #e5e7eb; border-radius: 8px;
|
||||
cursor: pointer; font-family: inherit; transition: all 0.15s;
|
||||
}
|
||||
.chat-widget-branches .chat-widget-branch-card:last-child { margin-bottom: 0; }
|
||||
.chat-widget-branches .chat-widget-branch-card:hover {
|
||||
border-color: ${config.colors.primary};
|
||||
background: ${config.colors.primaryLight};
|
||||
}
|
||||
.chat-widget-branch-name { font-size: 13px; font-weight: 600; color: #1f2937; margin-bottom: 2px; }
|
||||
.chat-widget-branch-meta { font-size: 11px; color: #6b7280; }
|
||||
|
||||
/* Department chip grid */
|
||||
.chat-widget-dept-grid {
|
||||
display: flex; flex-wrap: wrap; gap: 6px;
|
||||
}
|
||||
.chat-widget-dept-chip {
|
||||
display: inline-flex; align-items: center; gap: 6px;
|
||||
padding: 6px 10px; border-radius: 999px;
|
||||
border: 1px solid ${config.colors.primary};
|
||||
background: ${config.colors.primaryLight};
|
||||
color: ${config.colors.primary};
|
||||
font-size: 11px; font-weight: 500; cursor: pointer;
|
||||
font-family: inherit; transition: all 0.15s;
|
||||
}
|
||||
.chat-widget-dept-chip:hover {
|
||||
background: ${config.colors.primary}; color: #fff;
|
||||
}
|
||||
|
||||
/* Doctor cards */
|
||||
.chat-widget-doctor-card {
|
||||
padding: 10px; background: #f9fafb; border-radius: 8px;
|
||||
border: 1px solid #f3f4f6; margin-bottom: 6px;
|
||||
}
|
||||
.chat-widget-doctor-card:last-child { margin-bottom: 0; }
|
||||
.chat-widget-doctor-name { font-size: 13px; font-weight: 600; color: #1f2937; margin-bottom: 2px; }
|
||||
.chat-widget-doctor-meta { font-size: 11px; color: #6b7280; line-height: 1.4; }
|
||||
.chat-widget-doctor-action {
|
||||
margin-top: 8px; width: 100%;
|
||||
display: inline-flex; align-items: center; justify-content: center; gap: 6px;
|
||||
padding: 6px 10px; font-size: 11px; font-weight: 600;
|
||||
color: ${config.colors.primary};
|
||||
background: #fff;
|
||||
border: 1px solid ${config.colors.primary};
|
||||
border-radius: 6px; cursor: pointer;
|
||||
font-family: inherit; transition: all 0.15s;
|
||||
}
|
||||
.chat-widget-doctor-action:hover {
|
||||
background: ${config.colors.primary}; color: #fff;
|
||||
}
|
||||
|
||||
/* Clinic timings widget */
|
||||
.chat-widget-timings .chat-widget-timing-dept {
|
||||
margin-bottom: 10px; padding-bottom: 8px;
|
||||
border-bottom: 1px solid #f3f4f6;
|
||||
}
|
||||
.chat-widget-timings .chat-widget-timing-dept:last-child {
|
||||
margin-bottom: 0; padding-bottom: 0; border-bottom: 0;
|
||||
}
|
||||
.chat-widget-timing-dept-name {
|
||||
display: flex; align-items: center; gap: 6px;
|
||||
font-size: 12px; font-weight: 600; color: ${config.colors.primary};
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
.chat-widget-timing-row {
|
||||
padding: 4px 0 4px 22px;
|
||||
}
|
||||
.chat-widget-timing-doctor {
|
||||
font-size: 12px; font-weight: 500; color: #1f2937;
|
||||
}
|
||||
.chat-widget-timing-hours {
|
||||
font-size: 11px; color: #4b5563; line-height: 1.4;
|
||||
}
|
||||
.chat-widget-timing-clinic {
|
||||
font-size: 11px; color: #9ca3af; font-style: italic;
|
||||
}
|
||||
|
||||
/* Slots grid widget */
|
||||
.chat-widget-slots-doctor { font-size: 13px; font-weight: 600; color: #1f2937; }
|
||||
.chat-widget-slots-meta { font-size: 11px; color: #6b7280; margin-bottom: 8px; }
|
||||
.chat-widget-slots-grid {
|
||||
display: grid; grid-template-columns: repeat(3, 1fr); gap: 6px;
|
||||
}
|
||||
.chat-widget-slot-btn {
|
||||
padding: 8px 6px; font-size: 12px; font-weight: 500;
|
||||
color: ${config.colors.primary};
|
||||
background: ${config.colors.primaryLight};
|
||||
border: 1px solid ${config.colors.primary};
|
||||
border-radius: 6px; cursor: pointer;
|
||||
font-family: inherit; transition: all 0.15s;
|
||||
}
|
||||
.chat-widget-slot-btn:hover {
|
||||
background: ${config.colors.primary}; color: #fff;
|
||||
}
|
||||
.chat-widget-slot-btn.unavailable {
|
||||
color: #9ca3af; background: #f3f4f6;
|
||||
border-color: #e5e7eb; cursor: not-allowed;
|
||||
text-decoration: line-through;
|
||||
}
|
||||
|
||||
/* Booking suggestion card */
|
||||
.chat-widget-booking {
|
||||
display: flex; gap: 12px; align-items: flex-start;
|
||||
background: ${config.colors.primaryLight};
|
||||
border-color: ${config.colors.primary};
|
||||
}
|
||||
.chat-widget-booking-icon {
|
||||
flex-shrink: 0; width: 40px; height: 40px;
|
||||
border-radius: 10px; background: #fff;
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
color: ${config.colors.primary};
|
||||
}
|
||||
.chat-widget-booking-body { flex: 1; min-width: 0; }
|
||||
.chat-widget-booking-title { font-size: 13px; font-weight: 600; color: #1f2937; margin-bottom: 2px; }
|
||||
.chat-widget-booking-reason { font-size: 12px; color: #4b5563; line-height: 1.5; margin-bottom: 6px; }
|
||||
.chat-widget-booking-dept { font-size: 11px; color: ${config.colors.primary}; font-weight: 500; margin-bottom: 8px; }
|
||||
.chat-widget-booking .widget-btn { padding: 8px 14px; font-size: 12px; }
|
||||
|
||||
.chat-input-row { display: flex; gap: 8px; padding-top: 8px; border-top: 1px solid #e5e7eb; }
|
||||
.chat-input { flex: 1; }
|
||||
.chat-send {
|
||||
width: 36px; height: 36px; border-radius: 8px;
|
||||
background: ${config.colors.primary}; color: #fff;
|
||||
border: none; cursor: pointer; display: flex;
|
||||
align-items: center; justify-content: center;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.chat-send:hover { opacity: 0.9; }
|
||||
.chat-send:disabled { opacity: 0.5; cursor: not-allowed; }
|
||||
|
||||
.quick-actions { display: flex; flex-wrap: wrap; gap: 6px; justify-content: center; margin-bottom: 12px; }
|
||||
.quick-action {
|
||||
padding: 6px 12px; border-radius: 16px; font-size: 11px;
|
||||
border: 1px solid ${config.colors.primary}; color: ${config.colors.primary};
|
||||
background: ${config.colors.primaryLight}; cursor: pointer;
|
||||
transition: all 0.15s; font-family: inherit;
|
||||
}
|
||||
.quick-action:hover { background: ${config.colors.primary}; color: #fff; }
|
||||
|
||||
.widget-steps { display: flex; gap: 4px; margin-bottom: 16px; }
|
||||
.widget-step {
|
||||
flex: 1; height: 3px; border-radius: 2px; background: #e5e7eb;
|
||||
}
|
||||
.widget-step.active { background: ${config.colors.primary}; }
|
||||
.widget-step.done { background: #059669; }
|
||||
|
||||
/* Captcha gate — full-panel verification screen */
|
||||
.widget-captcha-gate {
|
||||
flex: 1; display: flex; flex-direction: column; align-items: center;
|
||||
justify-content: center; padding: 32px 24px; text-align: center;
|
||||
background: #fafafa;
|
||||
}
|
||||
.widget-captcha-gate-icon {
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
width: 96px; height: 96px; border-radius: 50%;
|
||||
background: ${config.colors.primaryLight}; margin-bottom: 20px;
|
||||
}
|
||||
.widget-captcha-gate-title {
|
||||
font-size: 17px; font-weight: 600; color: #1f2937; margin-bottom: 8px;
|
||||
}
|
||||
.widget-captcha-gate-text {
|
||||
font-size: 13px; color: #6b7280; margin-bottom: 24px; line-height: 1.5;
|
||||
max-width: 280px;
|
||||
}
|
||||
.widget-captcha {
|
||||
display: flex; flex-direction: column; align-items: center;
|
||||
gap: 8px; width: 100%;
|
||||
}
|
||||
/* Placeholder reserves space for the Turnstile widget which is portaled to
|
||||
document.body (light DOM) and visually positioned over this element. */
|
||||
.widget-captcha-mount {
|
||||
width: 300px; height: 65px;
|
||||
display: block;
|
||||
}
|
||||
.widget-captcha-status {
|
||||
font-size: 11px; color: #6b7280; text-align: center;
|
||||
}
|
||||
.widget-captcha-error { color: #dc2626; }
|
||||
`;
|
||||
94
widget-src/src/types.ts
Normal file
94
widget-src/src/types.ts
Normal file
@@ -0,0 +1,94 @@
|
||||
export type WidgetConfig = {
|
||||
brand: { name: string; logo: string };
|
||||
colors: { primary: string; primaryLight: string; text: string; textLight: string };
|
||||
captchaSiteKey: string;
|
||||
};
|
||||
|
||||
export type Doctor = {
|
||||
id: string;
|
||||
name: string;
|
||||
fullName: { firstName: string; lastName: string };
|
||||
department: string;
|
||||
specialty: string;
|
||||
visitingHours: string;
|
||||
consultationFeeNew: { amountMicros: number; currencyCode: string } | null;
|
||||
clinic: { clinicName: string } | null;
|
||||
};
|
||||
|
||||
export type TimeSlot = {
|
||||
time: string;
|
||||
available: boolean;
|
||||
};
|
||||
|
||||
// A doctor card rendered inside a show_doctors tool result.
|
||||
export type ChatDoctor = {
|
||||
id: string;
|
||||
name: string;
|
||||
specialty: string | null;
|
||||
visitingHours: string | null;
|
||||
clinic: string | null;
|
||||
};
|
||||
|
||||
export type ChatSlot = { time: string; available: boolean };
|
||||
|
||||
export type ClinicTimingDept = {
|
||||
name: string;
|
||||
entries: Array<{ name: string; hours: string; clinic: string | null }>;
|
||||
};
|
||||
|
||||
export type BranchOption = {
|
||||
name: string;
|
||||
doctorCount: number;
|
||||
departmentCount: number;
|
||||
};
|
||||
|
||||
// Per-tool output payload shapes (matching what the backend tool.execute returns).
|
||||
export type ToolOutputs = {
|
||||
pick_branch: { branches: BranchOption[] };
|
||||
list_departments: { branch: string | null; departments: string[] };
|
||||
show_clinic_timings: { branch: string | null; departments: ClinicTimingDept[] };
|
||||
show_doctors: { department: string; branch: string | null; doctors: ChatDoctor[] };
|
||||
show_doctor_slots: {
|
||||
doctor: { id: string; name: string; department: string | null; clinic: string | null } | null;
|
||||
date: string;
|
||||
slots: ChatSlot[];
|
||||
error?: string;
|
||||
};
|
||||
suggest_booking: { reason: string; department: string | null };
|
||||
};
|
||||
|
||||
// Seed data passed from chat → booking flow when a visitor picks a slot.
|
||||
export type BookingPrefill = {
|
||||
doctorId: string;
|
||||
date: string;
|
||||
time: string;
|
||||
};
|
||||
|
||||
export type ToolName = keyof ToolOutputs;
|
||||
|
||||
// UI parts are Vercel-style: an assistant message is a sequence of
|
||||
// TextPart | ToolPart that we render in order.
|
||||
export type ChatTextPart = {
|
||||
type: 'text';
|
||||
text: string;
|
||||
state: 'streaming' | 'done';
|
||||
};
|
||||
|
||||
export type ChatToolPart = {
|
||||
type: 'tool';
|
||||
toolCallId: string;
|
||||
toolName: ToolName | string; // unknown tool names are rendered as fallback
|
||||
state: 'input-streaming' | 'input-available' | 'output-available' | 'output-error';
|
||||
input?: any;
|
||||
output?: any;
|
||||
errorText?: string;
|
||||
};
|
||||
|
||||
export type ChatPart = ChatTextPart | ChatToolPart;
|
||||
|
||||
export type ChatMessage = {
|
||||
id: string;
|
||||
role: 'user' | 'assistant';
|
||||
parts: ChatPart[];
|
||||
};
|
||||
|
||||
164
widget-src/src/widget.tsx
Normal file
164
widget-src/src/widget.tsx
Normal file
@@ -0,0 +1,164 @@
|
||||
import { useEffect, useState } from 'preact/hooks';
|
||||
import type { WidgetConfig } from './types';
|
||||
import { getStyles } from './styles';
|
||||
import { IconSpan } from './icon-span';
|
||||
import { Captcha } from './captcha';
|
||||
import { Chat } from './chat';
|
||||
import { Booking } from './booking';
|
||||
import { Contact } from './contact';
|
||||
import { WidgetStoreProvider, useWidgetStore } from './store';
|
||||
|
||||
type Tab = 'chat' | 'book' | 'contact';
|
||||
|
||||
type WidgetProps = {
|
||||
config: WidgetConfig;
|
||||
shadow: ShadowRoot;
|
||||
};
|
||||
|
||||
// Outer wrapper — owns the shadow-DOM style injection and the store provider.
|
||||
// Everything inside WidgetShell reads shared state via useWidgetStore().
|
||||
export const Widget = ({ config, shadow }: WidgetProps) => {
|
||||
useEffect(() => {
|
||||
const style = document.createElement('style');
|
||||
style.textContent = getStyles(config);
|
||||
shadow.appendChild(style);
|
||||
return () => { shadow.removeChild(style); };
|
||||
}, [config, shadow]);
|
||||
|
||||
return (
|
||||
<WidgetStoreProvider>
|
||||
<WidgetShell config={config} shadow={shadow} />
|
||||
</WidgetStoreProvider>
|
||||
);
|
||||
};
|
||||
|
||||
const WidgetShell = ({ config, shadow }: WidgetProps) => {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [tab, setTab] = useState<Tab>('chat');
|
||||
const [maximized, setMaximized] = useState(false);
|
||||
const { captchaToken, setCaptchaToken, selectedBranch } = useWidgetStore();
|
||||
|
||||
// Maximized mode: host becomes a fullscreen fixed container so the modal
|
||||
// backdrop covers the page. Restored on exit.
|
||||
useEffect(() => {
|
||||
if (!maximized) return;
|
||||
const host = shadow.host as HTMLElement;
|
||||
const prevHostStyle = host.getAttribute('style');
|
||||
host.style.cssText = 'position:fixed;inset:0;z-index:999999;';
|
||||
const prevOverflow = document.body.style.overflow;
|
||||
document.body.style.overflow = 'hidden';
|
||||
return () => {
|
||||
if (prevHostStyle !== null) host.setAttribute('style', prevHostStyle);
|
||||
else host.removeAttribute('style');
|
||||
document.body.style.overflow = prevOverflow;
|
||||
};
|
||||
}, [maximized, shadow]);
|
||||
|
||||
// Esc to exit maximized mode.
|
||||
useEffect(() => {
|
||||
if (!maximized) return;
|
||||
const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') setMaximized(false); };
|
||||
window.addEventListener('keydown', onKey);
|
||||
return () => window.removeEventListener('keydown', onKey);
|
||||
}, [maximized]);
|
||||
|
||||
const requiresGate = Boolean(config.captchaSiteKey) && !captchaToken;
|
||||
|
||||
const close = () => {
|
||||
setMaximized(false);
|
||||
setOpen(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
{/* Floating bubble */}
|
||||
{!open && (
|
||||
<button class="widget-bubble" onClick={() => setOpen(true)} aria-label="Open chat">
|
||||
{config.brand.logo ? (
|
||||
<img src={config.brand.logo} alt={config.brand.name} />
|
||||
) : (
|
||||
<IconSpan name="message-dots" size={26} color={config.colors.primary} />
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
|
||||
{/* Panel */}
|
||||
{open && (
|
||||
<>
|
||||
{maximized && <div class="widget-backdrop" onClick={() => setMaximized(false)} />}
|
||||
<div class={`widget-panel ${maximized ? 'widget-panel-maximized' : ''}`}>
|
||||
{/* Header */}
|
||||
<div class="widget-header">
|
||||
{config.brand.logo && <img src={config.brand.logo} alt="" />}
|
||||
<div class="widget-header-text">
|
||||
<div class="widget-header-name">{config.brand.name}</div>
|
||||
<div class="widget-header-sub">
|
||||
We're here to help
|
||||
{selectedBranch && (
|
||||
<>
|
||||
{' • '}
|
||||
<span class="widget-header-branch">
|
||||
<IconSpan name="location-dot" size={10} color="#fff" />
|
||||
{selectedBranch}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
class="widget-header-btn"
|
||||
onClick={() => setMaximized(m => !m)}
|
||||
aria-label={maximized ? 'Restore' : 'Maximize'}
|
||||
title={maximized ? 'Restore' : 'Maximize'}
|
||||
>
|
||||
<IconSpan
|
||||
name={maximized ? 'down-left-and-up-right-to-center' : 'up-right-and-down-left-from-center'}
|
||||
size={14}
|
||||
color="#fff"
|
||||
/>
|
||||
</button>
|
||||
<button class="widget-header-btn" onClick={close} aria-label="Close" title="Close">
|
||||
<IconSpan name="xmark" size={16} color="#fff" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{requiresGate ? (
|
||||
<div class="widget-captcha-gate">
|
||||
<div class="widget-captcha-gate-icon">
|
||||
<IconSpan name="shield-check" size={56} color={config.colors.primary} />
|
||||
</div>
|
||||
<div class="widget-captcha-gate-title">Quick security check</div>
|
||||
<div class="widget-captcha-gate-text">
|
||||
Please verify you're not a bot to continue.
|
||||
</div>
|
||||
<Captcha siteKey={config.captchaSiteKey} onToken={setCaptchaToken} />
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{/* Tabs */}
|
||||
<div class="widget-tabs">
|
||||
<button class={`widget-tab ${tab === 'chat' ? 'active' : ''}`} onClick={() => setTab('chat')}>
|
||||
<IconSpan name="message-dots" size={14} /> Chat
|
||||
</button>
|
||||
<button class={`widget-tab ${tab === 'book' ? 'active' : ''}`} onClick={() => setTab('book')}>
|
||||
<IconSpan name="calendar" size={14} /> Book
|
||||
</button>
|
||||
<button class={`widget-tab ${tab === 'contact' ? 'active' : ''}`} onClick={() => setTab('contact')}>
|
||||
<IconSpan name="phone" size={14} /> Contact
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Body */}
|
||||
<div class="widget-body">
|
||||
{tab === 'chat' && <Chat onRequestBooking={() => setTab('book')} />}
|
||||
{tab === 'book' && <Booking />}
|
||||
{tab === 'contact' && <Contact />}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
41
widget-src/test.html
Normal file
41
widget-src/test.html
Normal file
@@ -0,0 +1,41 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Global Hospital — Widget Test</title>
|
||||
<style>
|
||||
body { font-family: -apple-system, sans-serif; max-width: 800px; margin: 0 auto; padding: 40px; color: #1f2937; }
|
||||
h1 { font-size: 28px; margin-bottom: 8px; }
|
||||
p { color: #6b7280; line-height: 1.6; }
|
||||
.hero { background: #f0f9ff; border-radius: 12px; padding: 40px; margin: 40px 0; }
|
||||
.hero h2 { color: #1e40af; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>🏥 Global Hospital, Bangalore</h1>
|
||||
<p>Welcome to Global Hospital — Bangalore's leading multi-specialty healthcare provider.</p>
|
||||
|
||||
<div class="hero">
|
||||
<h2>Book Your Appointment Online</h2>
|
||||
<p>Click the chat bubble in the bottom-right corner to talk to our AI assistant, book an appointment, or request a callback.</p>
|
||||
</div>
|
||||
|
||||
<h3>Our Departments</h3>
|
||||
<ul>
|
||||
<li>Cardiology</li>
|
||||
<li>Orthopedics</li>
|
||||
<li>Gynecology</li>
|
||||
<li>ENT</li>
|
||||
<li>General Medicine</li>
|
||||
</ul>
|
||||
|
||||
<p style="margin-top: 40px; font-size: 12px; color: #9ca3af;">
|
||||
This is a test page for the Helix Engage website widget.
|
||||
The widget loads from the sidecar and renders in a shadow DOM.
|
||||
</p>
|
||||
|
||||
<!-- Replace SITE_KEY with the generated key -->
|
||||
<script src="http://localhost:4100/widget.js" data-key="8197d39c9ad946ef.31e3b1f492a7380f77ea0c90d2f86d5d4b1ac8f70fd01423ac3d85b87d9aa511"></script>
|
||||
</body>
|
||||
</html>
|
||||
14
widget-src/tsconfig.json
Normal file
14
widget-src/tsconfig.json
Normal file
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"jsx": "react-jsx",
|
||||
"jsxImportSource": "preact",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"outDir": "dist",
|
||||
"skipLibCheck": true
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
22
widget-src/vite.config.ts
Normal file
22
widget-src/vite.config.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import { defineConfig } from 'vite';
|
||||
import preact from '@preact/preset-vite';
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [preact()],
|
||||
build: {
|
||||
lib: {
|
||||
entry: 'src/main.tsx',
|
||||
name: 'HelixWidget',
|
||||
fileName: () => 'widget.js',
|
||||
formats: ['iife'],
|
||||
},
|
||||
outDir: '../public',
|
||||
emptyOutDir: false,
|
||||
minify: 'esbuild',
|
||||
rollupOptions: {
|
||||
output: {
|
||||
inlineDynamicImports: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
Reference in New Issue
Block a user