All files / packages/app/utils receipt-item.ts

94.87% Statements 111/117
81.48% Branches 44/54
100% Functions 53/53
94.49% Lines 103/109

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409                                                                112x       1293x   7776x       7776x     7776x       1293x 335x 1073x   335x 1043x   335x         335x       112x 23611x 23611x 5831x 23611x   5831x   23611x   5831x 23611x     5831x             112x         2592x 5175x   2592x 5175x     2592x   5175x   2592x 2592x     2592x       2592x   5969x 3990x     2592x 5175x         2592x   5175x   2592x 5175x           2592x     112x         1299x       1299x         1299x   1303x       112x           4766x 1293x 6x     4766x 1293x 4760x       1293x       6x       1293x   1297x     1293x 6x     1293x   1303x 1303x       1303x             12x         1293x   1303x       1293x                                                                                                                                                 112x                 1293x 4766x   1293x 4532x     1293x 1293x 5369x   4532x       22308x     1293x   4532x     22797x       1293x   4532x     22797x       1293x 4532x     1293x   4760x       1293x   4760x     4760x         1293x               1293x             1293x 5369x         5369x 22797x         22797x   5369x   5369x 5369x           12x             22129x                    
import {
	entries,
	fromEntries,
	keys,
	mapValues,
	omitBy,
	unique,
	values,
} from "remeda";
 
import type { PeerId, ReceiptId, ReceiptItemId } from "~db/ids";
import { rotate } from "~utils/array";
import { getIndexByString } from "~utils/hash";
 
type ReceiptItem = {
	id: ReceiptItemId;
	quantity: number;
	price: number;
	consumers: {
		peerId: PeerId;
		part: number;
	}[];
	payers: {
		peerId: PeerId;
		part: number;
	}[];
};
type ReceiptParticipant = {
	createdAt: Temporal.ZonedDateTime;
	peerId: PeerId;
};
 
const getSortPeersByReceipt = (
	receiptId: ReceiptId,
	participants: ReceiptParticipant[],
) => {
	const mappedParticipants = rotate(
		participants.toSorted((participantA, participantB) => {
			const createdDelta = Temporal.ZonedDateTime.compare(
				participantA.createdAt,
				participantB.createdAt,
			);
			const peerIdComparison = participantA.peerId.localeCompare(
				participantB.peerId,
			);
			return createdDelta || peerIdComparison;
		}),
		getIndexByString(receiptId),
	);
	return (peerA: PeerId, peerB: PeerId) => {
		const participantAIndex = mappedParticipants.findIndex(
			(participant) => participant.peerId === peerA,
		);
		const participantBIndex = mappedParticipants.findIndex(
			(participant) => participant.peerId === peerB,
		);
		Iif (participantAIndex === -1 || participantBIndex === -1) {
			throw new Error(
				`Expected to have participants matched in sorting by receipt`,
			);
		}
		return participantAIndex - participantBIndex;
	};
};
 
const getItemCalculations = (sum: number, parts: Record<PeerId, number>) => {
	const partsAmount = values(parts).reduce((acc, part) => acc + part, 0);
	const sumsByPeer = mapValues(parts, (part) => (part / partsAmount) * sum);
	const flooredByPeers = mapValues(sumsByPeer, (sumByPeer) =>
		Math.floor(sumByPeer),
	);
	const shortagesByPeers = mapValues(
		sumsByPeer,
		(sumByPeer) => sumByPeer - Math.floor(sumByPeer),
	);
	const flooredSum = values(flooredByPeers).reduce(
		(acc, flooredByPeer) => acc + flooredByPeer,
		0,
	);
	return {
		flooredByPeers,
		shortagesByPeers,
		leftover: sum - flooredSum,
	};
};
 
const distributeLeftovers = (
	shortagesByPeers: Record<PeerId, number>,
	initialLeftover: number,
	sortPeers: (peerA: PeerId, peerB: PeerId) => number,
) => {
	const reimbursedByPeers = mapValues(shortagesByPeers, (shortage) =>
		Math.trunc(shortage),
	);
	const totalReimbursed = values(reimbursedByPeers).reduce(
		(acc, reimbursed) => acc + reimbursed,
		0,
	);
	const notReimbursedByPeers = mapValues(
		shortagesByPeers,
		(shortage, peerId) => shortage - (reimbursedByPeers[peerId] ?? 0),
	);
	const luckyLeftover = initialLeftover - totalReimbursed;
	Iif (luckyLeftover < 0) {
		throw new Error("Unexpected negative lucky leftover");
	}
	Iif (luckyLeftover > keys(shortagesByPeers).length) {
		throw new Error("Unexpected lucky leftover bigger than peers left");
	}
 
	const notReimbursedOrder = entries(notReimbursedByPeers).toSorted(
		([peerA, peerANotReimbursed], [peerB, peerBNotReimbursed]) => {
			const notReimbursedDelta = peerBNotReimbursed - peerANotReimbursed;
			return notReimbursedDelta || sortPeers(peerA, peerB);
		},
	);
	const luckyLeftovers = fromEntries(
		notReimbursedOrder.map(([peerId], index) => [
			peerId,
			index + 1 <= luckyLeftover ? 1 : 0,
		]),
	);
	const totalByPeers = mapValues(
		reimbursedByPeers,
		(reimbursed, peerId) => reimbursed + (luckyLeftovers[peerId] ?? 0),
	);
	Iif (
		initialLeftover !== values(totalByPeers).reduce((acc, sum) => acc + sum, 0)
	) {
		throw new Error(
			"Unexpected total after reimbursement differs from initial leftover",
		);
	}
	return totalByPeers;
};
 
