diff --git a/src/controllers/splitLogicController.js b/src/controllers/splitLogicController.js new file mode 100644 index 0000000..516134a --- /dev/null +++ b/src/controllers/splitLogicController.js @@ -0,0 +1,53 @@ +const validateBillSplit = require('../helpers/validateBillsplitInputs'); + +module.exports.splitBill = async (req, res) => { + // Step 1. Get the bare split equal done + const { description, amount, paidBy, splitType, selectedMemeber } = req.body; + if (!description || !amount || !paidBy || !splitType || !selectedMemeber) { + return res.status(400).json({ message: 'All fields are required' }); + } + + // type Checking + const validateInput = validateBillSplit(req.body); + if (!validateInput.isValid) { + return res + .status(400) + .json({ message: 'Invalid input types', errors: validateBillSplit.errors }); + } + + //Bill splitting logics + try { + const paidUsers = []; + + // Type 1: splitType === 'EQUAL' + if (splitType === 'EQUAL') { + let membersInex = [...selectedMembers]; + + // If paidBy should be included and isn't already in the array + if (isPaidByIncluded && !membersInex.includes(paidBy)) { + membersInex.push(paidBy); + } + + // Calculate split amount + const toEachMem = Number(amount / membersInex.length); + const eachShare = Math.round(toEachMem * 10) / 10; + + // Show who owes what + membersInex.forEach((mem) => { + if (mem === paidBy) { + console.log(`${mem} paid Rs. ${amount} and owes Rs. ${eachShare}`); + } else { + console.log(`${mem} has to pay Rs. ${eachShare} to ${paidBy}`); + } + }); + + return { + paymentType: 'EQUAL', + totalAmount: amount, + perPersonShare: eachShare, + paidBy, + participants: membersInex, + }; + } + } catch (error) {} +}; diff --git a/src/helpers/validateBillsplitInputs.js b/src/helpers/validateBillsplitInputs.js new file mode 100644 index 0000000..04fd2f2 --- /dev/null +++ b/src/helpers/validateBillsplitInputs.js @@ -0,0 +1,31 @@ +const validateBarterPayInput = (data) => { + const errors = []; + + if (typeof data.description !== 'string' || !data.description.trim()) { + errors.push('Description must be a non-empty string'); + } + + if (typeof data.amount !== 'number' || data.amount <= 0) { + errors.push('Amount must be a greater than 0'); + } + + if (typeof data.paidBy !== 'string' || !data.paidBy.trim()) { + errors.push('PaidBy must be a non-empty string'); + } + + if ( + typeof data.splitType !== 'string' || + !['EQUAL', 'CUSTOM'].includes(data.splitType.toUpperCase()) + ) { + errors.push('Invalid splitType'); + } + + if (!Array.isArray(data.selectedMemeber) || data.selectedMemeber.length === 0) { + errors.push('selectedMemeber must be a non-empty array'); + } + + return { + isValid: errors.length === 0, + errors, + }; +};