Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: initialise a new totals tab with basic UI #94

Merged
merged 5 commits into from
Feb 28, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/app/groups/[groupId]/group-tabs.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ export function GroupTabs({ groupId }: Props) {
<TabsList>
<TabsTrigger value="expenses">Expenses</TabsTrigger>
<TabsTrigger value="balances">Balances</TabsTrigger>
<TabsTrigger value="stats">Stats</TabsTrigger>
<TabsTrigger value="edit">Settings</TabsTrigger>
</TabsList>
</Tabs>
Expand Down
60 changes: 60 additions & 0 deletions src/app/groups/[groupId]/stats/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { cached } from '@/app/cached-functions'
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from '@/components/ui/card'
import { getGroupExpenses } from '@/lib/api'
import { Metadata } from 'next'
import { notFound } from 'next/navigation'
import { TotalsGroupSpending } from '@/app/groups/[groupId]/totals-group-spending'
import { getTotalGroupSpending } from '@/lib/totals'
import { TotalsYourSpendings } from '@/app/groups/[groupId]/totals-your-spending'
import { TotalsYourShare } from '@/app/groups/[groupId]/totals-your-share'
import { Space } from 'lucide-react'

export const metadata: Metadata = {
title: 'Totals',
}

export default async function TotalsPage({
params: { groupId },
}: {
params: { groupId: string }
}) {
const group = await cached.getGroup(groupId)
if (!group) notFound()

const expenses = await getGroupExpenses(groupId)
const totalGroupSpendings = getTotalGroupSpending(expenses)

return (
<>
<Card className="mb-4">
<CardHeader>
<CardTitle>Totals</CardTitle>
<CardDescription>
Spending summary of the entire group
scastiel marked this conversation as resolved.
Show resolved Hide resolved
</CardDescription>
</CardHeader>
<CardContent className='flex flex-col space-y-4'>
<TotalsGroupSpending
totalGroupSpendings={totalGroupSpendings}
currency={group.currency}
/>
<TotalsYourSpendings
group={group}
expenses={expenses}
/>
<TotalsYourShare
group={group}
expenses={expenses}
/>
</CardContent>
</Card>

</>
)
}
19 changes: 19 additions & 0 deletions src/app/groups/[groupId]/totals-group-spending.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { formatCurrency } from '@/lib/utils'

type Props = {
totalGroupSpendings: number
currency: string
}

export function TotalsGroupSpending({ totalGroupSpendings, currency }: Props) {
return (
<div>
<div className="text-muted-foreground">
Total group spendings
</div>
<div className="text-lg">
{formatCurrency(currency, totalGroupSpendings)}
</div>
</div>
)
}
38 changes: 38 additions & 0 deletions src/app/groups/[groupId]/totals-your-share.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
'use client'
import { formatCurrency } from '@/lib/utils'
import { getGroup, getGroupExpenses } from '@/lib/api'
import { getTotalActiveUserShare } from '@/lib/totals'
import { useEffect, useState } from 'react'


type Props = {
group: NonNullable<Awaited<ReturnType<typeof getGroup>>>
expenses: NonNullable<Awaited<ReturnType<typeof getGroupExpenses>>>
}

export function TotalsYourShare({ group, expenses }: Props) {

const [activeUser, setActiveUser] = useState('')

useEffect(() => {
const activeUser = localStorage.getItem(`${group.id}-activeUser`)
if (activeUser) setActiveUser(activeUser)

}, [group, expenses])

const totalActiveUserShare = (activeUser === '' || activeUser === 'None') ? 0 : getTotalActiveUserShare(activeUser, expenses)
const currency = group.currency

return (
<div>
<div className="text-muted-foreground">
Your total share

</div>
<div className="text-lg">
{formatCurrency(currency, totalActiveUserShare)}
</div>
</div>

)
}
38 changes: 38 additions & 0 deletions src/app/groups/[groupId]/totals-your-spending.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
'use client'
import { formatCurrency } from '@/lib/utils'
import { getGroup, getGroupExpenses } from '@/lib/api'
import { getTotalActiveUserPaidFor } from '@/lib/totals'
import { useEffect, useState } from 'react'


type Props = {
group: NonNullable<Awaited<ReturnType<typeof getGroup>>>
expenses: NonNullable<Awaited<ReturnType<typeof getGroupExpenses>>>
}

export function TotalsYourSpendings({ group, expenses }: Props) {

const [activeUser, setActiveUser] = useState('')

useEffect(() => {
const activeUser = localStorage.getItem(`${group.id}-activeUser`)
if (activeUser) setActiveUser(activeUser)

}, [group, expenses])

const totalYourSpendings = (activeUser === '' || activeUser === 'None') ? 0 : getTotalActiveUserPaidFor(activeUser, expenses)
const currency = group.currency

return (
<div>
<div className="text-muted-foreground">
Total you paid for
</div>

<div className="text-lg">
{formatCurrency(currency, totalYourSpendings)}
</div>
</div>

)
}
46 changes: 46 additions & 0 deletions src/lib/totals.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { getGroupExpenses } from "@/lib/api";
import { match } from 'ts-pattern'

export function getTotalGroupSpending(expenses: NonNullable<Awaited<ReturnType<typeof getGroupExpenses>>>): number {
return expenses.reduce((total, expense) => (!expense.isReimbursement ? total + expense.amount : total + 0), 0)
}

export function getTotalActiveUserPaidFor(activeUserId: string | null, expenses: NonNullable<Awaited<ReturnType<typeof getGroupExpenses>>>): number {
return expenses.reduce((total, expense) => (expense.paidBy.id === activeUserId ? total + expense.amount : total + 0),0)
}

export function getTotalActiveUserShare(activeUserId: string | null, expenses: NonNullable<Awaited<ReturnType<typeof getGroupExpenses>>>): number {
let total = 0;

expenses.forEach(expense => {
const paidFors = expense.paidFor;
const userPaidFor = paidFors.find(paidFor => paidFor.participantId === activeUserId);

if (!userPaidFor) {
// If the active user is not involved in the expense, skip it
return;
}

switch (expense.splitMode) {
case 'EVENLY':
// Divide the total expense evenly among all participants
total += expense.amount / paidFors.length;
break;
case 'BY_AMOUNT':
// Directly add the user's share if the split mode is BY_AMOUNT
total += userPaidFor.shares;
break;
case 'BY_PERCENTAGE':
// Calculate the user's share based on their percentage of the total expense
total += (expense.amount * userPaidFor.shares) / 10000; // Assuming shares are out of 10000 for percentage
break;
case 'BY_SHARES':
// Calculate the user's share based on their shares relative to the total shares
const totalShares = paidFors.reduce((sum, paidFor) => sum + paidFor.shares, 0);
total += (expense.amount * userPaidFor.shares) / totalShares;
break;
}
});

return parseFloat(total.toFixed(2));
}
Loading