const getPeerSums = (
	sum: number,
	parts: Record<PeerId, number>,
	sortPeers: (peerA: PeerId, peerB: PeerId) => number,
) => {
	const { flooredByPeers, shortagesByPeers, leftover } = getItemCalculations(
		sum,
		parts,
	);
	const distributedLeftovers = distributeLeftovers(
		shortagesByPeers,
		leftover,
		sortPeers,
	);
	return mapValues(
		flooredByPeers,
		(value, peerId) => value + (distributedLeftovers[peerId] ?? 0),
	);
};
 
const getPayersSums = (
	commonPayers: ReceiptItem["consumers"],
	items: ReceiptItem[],
	fromUnitToSubunit: (input: number) => number,
	sortPeers: (peerA: PeerId, peerB: PeerId) => number,
) => {
	const separatelyPayedItems = items.filter((item) => item.payers.length !== 0);
	const separatelyPayedSum = separatelyPayedItems.reduce(
		(acc, item) => acc + fromUnitToSubunit(item.price * item.quantity),
		0,
	);
	const commonlyPayedItems = items.filter((item) => item.payers.length === 0);
	const commonlyPayedSum = commonlyPayedItems.reduce(
		(acc, item) => acc + fromUnitToSubunit(item.price * item.quantity),
		0,
	);
 
	const separatelyPayedSumsByItem = separatelyPayedItems.map((item) => ({
		itemId: item.id,
		sums: getPeerSums(
			fromUnitToSubunit(item.price * item.quantity),
			fromEntries(item.payers.map(({ peerId, part }) => [peerId, part])),
			sortPeers,
		),
	}));
	const commonlyPayedSums = getPeerSums(
		commonlyPayedSum,
		fromEntries(commonPayers.map(({ peerId, part }) => [peerId, part])),
		sortPeers,
	);
	const allPayers = unique<PeerId[]>([
		...separatelyPayedSumsByItem.flatMap((item) => keys(item.sums)),
		...keys(commonlyPayedSums),
	]);
	const payersSums = fromEntries(
		allPayers.map((payerId) => {
			const commonPayedSum = commonlyPayedSums[payerId] ?? 0;
			const itemPayedSums = separatelyPayedSumsByItem.map((sumsByPeers) => ({
				itemId: sumsByPeers.itemId,
				sum: sumsByPeers.sums[payerId] ?? 0,
			}));
			return [
				payerId,
				{
					common: commonPayedSum,
					items: itemPayedSums,
					total:
						commonPayedSum +
						itemPayedSums.reduce((acc, { sum }) => acc + sum, 0),
				},
			];
		}),
	);
	Iif (
		separatelyPayedSum + commonlyPayedSum !==
		values(payersSums).reduce((acc, { total }) => acc + total, 0)
	) {
		throw new Error("Unexpected total payed sum differs from payer sums");
	}
	return payersSums;
};
 
