AI Summary not showing appointments fix.

This commit is contained in:
Kartik Datrika
2026-04-16 11:36:10 +05:30
parent 6adb3985cb
commit 973614749b
5 changed files with 702 additions and 433 deletions

View File

@@ -1,88 +1,147 @@
import { Controller, Post, Body, Logger, Headers, HttpException } from '@nestjs/common';
import {
Controller,
Post,
Body,
Logger,
Headers,
HttpException,
} from '@nestjs/common';
import { PlatformGraphqlService } from '../platform/platform-graphql.service';
import { AiEnrichmentService } from '../ai/ai-enrichment.service';
@Controller('api/call')
export class CallLookupController {
private readonly logger = new Logger(CallLookupController.name);
private readonly logger = new Logger(CallLookupController.name);
constructor(
private readonly platform: PlatformGraphqlService,
private readonly ai: AiEnrichmentService,
) {}
constructor(
private readonly platform: PlatformGraphqlService,
private readonly ai: AiEnrichmentService,
) {}
@Post('lookup')
async lookupCaller(
@Body() body: { phoneNumber: string },
@Headers('authorization') authHeader: string,
) {
if (!authHeader) throw new HttpException('Authorization required', 401);
if (!body.phoneNumber) throw new HttpException('phoneNumber required', 400);
@Post('lookup')
async lookupCaller(
@Body() body: { phoneNumber: string },
@Headers('authorization') authHeader: string,
) {
if (!authHeader) throw new HttpException('Authorization required', 401);
if (!body.phoneNumber) throw new HttpException('phoneNumber required', 400);
const phone = body.phoneNumber.replace(/^0+/, '');
this.logger.log(`Looking up caller: ${phone}`);
const phone = body.phoneNumber.replace(/^0+/, '');
this.logger.log(`Looking up caller: ${phone}`);
// Query platform for leads matching this phone number
let lead = null;
let activities: any[] = [];
// Query platform for leads matching this phone number
let lead = null;
let activities: any[] = [];
try {
lead = await this.platform.findLeadByPhoneWithToken(phone, authHeader);
} catch (err) {
this.logger.warn(`Lead lookup failed: ${err}`);
}
if (lead) {
this.logger.log(`Matched lead: ${lead.id}${lead.contactName?.firstName} ${lead.contactName?.lastName}`);
// Get recent activities
try {
activities = await this.platform.getLeadActivitiesWithToken(lead.id, authHeader, 5);
} catch (err) {
this.logger.warn(`Activity fetch failed: ${err}`);
}
// AI enrichment if no existing summary
if (!lead.aiSummary) {
try {
const enrichment = await this.ai.enrichLead({
firstName: lead.contactName?.firstName,
lastName: lead.contactName?.lastName,
leadSource: lead.leadSource ?? undefined,
interestedService: lead.interestedService ?? undefined,
leadStatus: lead.leadStatus ?? undefined,
contactAttempts: lead.contactAttempts ?? undefined,
createdAt: lead.createdAt,
activities: activities.map((a: any) => ({
activityType: a.activityType ?? '',
summary: a.summary ?? '',
})),
});
lead.aiSummary = enrichment.aiSummary;
lead.aiSuggestedAction = enrichment.aiSuggestedAction;
// Persist AI enrichment back to platform
try {
await this.platform.updateLeadWithToken(lead.id, {
aiSummary: enrichment.aiSummary,
aiSuggestedAction: enrichment.aiSuggestedAction,
}, authHeader);
} catch (err) {
this.logger.warn(`Failed to persist AI enrichment: ${err}`);
}
} catch (err) {
this.logger.warn(`AI enrichment failed: ${err}`);
}
}
} else {
this.logger.log(`No lead found for phone ${phone}`);
}
return {
lead,
activities,
matched: lead !== null,
};
try {
lead = await this.platform.findLeadByPhoneWithToken(phone, authHeader);
} catch (err) {
this.logger.warn(`Lead lookup failed: ${err}`);
}
if (lead) {
this.logger.log(
`Matched lead: ${lead.id}${lead.contactName?.firstName} ${lead.contactName?.lastName}`,
);
// Get recent activities
try {
activities = await this.platform.getLeadActivitiesWithToken(
lead.id,
authHeader,
5,
);
} catch (err) {
this.logger.warn(`Activity fetch failed: ${err}`);
}
// Fetch patient context if patientId exists
let patientData = null;
let upcomingAppointments: any[] = [];
if (lead.patientId) {
try {
patientData = await this.platform.getPatientWithToken(
lead.patientId,
authHeader,
);
} catch (err) {
this.logger.warn(`Patient fetch failed: ${err}`);
}
if (patientData) {
try {
upcomingAppointments =
await this.platform.getUpcomingAppointmentsWithToken(
lead.patientId,
authHeader,
3,
);
} catch (err) {
this.logger.warn(`Appointment fetch failed: ${err}`);
}
}
}
// AI enrichment if no existing summary
// generate aiSummary everytime
// if (!lead.aiSummary) {
try {
const enrichment = await this.ai.enrichLead({
firstName: lead.contactName?.firstName,
lastName: lead.contactName?.lastName,
leadSource: lead.leadSource ?? undefined,
interestedService: lead.interestedService ?? undefined,
leadStatus: lead.leadStatus ?? undefined,
contactAttempts: lead.contactAttempts ?? undefined,
createdAt: lead.createdAt,
patient: patientData
? {
age: patientData.dateOfBirth
? Math.floor(
(Date.now() -
new Date(patientData.dateOfBirth).getTime()) /
(1000 * 60 * 60 * 24 * 365.25),
)
: undefined,
type: patientData.patientType,
hasRecords: true,
}
: undefined,
upcomingAppointments,
activities: activities.map((a: any) => ({
activityType: a.activityType ?? '',
summary: a.summary ?? '',
})),
});
lead.aiSummary = enrichment.aiSummary;
lead.aiSuggestedAction = enrichment.aiSuggestedAction;
// Persist AI enrichment back to platform
try {
await this.platform.updateLeadWithToken(
lead.id,
{
aiSummary: enrichment.aiSummary,
aiSuggestedAction: enrichment.aiSuggestedAction,
},
authHeader,
);
} catch (err) {
this.logger.warn(`Failed to persist AI enrichment: ${err}`);
}
} catch (err) {
this.logger.warn(`AI enrichment failed: ${err}`);
}
// }
} else {
this.logger.log(`No lead found for phone ${phone}`);
}
return {
lead,
activities,
matched: lead !== null,
};
}
}