forked from pagevamp/copilot-profile-manager
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroute.ts
180 lines (156 loc) · 7.62 KB
/
route.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
import { NextRequest, NextResponse } from 'next/server';
import { ClientProfileUpdatesRequestSchema, ParsedClientProfileUpdatesResponse } from '@/types/clientProfileUpdates';
import { CopilotAPI } from '@/utils/copilotApiUtils';
import { handleError, respondError } from '@/utils/common';
import { ClientProfileUpdatesService } from '@/app/api/client-profile-updates/services/clientProfileUpdates.service';
import { ClientResponse, CompanyResponse } from '@/types/common';
import { z } from 'zod';
import { createLookup, createMapLookup, getObjectDifference, getSelectedOptions } from '@/lib/helper';
export async function POST(request: NextRequest) {
const data = await request.json();
const clientProfileUpdateRequest = ClientProfileUpdatesRequestSchema.safeParse(data);
if (!clientProfileUpdateRequest.success) {
return NextResponse.json(clientProfileUpdateRequest.error.issues, { status: 422 });
}
try {
//todo: check access
const copilotClient = new CopilotAPI(clientProfileUpdateRequest.data.token);
const client: ClientResponse = await copilotClient.getClient(clientProfileUpdateRequest.data.clientId);
for (const key of Object.keys(clientProfileUpdateRequest.data.form)) {
// Yes, this code sucks. No, I don't have an option right now
// TODO: Cleanup once we support better fields for address
const data = clientProfileUpdateRequest?.data?.form?.[key];
const addressableData = data as { fullAddress: string };
if (addressableData?.fullAddress) {
clientProfileUpdateRequest.data.form[key] = addressableData.fullAddress;
}
}
const clientUpdateResponse = await copilotClient.updateClient(clientProfileUpdateRequest.data.clientId, {
// @ts-expect-error temporary support for address type
customFields: clientProfileUpdateRequest.data.form,
});
// NOTE: If you pass empty string as value to a custom field, that key will be deleted from the copilot api
// (Probably because it's built in Go and Go does the weird zero value cast thing)
// So sending an empty "" is the same as nil
clientUpdateResponse.customFields = { ...clientProfileUpdateRequest.data.form, ...clientUpdateResponse.customFields };
const changedFields = getObjectDifference(
(clientUpdateResponse.customFields ?? {}) as Record<string, any>,
(client.customFields ?? {}) as Record<string, any>,
);
if (Object.keys(changedFields).length === 0) {
return NextResponse.json({ message: 'No changed fields detected' });
}
const service = new ClientProfileUpdatesService();
console.log(`Processing profile update for client: ${client}`);
// First, check if the copilot's custom fields and our recent history are in sync
for (const key of Object.keys(changedFields)) {
const updateHistory = await new ClientProfileUpdatesService().getUpdateHistory(key, client.id, new Date());
console.log('Processing updateHistory:', updateHistory);
const lastHistory = updateHistory?.[0]?.changedFields?.[key];
console.log('Last history:', lastHistory);
const areHistoriesEmpty =
// Case where both have empty values. Make sure to strict check so we don't consider 0 input as empty history
(lastHistory === undefined || lastHistory === null || lastHistory === '') &&
client.customFields?.[key] === undefined;
if (areHistoriesEmpty) continue;
if (client.customFields?.[key] !== lastHistory) {
const newFullAddress = (client.customFields?.[key] as { fullAddress: string })?.fullAddress;
const addressableLastHistory = (lastHistory as { fullAddress: string })?.fullAddress;
if (newFullAddress && addressableLastHistory && newFullAddress === addressableLastHistory) {
return NextResponse.json({ message: 'No changed fields detected' });
}
// If not, fix it.
await service.save({
clientId: clientProfileUpdateRequest.data.clientId,
companyId: clientProfileUpdateRequest.data.companyId,
portalId: clientProfileUpdateRequest.data.portalId,
customFields: { ...(clientUpdateResponse.customFields ?? {}), [key]: client.customFields?.[key] } as Record<
string,
any
>,
// @ts-expect-error inject key
changedFields: { [key]: client.customFields?.[key] },
wasUpdatedByIU: true,
});
}
}
await service.save({
clientId: clientProfileUpdateRequest.data.clientId,
companyId: clientProfileUpdateRequest.data.companyId,
portalId: clientProfileUpdateRequest.data.portalId,
customFields: (clientUpdateResponse.customFields ?? {}) as Record<string, any>,
changedFields,
});
return NextResponse.json({ message: 'Saved client profile updates along with changed fields' });
} catch (error) {
return handleError(error);
}
}
export async function GET(request: NextRequest) {
const token = request.nextUrl.searchParams.get('token');
const portalId = request.nextUrl.searchParams.get('portalId');
if (!token) {
return respondError('Missing token', 422);
}
if (!portalId) {
return respondError('Missing portalId', 422);
}
try {
const copilotClient = new CopilotAPI(z.string().parse(token));
const [clients, companies, portalCustomFields] = await Promise.all([
copilotClient.getClients(),
copilotClient.getCompanies(),
copilotClient.getCustomFields(),
]);
//todo:: filter companyIds based on currentUser restrictions
const clientProfileUpdates = await new ClientProfileUpdatesService().findMany(portalId, []);
const clientLookup = createLookup(clients.data, 'id');
const companyLookup = createMapLookup(companies.data, 'id');
const parsedClientProfileUpdates: ParsedClientProfileUpdatesResponse[] = clientProfileUpdates.map((update) => {
const client = clientLookup[update.clientId];
const company = companyLookup.get(update.companyId);
let parsedClientProfileUpdate: ParsedClientProfileUpdatesResponse = {
id: update?.id,
client: client ? getClientDetails(client) : undefined,
company: company ? getCompanyDetails(company) : undefined,
lastUpdated: update.createdAt,
};
portalCustomFields.data?.forEach((portalCustomField) => {
if (!portalCustomField) return;
const value = update.customFields[portalCustomField.key] ?? null;
const options = getSelectedOptions(portalCustomField, value || '');
// @ts-ignore
parsedClientProfileUpdate[portalCustomField.name] = {
name: portalCustomField.name,
type: portalCustomField.type,
key: portalCustomField.key,
value: options.length > 0 ? options : value,
isChanged: update.changedFields[portalCustomField.key] === '' || !!update.changedFields[portalCustomField.key],
};
});
return parsedClientProfileUpdate;
});
// If any client is deleted in Copilot, we can't fetch the client data for it.
// Filter them out of the array to only show active client profile updates
const activeClientProfileUpdates = parsedClientProfileUpdates.filter((profile) => !!profile.client);
return NextResponse.json(activeClientProfileUpdates);
} catch (error) {
return handleError(error);
}
}
function getClientDetails(client: ClientResponse) {
return {
id: client?.id,
name: `${client?.givenName} ${client?.familyName}`,
email: client?.email,
avatarImageUrl: client?.avatarImageUrl,
};
}
function getCompanyDetails(company: CompanyResponse) {
return {
id: company?.id,
name: company?.name,
iconImageUrl: company?.iconImageUrl,
fallbackColor: company?.fallbackColor,
};
}