/*
	How does distributing sums work?
	Calculation consist of three phases:
	- calculate floored sums, participant shortages and leftovers
	- reimbursed shortages with some of leftovers
	- distribute lucky leftovers
 
	E.g.:
	- receipt has 3 items - 40.01$, 4.01$ and 4$ (I1, I2 and I3)
	- 3 participants (P1, P2 and P3) share 4$ and 4.01$ items equally, 40.01$ has P1 10/12, the rest have 1/12
	
	First, we calculate floored sums, participant shortage and leftovers for every item.
	For I1 those would be:
	- floored sums: P1 3334, P2 333, P3 333
	- participant shortage: P1 0.1(6), P2 0.41(6), P3 0.41(6)
	- leftover: 4001 - 3334 - 333 - 333 = 1
	For I2 those would be:
	- floored sums: 133 each participant
	- participant shortage: 0.(6) each participant
	- leftover: 401 - 133 - 133 - 133 = 2
	For I3 those would be:
	- floored sums: 133 each participant
	- participant shortage: 0.(3) each participant
	- leftover: 400 - 133 - 133 - 133 = 1
 
	Slice by participants:
	P1:
	- floored sum is 3334 + 133 + 133 = 3600
	- shortage is 0.1(6) + 0.(6) + 0.(3) = 1.1(6)
	P2 and P3:
	- floored sum is 333 + 133 + 133 = 599
	- shortage is 0.41(6) + 0.(6) + 0.(3) = 1.41(6)
 
	Total leftover is 1 + 2 + 1 = 4
 
	Second, we reimburse shortages - the integer ones - for each participant.
	Every participant gets 1 as reimburse, and is left with non-reimbursed shortage:
	P1: 0.1(6)
	P2 and P3: 0.41(6)
 
	Total leftover is now 1.
 
	Third, we order participants by non-reimbursed shortage:
	(1st place) P2 and P3
	(2nd place) P1
 
	Fourth, we roll the dice* to figure out who will recieve the leftovers first:
	(1st) P2 (wins in dice roll)
	(2nd) P3
	(3rd) P1
 
	* Die orders participants by creation date, if equal - by peer id,
	then rotate the array of participants based on receipt id (statistically random)
 
	Finally, we give one cent to each participant with index less than amount of leftover (which is 1)
 
	Final slice by participant:
	P1: total 3601 (36.01$)
	- floored sum is 3600
	- reimbursed shortage is 1
	- lucky leftover gave 0
	P2: total 601 (6.01$)
	- floored sum is 599
	- reimbursed shortage is 1
	- lucky leftover gave 1
	P3: total 600 (6.00$)
	- floored sum is 599
	- reimbursed shortage is 1
	- lucky leftover gave 0
*/
export const getParticipantSums = (
	receiptId: ReceiptId,
	ownerPeerId: PeerId,
	items: ReceiptItem[],
	participants: ReceiptParticipant[],
	payers: ReceiptItem["consumers"],
	fromUnitToSubunit: (input: number) => number,
	fromSubunitToUnit: (input: number) => number,
) => {
	const itemsWithConsumers = items.filter(
		(item) => item.consumers.length !== 0,
	);
	const totalSum = itemsWithConsumers.reduce(
		(acc, item) => acc + fromUnitToSubunit(item.price * item.quantity),
		0,
	);
	const sortPeersByReceipt = getSortPeersByReceipt(receiptId, participants);
	const allParticipantsIds = fromEntries(
		participants.map((participant) => [participant.peerId, 0]),
	);
	const itemCalculations = itemsWithConsumers.map((item) => ({
		id: item.id,
		...getItemCalculations(
			fromUnitToSubunit(item.price * item.quantity),
			fromEntries(item.consumers.map(({ peerId, part }) => [peerId, part])),
		),
	}));
	const flooredByPeers = itemCalculations.reduce<Record<PeerId, number>>(
		(acc, itemCalculation) =>
			mapValues(
				allParticipantsIds,
				(_, peerId) =>
					(acc[peerId] ?? 0) + (itemCalculation.flooredByPeers[peerId] ?? 0),
			),
		{},
	);
	const shortagesByPeers = itemCalculations.reduce<Record<PeerId, number>>(
		(acc, itemCalculation) =>
			mapValues(
				allParticipantsIds,
				(_, peerId) =>
					(acc[peerId] ?? 0) + (itemCalculation.shortagesByPeers[peerId] ?? 0),
			),
		{},
	);
	const totalLeftover = itemCalculations.reduce(
		(acc, itemCalculation) => acc + itemCalculation.leftover,
		0,
	);
	const distributedLeftovers = distributeLeftovers(
		// Not distributing leftovers amongst those who don't participate
		omitBy(shortagesByPeers, (value) => value === 0) as Record<PeerId, number>,
		totalLeftover,
		sortPeersByReceipt,
	);
	const debtSums = mapValues(
		flooredByPeers,
		(value, peerId) => value + (distributedLeftovers[peerId] ?? 0),
	);
 
	Iif (totalSum !== values(debtSums).reduce((acc, sum) => acc + sum, 0)) {
		throw new Error("Unexpected total debt sum differs from debtors sums");
	}
 
	const surePayers =
		payers.length === 0
			? [
					{
						peerId: ownerPeerId,
						part: 1,
					},
				]
			: payers;
	const payersSums = getPayersSums(
		surePayers,
		items,
		fromUnitToSubunit,
		sortPeersByReceipt,
	);
 
	return participants.map(({ peerId }) => {
		const payerObject = payersSums[peerId] ?? {
			common: 0,
			items: [],
			total: 0,
		};
		const flooredDebts = itemCalculations
			.map((item) => ({
				itemId: item.id,
				sum: item.flooredByPeers[peerId] ?? 0,
				shortage: item.shortagesByPeers[peerId] ?? 0,
			}))
			.filter(({ sum, shortage }) => sum !== 0 || shortage !== 0);
		// Sometimes there's a rounding error around here
		const totalPayment = Math.round(payerObject.total);
		// Sometimes there's a rounding error around here
		const totalDebt = Math.round(debtSums[peerId] ?? 0);
		return {
			peerId,
			payment: {
				// Sometimes there's a rounding error around here
				total: fromSubunitToUnit(totalPayment),
				common: fromSubunitToUnit(payerObject.common),
				items: payerObject.items.map((item) => ({
					...item,
					sum: fromSubunitToUnit(item.sum),
				})),
			},
			debt: {
				total: fromSubunitToUnit(totalDebt),
				items: flooredDebts.map((item) => ({
					...item,
					sum: fromSubunitToUnit(item.sum),
				})),
				leftover: fromSubunitToUnit(distributedLeftovers[peerId] ?? 0),
			},
			balance: fromSubunitToUnit(totalDebt - totalPayment),
		};
	});
};