import { getAdmin, getLogger } from "../../shared/config"; const admin = getAdmin(); const logger = getLogger(); // Define an interface for the payment data to avoid type errors interface PaymentData { id: string; date: string; dateTimestamp: FirebaseFirestore.Timestamp; amount: any; paymentMethod: string; referenceNumber: string; discount: any; transactionId: string; createdAt: Date; invoicePath?: string; // Make this optional } export async function updatePaymentDataAfterSuccess( merchantOrderId: string, orderId: string, paymentDetails: any, invoicePath?: string ): Promise { try { // Get the payment order from Firestore const orderQuery = await admin.firestore() .collection('payment_orders') .where('merchantOrderId', '==', merchantOrderId) .limit(1) .get(); if (orderQuery.empty) { logger.error(`No payment order found with merchantOrderId: ${merchantOrderId}`); return false; } const orderDoc = orderQuery.docs[0]; const orderData = orderDoc.data(); // Extract membership ID from metaInfo const membershipId = orderData.metaInfo?.membershipId; if (!membershipId) { logger.error(`No membershipId found in metaInfo for order: ${merchantOrderId}`); return false; } const isoDate = new Date().toLocaleDateString('en-GB').split('/').join('-'); // DD-MM-YYYY format const dateTimestamp = admin.firestore.Timestamp.now(); // Create payment data object with proper typing const paymentData: PaymentData = { id: admin.firestore().collection('_').doc().id, // Generate a UUID date: isoDate, dateTimestamp: dateTimestamp, amount: orderData.amount, paymentMethod: 'Online', referenceNumber: merchantOrderId, discount: orderData.metaInfo?.discount || null, transactionId: orderId, createdAt: new Date() }; // Add invoice path if provided if (invoicePath) { paymentData.invoicePath = invoicePath; } // Get reference to membership payments document const membershipPaymentsRef = admin.firestore() .collection('membership_payments') .doc(membershipId); const docSnapshot = await membershipPaymentsRef.get(); // Update or create the membership payments document if (docSnapshot.exists) { await membershipPaymentsRef.update({ 'payments': admin.firestore.FieldValue.arrayUnion(paymentData), 'updatedAt': admin.firestore.FieldValue.serverTimestamp(), 'updatedBy': orderData.userId, }); } else { await membershipPaymentsRef.set({ 'membershipId': membershipId, 'payments': [paymentData], 'createdAt': admin.firestore.FieldValue.serverTimestamp(), 'createdBy': orderData.userId, 'updatedAt': admin.firestore.FieldValue.serverTimestamp(), 'updatedBy': orderData.userId, }); } // Update membership status await updateMembershipStatus(membershipId, orderData.userId); logger.info(`Successfully updated payment data for membership: ${membershipId}`); return true; } catch (error: any) { logger.error('Error updating payment data:', error); return false; } } async function updateMembershipStatus(membershipId: string, userId: string): Promise { try { const membershipDoc = await admin.firestore() .collection('memberships') .doc(membershipId) .get(); if (!membershipDoc.exists) { throw new Error(`Membership not found for id: ${membershipId}`); } await admin.firestore() .collection('memberships') .doc(membershipId) .update({ 'status': 'ACTIVE', // Assuming this matches your InvitationStatus.active 'updatedAt': admin.firestore.FieldValue.serverTimestamp(), }); logger.info(`Successfully updated membership status for: ${membershipId}`); } catch (error: any) { logger.error('Error updating membership status:', error); throw error; } }