mirror of
https://github.com/spliit-app/spliit.git
synced 2025-12-06 09:29:39 +01:00
Reimbursements
This commit is contained in:
@@ -6,6 +6,12 @@ export type Balances = Record<
|
||||
{ paid: number; paidFor: number; total: number }
|
||||
>
|
||||
|
||||
export type Reimbursement = {
|
||||
from: Participant['id']
|
||||
to: Participant['id']
|
||||
amount: number
|
||||
}
|
||||
|
||||
export function getBalances(
|
||||
expenses: NonNullable<Awaited<ReturnType<typeof getGroupExpenses>>>,
|
||||
): Balances {
|
||||
@@ -40,3 +46,37 @@ function divide(total: number, count: number, isLast: boolean): number {
|
||||
|
||||
return total - divide(total, count, false) * (count - 1)
|
||||
}
|
||||
|
||||
export function getSuggestedReimbursements(
|
||||
balances: Balances,
|
||||
): Reimbursement[] {
|
||||
const balancesArray = Object.entries(balances).map(
|
||||
([participantId, { total }]) => ({ participantId, total }),
|
||||
)
|
||||
balancesArray.sort((b1, b2) => b2.total - b1.total)
|
||||
console.log(balancesArray)
|
||||
const reimbursements: Reimbursement[] = []
|
||||
while (balancesArray.length > 1) {
|
||||
const first = balancesArray[0]
|
||||
const last = balancesArray[balancesArray.length - 1]
|
||||
const amount = Math.round(first.total * 100 + last.total * 100) / 100
|
||||
if (first.total > -last.total) {
|
||||
reimbursements.push({
|
||||
from: last.participantId,
|
||||
to: first.participantId,
|
||||
amount: -last.total,
|
||||
})
|
||||
first.total = amount
|
||||
balancesArray.pop()
|
||||
} else {
|
||||
reimbursements.push({
|
||||
from: last.participantId,
|
||||
to: first.participantId,
|
||||
amount: first.total,
|
||||
})
|
||||
last.total = amount
|
||||
balancesArray.shift()
|
||||
}
|
||||
}
|
||||
return reimbursements
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user