UNPKG

@wernerthiago/teo

Version:

Test Execution Optimizer

115 lines (93 loc) 2.97 kB
// Payment processing module export class PaymentService { constructor() { this.transactions = new Map() this.paymentMethods = new Map() } async processPayment(amount, paymentMethodId, currency = 'USD') { const paymentMethod = this.paymentMethods.get(paymentMethodId) if (!paymentMethod) { throw new Error('Invalid payment method') } if (amount <= 0) { throw new Error('Invalid amount') } const transactionId = this.generateTransactionId() const transaction = { id: transactionId, amount, currency, paymentMethodId, status: 'processing', createdAt: new Date() } this.transactions.set(transactionId, transaction) // Simulate payment processing const success = await this.simulatePaymentProcessing() transaction.status = success ? 'completed' : 'failed' transaction.completedAt = new Date() return transaction } async addPaymentMethod(userId, cardNumber, expiryDate, cvv) { const paymentMethodId = this.generatePaymentMethodId() const paymentMethod = { id: paymentMethodId, userId, cardNumber: this.maskCardNumber(cardNumber), expiryDate, createdAt: new Date() } this.paymentMethods.set(paymentMethodId, paymentMethod) return paymentMethod } async refundPayment(transactionId, amount) { const transaction = this.transactions.get(transactionId) if (!transaction) { throw new Error('Transaction not found') } if (transaction.status !== 'completed') { throw new Error('Cannot refund incomplete transaction') } if (amount > transaction.amount) { throw new Error('Refund amount exceeds transaction amount') } const refundId = this.generateTransactionId() const refund = { id: refundId, originalTransactionId: transactionId, amount, currency: transaction.currency, status: 'completed', createdAt: new Date() } this.transactions.set(refundId, refund) return refund } async simulatePaymentProcessing() { // Simulate network delay await new Promise(resolve => setTimeout(resolve, 100)) // 95% success rate return Math.random() > 0.05 } maskCardNumber(cardNumber) { return cardNumber.replace(/\d(?=\d{4})/g, '*') } generateTransactionId() { return 'txn_' + Math.random().toString(36).substring(2) + Date.now().toString(36) } generatePaymentMethodId() { return 'pm_' + Math.random().toString(36).substring(2) + Date.now().toString(36) } } export default PaymentService // New feature: Payment retry logic async retryPayment(transactionId, maxRetries = 3) { for (let i = 0; i < maxRetries; i++) { try { return await this.processPayment(transactionId) } catch (error) { if (i === maxRetries - 1) throw error await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1))) } } }