diff --git a/app/lib/auth.ts b/app/lib/auth.ts index fa146d9..f294bcf 100644 --- a/app/lib/auth.ts +++ b/app/lib/auth.ts @@ -2,6 +2,7 @@ import NextAuth, { NextAuthConfig } from 'next-auth'; import GoogleProvider from 'next-auth/providers/google'; import { Session } from 'next-auth'; import { AuthenticatedUser } from './types/next-auth'; +import { BillingLocation } from './db-types'; const authConfig: NextAuthConfig = { callbacks: { @@ -48,7 +49,18 @@ const authConfig: NextAuthConfig = { export const { auth, handlers: { GET, POST } } = NextAuth(authConfig); -export const withUser = (fn: (user: AuthenticatedUser, ...args:any) => Promise) => async (...args:any) => { +export type AuthErrorMessage = { + message: string, + errors: { + message: string, + } +} + +export const isAuthErrorMessage = (obj: any): obj is AuthErrorMessage => { + return (obj.message && obj.errors && obj.errors.message); +} + +export const withUser = (fn: (user: AuthenticatedUser, ...args:any) => Promise>) => async (...args:any) => { const session = await auth(); if(!session) { @@ -57,7 +69,7 @@ export const withUser = (fn: (user: AuthenticatedUser, ...args:any) => Promise { return(yearMonth % 100 === 12 ? yearMonth + 89 : yearMonth + 1); } +const formatCurrency = (amount:number) => { + // format number wirh 2 decimal places and a thousand separator + const formattedAmount = amount.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,'); + return(formattedAmount); +} + + export const Page = async () => { const locations = await fetchAllLocations(); + if(isAuthErrorMessage(locations)) { + return ( +
+

{locations.message}

+
); + } + // if the database is in it's initial state, show the add location button for the current month if(locations.length === 0) { const currentYearMonth = new Date().getFullYear() * 100 + new Date().getMonth() + 1; @@ -28,25 +40,47 @@ export const Page = async () => { ); } + let monthlyExpense = 0; + return (
{ locations.map((location, ix, array) => { + + const isFirstLocationInMonth = ix === 0 || location.yearMonth !== array[ix-1].yearMonth; + const isLastLocationInMonth = location.yearMonth !== array[ix+1]?.yearMonth; + const isLastLocationOfFirstMonth = isLastLocationInMonth && location.yearMonth === array[0].yearMonth; + + if(isFirstLocationInMonth) { + monthlyExpense = 0; + } + + monthlyExpense += location.bills.reduce((acc, bill) => acc + (bill.payedAmount ?? 0), 0); return ( <> { // show month title above the first LocationCard in the month - ix === 0 || location.yearMonth !== array[ix-1].yearMonth ? + isFirstLocationInMonth ? : null } { // show AddLocationButton as a last item in the firts month - location.yearMonth === array[0].yearMonth && location.yearMonth !== array[ix+1]?.yearMonth ? + isLastLocationOfFirstMonth ? : null } + { + isLastLocationInMonth && monthlyExpense>0 ? +
+ +

+ Total monthly expenditure: { formatCurrency(monthlyExpense/100) } +

+
+
: null + } ) })