feature/fitlien-add-cors #13

Merged
dhanshas merged 10 commits from feature/fitlien-add-cors into dev 2025-04-09 11:43:54 +00:00

View File

@ -24,7 +24,7 @@ if (!admin.apps.length) {
const corsHandler = cors({ origin: true }); const corsHandler = cors({ origin: true });
export const sendEmailWithAttachment = onRequest({ export const sendEmailWithAttachment = onRequest({
region: process.env.SERVICES_RGN region: '#{SERVICES_RGN}#'
}, async (request: Request, response: express.Response) => { }, async (request: Request, response: express.Response) => {
return corsHandler(request, response, async () => { return corsHandler(request, response, async () => {
try { try {
@ -157,7 +157,7 @@ export const sendEmailMessage = onRequest({
}); });
export const sendSMSMessage = onRequest({ export const sendSMSMessage = onRequest({
region: process.env.SERVICES_RGN region: '#{SERVICES_RGN}#'
}, (request: Request, response: express.Response) => { }, (request: Request, response: express.Response) => {
return corsHandler(request, response, async () => { return corsHandler(request, response, async () => {
@ -181,26 +181,26 @@ export const sendSMSMessage = onRequest({
}); });
export const processNotificationOnCreate = onDocumentCreated({ export const processNotificationOnCreate = onDocumentCreated({
region: process.env.SERVICES_RGN, region: '#{SERVICES_RGN}#',
document: 'notifications/{notificationId}' document: 'notifications/{notificationId}'
}, async (event) => { }, async (event) => {
try { try {
const notification = event.data?.data(); const notification = event.data?.data();
const notificationId = event.params.notificationId; const notificationId = event.params.notificationId;
if (!notification) { if (!notification) {
logger.error(`No data found for notification ${notificationId}`); logger.error(`No data found for notification ${notificationId}`);
return; return;
} }
if (notification.notificationSent === true) { if (notification.notificationSent === true) {
logger.info(`Notification ${notificationId} already sent, skipping.`); logger.info(`Notification ${notificationId} already sent, skipping.`);
return; return;
} }
let userId = null; let userId = null;
let fcmToken = null; let fcmToken = null;
if (notification.userId) { if (notification.userId) {
userId = notification.userId; userId = notification.userId;
const userDoc = await admin.firestore().collection('users').doc(userId).get(); const userDoc = await admin.firestore().collection('users').doc(userId).get();
@ -226,14 +226,14 @@ export const processNotificationOnCreate = onDocumentCreated({
.where('phoneNumber', '==', notification.phoneNumber) .where('phoneNumber', '==', notification.phoneNumber)
.limit(1) .limit(1)
.get(); .get();
if (!userQuery.empty) { if (!userQuery.empty) {
const userDoc = userQuery.docs[0]; const userDoc = userQuery.docs[0];
userId = userDoc.id; userId = userDoc.id;
fcmToken = userDoc.data()?.fcmToken; fcmToken = userDoc.data()?.fcmToken;
} }
} }
if (!fcmToken) { if (!fcmToken) {
logger.error(`FCM token not found for notification ${notificationId}`); logger.error(`FCM token not found for notification ${notificationId}`);
await admin.firestore().collection('notifications').doc(notificationId).update({ await admin.firestore().collection('notifications').doc(notificationId).update({
@ -242,35 +242,35 @@ export const processNotificationOnCreate = onDocumentCreated({
}); });
return; return;
} }
let title = 'New Notification'; let title = 'New Notification';
let body = notification.message || 'You have a new notification'; let body = notification.message || 'You have a new notification';
let data: Record<string, string> = { let data: Record<string, string> = {
type: notification.type, type: notification.type,
}; };
switch (notification.type) { switch (notification.type) {
case 'day_pass_entry': case 'day_pass_entry':
const isAccepted = notification.status === 'ACCEPTED'; const isAccepted = notification.status === 'ACCEPTED';
title = isAccepted ? 'Day Pass Approved' : 'Day Pass Denied'; title = isAccepted ? 'Day Pass Approved' : 'Day Pass Denied';
body = notification.message || (isAccepted ? body = notification.message || (isAccepted ?
`Your day pass has been approved` : `Your day pass has been approved` :
`Your day pass has been denied`); `Your day pass has been denied`);
data.gymName = notification.gymName || ''; data.gymName = notification.gymName || '';
break; break;
case 'trainer_assigned_to_client': case 'trainer_assigned_to_client':
title = 'Trainer Assigned'; title = 'Trainer Assigned';
body = notification.message || `${notification.trainerName} has been assigned as your trainer`; body = notification.message || `${notification.trainerName} has been assigned as your trainer`;
data.trainerName = notification.trainerName || ''; data.trainerName = notification.trainerName || '';
data.membershipId = notification.membershipId || ''; data.membershipId = notification.membershipId || '';
break; break;
case 'client_invitations': case 'client_invitations':
if (notification.userId || notification.invitorId) { if (notification.userId || notification.invitorId) {
const isAccept = notification.status === 'ACCEPTED'; const isAccept = notification.status === 'ACCEPTED';
title = isAccept ? 'Invitation Accepted' : 'Invitation Rejected'; title = isAccept ? 'Invitation Accepted' : 'Invitation Rejected';
body = notification.message || (isAccept ? body = notification.message || (isAccept ?
`The invitation for ${notification.subscriptionName} you shared with ${notification.name} has been accepted` : `The invitation for ${notification.subscriptionName} you shared with ${notification.name} has been accepted` :
`The invitation for ${notification.subscriptionName} you shared with ${notification.name} has been rejected`); `The invitation for ${notification.subscriptionName} you shared with ${notification.name} has been rejected`);
} else if (notification.phoneNumber) { } else if (notification.phoneNumber) {
@ -278,17 +278,17 @@ export const processNotificationOnCreate = onDocumentCreated({
if (notification.status === 'ACCEPTED') { if (notification.status === 'ACCEPTED') {
invitationStatus = 'accepted'; invitationStatus = 'accepted';
title = 'Invitation Accepted'; title = 'Invitation Accepted';
body = notification.message || body = notification.message ||
`You have accepted the invitation from ${notification.name}`; `You have accepted the invitation from ${notification.name}`;
} else if (notification.status === 'REJECTED') { } else if (notification.status === 'REJECTED') {
invitationStatus = 'rejected'; invitationStatus = 'rejected';
title = 'Invitation Rejected'; title = 'Invitation Rejected';
body = notification.message || body = notification.message ||
`You have rejected the invitation from ${notification.name}`; `You have rejected the invitation from ${notification.name}`;
} else if (notification.status === 'PENDING') { } else if (notification.status === 'PENDING') {
invitationStatus = 'pending'; invitationStatus = 'pending';
title = 'New Invitation'; title = 'New Invitation';
body = notification.message || body = notification.message ||
`You have a new invitation pending from ${notification.name}`; `You have a new invitation pending from ${notification.name}`;
} else { } else {
invitationStatus = 'unknown'; invitationStatus = 'unknown';
@ -297,19 +297,19 @@ export const processNotificationOnCreate = onDocumentCreated({
} }
data.status = invitationStatus; data.status = invitationStatus;
} }
data.gymName = notification.gymName || ''; data.gymName = notification.gymName || '';
data.clientEmail = notification.clientEmail || ''; data.clientEmail = notification.clientEmail || '';
data.clientName = notification.name || ''; data.clientName = notification.name || '';
data.invitationId = notification.invitationId || ''; data.invitationId = notification.invitationId || '';
data.subscriptionName = notification.subscriptionName || ''; data.subscriptionName = notification.subscriptionName || '';
break; break;
default: default:
logger.info(`Using default handling for notification type: ${notification.type}`); logger.info(`Using default handling for notification type: ${notification.type}`);
break; break;
} }
const message: admin.messaging.Message = { const message: admin.messaging.Message = {
notification: { notification: {
title: title, title: title,
@ -337,18 +337,18 @@ export const processNotificationOnCreate = onDocumentCreated({
}, },
token: fcmToken, token: fcmToken,
}; };
try { try {
const fcmResponse = await admin.messaging().send(message); const fcmResponse = await admin.messaging().send(message);
logger.info(`FCM notification sent successfully: ${fcmResponse}`); logger.info(`FCM notification sent successfully: ${fcmResponse}`);
await admin.firestore().collection('notifications').doc(notificationId).update({ await admin.firestore().collection('notifications').doc(notificationId).update({
notificationSent: true, notificationSent: true,
sentAt: admin.firestore.FieldValue?.serverTimestamp?.() || new Date() sentAt: admin.firestore.FieldValue?.serverTimestamp?.() || new Date()
}); });
} catch (error) { } catch (error) {
logger.error(`Error sending notification ${notificationId}:`, error); logger.error(`Error sending notification ${notificationId}:`, error);
await admin.firestore().collection('notifications').doc(notificationId).update({ await admin.firestore().collection('notifications').doc(notificationId).update({
notificationError: error instanceof Error ? error.message : String(error), notificationError: error instanceof Error ? error.message : String(error),
updatedAt: admin.firestore.FieldValue?.serverTimestamp?.() || new Date() updatedAt: admin.firestore.FieldValue?.serverTimestamp?.() || new Date()
@ -569,3 +569,44 @@ export const getPlacesAutocomplete = onRequest({
} }
}); });
}); });
export const getPlaceDetails = onRequest({
region: '#{SERVICES_RGN}#'
}, async (request: Request, response: express.Response) => {
return corsHandler(request, response, async () => {
try {
const { place_id, fields } = request.query;
if (!place_id) {
response.status(400).json({
error: 'place_id parameter is required'
});
return;
}
const apiKey = process.env.GOOGLE_MAPS_API_KEY;
if (!apiKey) {
logger.error('Google Places API key is not configured');
response.status(500).json({ error: 'Server configuration error' });
return;
}
const url = 'https://maps.googleapis.com/maps/api/place/details/json';
const params: any = {
key: apiKey,
place_id: place_id,
fields: fields || 'geometry'
};
const result = await axios.get(url, { params });
logger.info('Google Places Details API request completed successfully');
response.json(result.data);
} catch (error) {
logger.error('Error fetching place details:', error);
response.status(500).json({
success: false,
error: error instanceof Error ? error.message : String(error)
});
}
});
});