added logging

This commit is contained in:
AllenTJ7 2025-05-20 15:40:30 +05:30
parent c6f8b7fc35
commit a4c3cbbba2

View File

@ -21,7 +21,7 @@ export const phonePeWebhook = onRequest({
body: request.body, body: request.body,
method: request.method method: request.method
}); });
const authHeader = request.headers['authorization'] as string; const authHeader = request.headers['authorization'] as string;
const username = process.env.PHONEPE_WEBHOOK_USERNAME; const username = process.env.PHONEPE_WEBHOOK_USERNAME;
const password = process.env.PHONEPE_WEBHOOK_PASSWORD; const password = process.env.PHONEPE_WEBHOOK_PASSWORD;
@ -37,7 +37,7 @@ export const phonePeWebhook = onRequest({
.createHash('sha256') .createHash('sha256')
.update(credentialString) .update(credentialString)
.digest('hex'); .digest('hex');
const receivedAuth = authHeader.replace(/^SHA256\s+/i, ''); const receivedAuth = authHeader.replace(/^SHA256\s+/i, '');
if (receivedAuth.toLowerCase() !== expectedAuth.toLowerCase()) { if (receivedAuth.toLowerCase() !== expectedAuth.toLowerCase()) {
@ -106,44 +106,54 @@ export const phonePeWebhook = onRequest({
} }
if (payload.state === 'COMPLETED') { if (payload.state === 'COMPLETED') {
logger.info(`Payment COMPLETED for merchantOrderId: ${payload.merchantOrderId}, orderId: ${payload.orderId}`);
logger.info('Payment completion details:', {
merchantOrderId: payload.merchantOrderId,
orderId: payload.orderId,
amount: payload.amount,
paymentInstrument: payload.paymentInstrument,
timestamp: new Date().toISOString()
});
try { try {
logger.info(`Starting payment update process for merchantOrderId: ${payload.merchantOrderId}`);
const paymentUpdateSuccess = await updatePaymentDataAfterSuccess( const paymentUpdateSuccess = await updatePaymentDataAfterSuccess(
payload.merchantOrderId, payload.merchantOrderId,
payload.orderId, payload.orderId,
payload payload
); );
logger.info(`Payment update result for merchantOrderId: ${payload.merchantOrderId}`, {
success: paymentUpdateSuccess,
orderId: payload.orderId
});
if (paymentUpdateSuccess) { if (paymentUpdateSuccess) {
const orderData = orderDoc.data(); const orderData = orderDoc.data();
const membershipId = orderData.metaInfo?.membershipId; const membershipId = orderData.metaInfo?.membershipId;
logger.info(`Processing invoice for completed payment`, {
merchantOrderId: payload.merchantOrderId,
orderId: payload.orderId,
membershipId: membershipId || 'not-provided'
});
if (membershipId) { if (membershipId) {
try { try {
logger.info(`Fetching membership data for membershipId: ${membershipId}`);
const membershipDoc = await admin.firestore() const membershipDoc = await admin.firestore()
.collection('memberships') .collection('memberships')
.doc(membershipId) .doc(membershipId)
.get(); .get();
if (membershipDoc.exists) { if (membershipDoc.exists) {
logger.info(`Membership data retrieved successfully for membershipId: ${membershipId}`);
const membershipData = membershipDoc.data(); const membershipData = membershipDoc.data();
const userId = membershipData?.userId; const userId = membershipData?.userId;
logger.info(`Fetching user data for userId: ${userId}`);
const userDoc = await admin.firestore() const userDoc = await admin.firestore()
.collection('users') .collection('users')
.doc(userId) .doc(userId)
.get(); .get();
if (userDoc.exists) { if (userDoc.exists) {
logger.info(`User data retrieved successfully for userId: ${userId}`);
logger.info(`Starting invoice generation process for payment: ${payload.merchantOrderId}`);
const userData = userDoc.data(); const userData = userDoc.data();
const gymId = orderData.metaInfo?.gymId || membershipData?.gymId; const gymId = orderData.metaInfo?.gymId || membershipData?.gymId;
@ -211,6 +221,14 @@ export const phonePeWebhook = onRequest({
} }
const invoiceNumber = `INV-${payload.merchantOrderId.substring(0, 8)}`; const invoiceNumber = `INV-${payload.merchantOrderId.substring(0, 8)}`;
logger.info(`Generated invoice number: ${invoiceNumber}`);
logger.info(`Preparing invoice data for generation`, {
invoiceNumber,
merchantOrderId: payload.merchantOrderId,
gymName: gymName
});
const invoiceData = { const invoiceData = {
invoiceNumber, invoiceNumber,
businessName: gymName, businessName: gymName,
@ -227,6 +245,12 @@ export const phonePeWebhook = onRequest({
}; };
const invoicePath = await invoiceService.generateInvoice(invoiceData); const invoicePath = await invoiceService.generateInvoice(invoiceData);
logger.info(`Invoice generated successfully at path: ${invoicePath}`);
logger.info(`Updating membership payment with invoice path`, {
membershipId,
invoicePath
});
await admin.firestore() await admin.firestore()
.collection('membership_payments') .collection('membership_payments')
@ -234,29 +258,50 @@ export const phonePeWebhook = onRequest({
.get() .get()
.then(async (doc) => { .then(async (doc) => {
if (doc.exists) { if (doc.exists) {
logger.info(`Found membership payment document for membershipId: ${membershipId}`);
const paymentsData = doc.data()?.payments || []; const paymentsData = doc.data()?.payments || [];
let paymentFound = false;
for (let i = 0; i < paymentsData.length; i++) { for (let i = 0; i < paymentsData.length; i++) {
if (paymentsData[i].referenceNumber === payload.merchantOrderId || if (paymentsData[i].referenceNumber === payload.merchantOrderId ||
paymentsData[i].transactionId === payload.orderId) { paymentsData[i].transactionId === payload.orderId) {
paymentsData[i].invoicePath = invoicePath; paymentsData[i].invoicePath = invoicePath;
paymentFound = true;
break; break;
} }
} }
logger.info(`Payment record ${paymentFound ? 'found' : 'not found'} in membership payments`, {
membershipId,
merchantOrderId: payload.merchantOrderId,
orderId: payload.orderId
});
await doc.ref.update({ await doc.ref.update({
'payments': paymentsData, 'payments': paymentsData,
'updatedAt': admin.firestore.FieldValue.serverTimestamp(), 'updatedAt': admin.firestore.FieldValue.serverTimestamp(),
}); });
logger.info(`Successfully updated membership payment with invoice path`, {
membershipId,
invoicePath
});
} else {
logger.warn(`No membership payment document found for membershipId: ${membershipId}`);
} }
}); });
logger.info(`Generated invoice for payment: ${payload.merchantOrderId}, path: ${invoicePath}`); logger.info(`Generated invoice for payment: ${payload.merchantOrderId}, path: ${invoicePath}`);
logger.info(`Getting download URL for invoice: ${invoicePath}`);
const downloadUrl = await invoiceService.getInvoiceDownloadUrl(invoicePath); const downloadUrl = await invoiceService.getInvoiceDownloadUrl(invoicePath);
logger.info(`Generated download URL for invoice: ${invoicePath}`);
const formattedDate = format(new Date(), 'dd/MM/yyyy'); const formattedDate = format(new Date(), 'dd/MM/yyyy');
if (membershipData?.fields?.['email']) { if (membershipData?.fields?.['email']) {
logger.info(`Preparing to send invoice email to customer: ${membershipData?.fields?.['email']}`);
try { try {
const emailSubject = isFreeplan const emailSubject = isFreeplan
? `Free Plan Assigned - ${gymName}` ? `Free Plan Assigned - ${gymName}`
@ -303,6 +348,7 @@ export const phonePeWebhook = onRequest({
} }
if (gymOwnerEmail) { if (gymOwnerEmail) {
logger.info(`Preparing to send invoice email to gym owner: ${gymOwnerEmail}`);
try { try {
const ownerEmailSubject = isFreeplan const ownerEmailSubject = isFreeplan
? `Free Plan Assigned${paymentType === 'Gym Membership with Personal Training' ? ' with Personal Training' : ''} - ${gymName}` ? `Free Plan Assigned${paymentType === 'Gym Membership with Personal Training' ? ' with Personal Training' : ''} - ${gymName}`