Skip to content

Commit

Permalink
feat: implemented bill splitting type equal version 1
Browse files Browse the repository at this point in the history
  • Loading branch information
abhiraj-ku committed Nov 10, 2024
1 parent a1105fa commit 18f328b
Show file tree
Hide file tree
Showing 2 changed files with 84 additions and 0 deletions.
53 changes: 53 additions & 0 deletions src/controllers/splitLogicController.js
Original file line number Diff line number Diff line change
@@ -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) {}
};
31 changes: 31 additions & 0 deletions src/helpers/validateBillsplitInputs.js
Original file line number Diff line number Diff line change
@@ -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,
};
};

0 comments on commit 18f328b

Please sign in to comment.