import Transaction from '../models/Transaction.js'; import User from '../models/User.js'; import ActivityLog from '../models/ActivityLog.js'; import { initiateMobilePayment } from '../services/paymentService.js'; import { uploadToR2 } from '../utils/storageUtils.js'; import crypto from 'crypto'; // Price Configuration: 20 credits per 15,000 TZS => 750 TZS per credit const CREDITS_PER_PACKAGE = 20; const PRICE_PER_PACKAGE_TZS = 15000; const PRICE_PER_CREDIT_TZS = PRICE_PER_PACKAGE_TZS / CREDITS_PER_PACKAGE; // 750 TZS // @desc Initiate Automatic Payment (Tigo/Halopesa/Airtel via ClickPesa) // @route POST /api/payments/buy export const buyCredits = async (req, res) => { try { const { credits, phoneNumber } = req.body; if (!credits || credits < 1) return res.status(400).json({ message: 'Invalid credit amount' }); if (!phoneNumber) return res.status(400).json({ message: 'Phone number required' }); const amount = credits * PRICE_PER_CREDIT_TZS; const shortRef = crypto.randomBytes(6).toString('hex'); const transaction = await Transaction.create({ user: req.user._id, amount, creditsPurchased: credits, phoneNumber, status: 'pending', paymentMethod: 'auto', reference: shortRef }); const paymentResponse = await initiateMobilePayment(amount, phoneNumber, shortRef); transaction.providerReference = paymentResponse.transaction_id || paymentResponse.id; await transaction.save(); await ActivityLog.create({ user: req.user._id, userEmail: req.user.email, action: 'PAYMENT_INITIATED', details: { amount, credits, phoneNumber: phoneNumber.replace(/.(?=.{4})/g, '*'), reference: shortRef, method: 'auto' } }); res.json({ message: 'Payment initiated. Check your phone.', transactionId: transaction._id, providerResponse: paymentResponse }); } catch (error) { console.error(error); res.status(500).json({ message: 'Payment failed' }); } }; // @desc Submit Manual M-Pesa Payment (screenshot or transaction code) // @route POST /api/payments/mpesa (multipart/form-data for screenshot, or JSON for code) export const submitMpesaPayment = async (req, res) => { try { const { credits, mpesaNumber, transactionCode } = req.body; if (!credits || parseInt(credits) < 1) return res.status(400).json({ message: 'Invalid credit amount' }); if (!mpesaNumber) return res.status(400).json({ message: 'M-Pesa number is required' }); const amount = parseInt(credits) * PRICE_PER_CREDIT_TZS; const shortRef = crypto.randomBytes(6).toString('hex').toUpperCase(); let mpesaProof = null; let mpesaProofType = 'code'; if (req.file) { // Screenshot upload const key = await uploadToR2(req.file.buffer, `mpesa_${shortRef}_${req.file.originalname}`, req.file.mimetype); mpesaProof = key; mpesaProofType = 'screenshot'; } else if (transactionCode) { mpesaProof = transactionCode.trim().toUpperCase(); mpesaProofType = 'code'; } if (!mpesaProof) { return res.status(400).json({ message: 'Please provide a transaction code or upload a screenshot' }); } const transaction = await Transaction.create({ user: req.user._id, amount, creditsPurchased: parseInt(credits), phoneNumber: mpesaNumber, mpesaNumber, mpesaProof, mpesaProofType, status: 'pending_review', paymentMethod: 'mpesa_manual', reference: shortRef }); await ActivityLog.create({ user: req.user._id, userEmail: req.user.email, action: 'PAYMENT_INITIATED', details: { amount, credits: parseInt(credits), method: 'mpesa_manual', mpesaNumber: mpesaNumber.replace(/.(?=.{4})/g, '*'), reference: shortRef, proofType: mpesaProofType } }); res.status(201).json({ message: 'M-Pesa payment submitted for review. Credits will be added within 1 hour during workhours.', transactionId: transaction._id, reference: shortRef }); } catch (error) { console.error('M-Pesa Submit Error:', error); res.status(500).json({ message: 'Failed to submit payment' }); } }; // @desc Handle ClickPesa Webhook (auto payments only) // @route POST /api/payments/webhook export const handleWebhook = async (req, res) => { try { const { event, data } = req.body; if (!data || !data.orderReference) { console.warn("⚠️ Received malformed webhook:", req.body); return res.status(400).send("Invalid payload"); } const { status, orderReference, message } = data; console.log(`Webhook Ref: ${orderReference} | Status: ${status} | Event: ${event}`); const transaction = await Transaction.findOne({ reference: orderReference }); if (!transaction) return res.status(404).json({ message: 'Transaction not found' }); if (['SETTLED', 'SUCCESS', 'completed'].includes(transaction.status)) { return res.status(200).json({ message: 'Already processed' }); } if (status === 'SUCCESS' || status === 'SETTLED') { transaction.status = status; await transaction.save(); const user = await User.findById(transaction.user); if (user) { user.credits += transaction.creditsPurchased; await user.save(); await ActivityLog.create({ user: user._id, userEmail: user.email, action: 'PAYMENT_SUCCESS', details: { amount: transaction.amount, credits: transaction.creditsPurchased, reference: orderReference } }); } } else { transaction.status = status; await transaction.save(); const user = await User.findById(transaction.user); if (user) { await ActivityLog.create({ user: user._id, userEmail: user.email, action: 'PAYMENT_FAILED', details: { amount: transaction.amount, credits: transaction.creditsPurchased, status, message } }); } } res.status(200).json({ received: true }); } catch (error) { console.error("Webhook Error:", error); res.status(500).json({ message: 'Server Error' }); } }; // @desc Simulate Webhook (Dev Only) // @route POST /api/payments/test-webhook export const testWebhook = async (req, res) => { if (process.env.NODE_ENV !== 'development') return res.status(403).send("Dev only"); const { transactionId } = req.body; const transaction = await Transaction.findById(transactionId); if (transaction && transaction.status === 'pending') { transaction.status = 'completed'; await transaction.save(); const user = await User.findById(transaction.user); user.credits += transaction.creditsPurchased; await user.save(); return res.json({ message: "Simulated Success" }); } res.status(400).json({ message: "Transaction not pending or found" }); }; // @desc Get credit pricing info // @route GET /api/payments/pricing export const getPricing = async (req, res) => { res.json({ creditsPerPackage: CREDITS_PER_PACKAGE, pricePerPackageTZS: PRICE_PER_PACKAGE_TZS, pricePerCreditTZS: PRICE_PER_CREDIT_TZS, processCost: 10, refineCost: 2 }); };