82 lines
2.2 KiB
TypeScript
82 lines
2.2 KiB
TypeScript
"use client";
|
|
|
|
import React from "react";
|
|
import { api } from "@/trpc/react";
|
|
import type { Session } from "next-auth";
|
|
import type { PublicUser } from "next-auth";
|
|
import { calculateSplits, type Payment } from "@/lib/utils/expense";
|
|
|
|
export enum SplitTypeEnum {
|
|
Fixed = "fixed",
|
|
Percentage = "percentage",
|
|
Equal = "equal",
|
|
}
|
|
export type SplitType = keyof typeof SplitTypeEnum;
|
|
export const splitTypeKeys = Object.keys(SplitTypeEnum);
|
|
|
|
export const useExpenseSplit = (amount: number, session: Session) => {
|
|
const [friends] = api.friend.getAll.useSuspenseQuery();
|
|
const [friendTarget, setFriendTarget] = React.useState<string>();
|
|
const [participants, setParticipants] = React.useState<Array<PublicUser>>([
|
|
session.user,
|
|
]);
|
|
const [activeSplitType, setActiveSplitType] =
|
|
React.useState<SplitType>("Equal");
|
|
const [payments, setPayments] = React.useState<Array<Payment>>([
|
|
{ amount: amount, userId: session.user.id },
|
|
]);
|
|
|
|
const [splits, setSplits] = React.useState<
|
|
Record<string /* user.id */, string /* amount */>
|
|
>({});
|
|
|
|
React.useEffect(() => {
|
|
// const generateSplitsAmount = () => {
|
|
// var newSplits: Record<string, SplitType> = {};
|
|
// participants.forEach((user) => {
|
|
// newSplits[user.id!] = splits[user.id!] ?? {};
|
|
// });
|
|
// console.log(newSplits);
|
|
// return newSplits;
|
|
// };
|
|
|
|
setSplits(
|
|
calculateSplits(
|
|
{
|
|
amount,
|
|
users: participants.map((user) => user.id!),
|
|
splitType: activeSplitType,
|
|
}
|
|
// generateSplitsAmount()
|
|
)
|
|
);
|
|
}, [participants, activeSplitType, amount]);
|
|
|
|
const addParticipant = (newUser: PublicUser) => {
|
|
setParticipants((prev) =>
|
|
prev.find((user) => user.id === newUser.id) ? prev : [...prev, newUser]
|
|
);
|
|
};
|
|
const removeParticipant = (userId: string) => {
|
|
setParticipants((prev) => prev.filter((user) => user.id !== userId));
|
|
};
|
|
|
|
return {
|
|
friends,
|
|
amount,
|
|
participants,
|
|
addParticipant,
|
|
removeParticipant,
|
|
friendTarget,
|
|
setFriendTarget,
|
|
splitType: activeSplitType,
|
|
setSplitType: setActiveSplitType,
|
|
payments,
|
|
setPayments,
|
|
//
|
|
splits,
|
|
};
|
|
};
|
|
|
|
export type ExpenseSplitHook = ReturnType<typeof useExpenseSplit>;
|