Merge branch 'release/1.9.0'

This commit is contained in:
2024-02-08 14:45:06 +01:00
17 changed files with 296 additions and 128 deletions

View File

@@ -0,0 +1,9 @@
import { fetchAvailableYears } from '@/app/lib/actions/monthActions';
import { NextResponse } from 'next/server';
export async function GET(request: Request) {
const availableYears = await fetchAvailableYears();
return NextResponse.json({ availableYears });
}

View File

@@ -0,0 +1,13 @@
import { fetchLocationById } from '@/app/lib/actions/locationActions';
import type { NextApiRequest } from 'next'
import { NextResponse } from 'next/server';
export const GET = async (
req: NextApiRequest,
) => {
const url = new URL(req.url as string);
const locationId = url.searchParams.get('id');
const location = await fetchLocationById(locationId as string);
return NextResponse.json({ location });
}

View File

@@ -0,0 +1,14 @@
import { fetchAllLocations } from '@/app/lib/actions/locationActions';
import type { NextApiRequest } from 'next'
import { NextResponse } from 'next/server';
export const GET = async (
req: NextApiRequest,
) => {
// get year from query params
const url = new URL(req.url as string);
const year = parseInt(url.searchParams.get('year') as string, 10);
const locations = await fetchAllLocations(year);
return NextResponse.json({ locations });
}

View File

@@ -70,7 +70,7 @@ export const fetchAvailableYears = withUser(async (user:AuthenticatedUser) => {
const dbClient = await getDbClient(); const dbClient = await getDbClient();
// query mnogodb for all `yearMonth` values // query mnogodb for all `yearMonth` values
const years = await dbClient.collection<BillingLocation>("lokacije") const years:number[] = await dbClient.collection<BillingLocation>("lokacije")
.distinct("yearMonth.year", { userId }) .distinct("yearMonth.year", { userId })
// sort the years in descending order // sort the years in descending order

View File

@@ -1,8 +1,7 @@
import { notFound } from 'next/navigation'; "use client";
import { LocationEditForm } from '@/app/ui/LocationEditForm'; import { LocationEditForm } from '@/app/ui/LocationEditForm';
import { fetchLocationById } from '@/app/lib/actions/locationActions';
import { YearMonth } from '@/app/lib/db-types'; import { YearMonth } from '@/app/lib/db-types';
import { Main } from '@/app/ui/Main';
export default async function LocationAddPage({ yearMonth }: { yearMonth:YearMonth }) { export default async function LocationAddPage({ yearMonth }: { yearMonth:YearMonth }) {
return (<LocationEditForm yearMonth={yearMonth} />); return (<LocationEditForm yearMonth={yearMonth} />);

View File

@@ -1,15 +1,16 @@
import { parseYearMonth } from '@/app/lib/format'; import { parseYearMonth } from '@/app/lib/format';
import { LocationEditFormSkeleton } from '@/app/ui/LocationEditForm';
import LocationAddPage from './LocationAddPage';
import { Main } from '@/app/ui/Main'; import { Main } from '@/app/ui/Main';
import { Suspense } from 'react'; import dynamic from 'next/dynamic'
const LocationAddPage = dynamic(
() => import('./LocationAddPage'),
{ ssr: false }
)
export default async function Page({ params:{ id } }: { params: { id:string } }) { export default async function Page({ params:{ id } }: { params: { id:string } }) {
return ( return (
<Main> <Main>
<Suspense fallback={<LocationEditFormSkeleton />}>
<LocationAddPage yearMonth={ parseYearMonth(id) } /> <LocationAddPage yearMonth={ parseYearMonth(id) } />
</Suspense>
</Main> </Main>
); );
} }

View File

@@ -1,14 +1,54 @@
"use client";
import { notFound } from 'next/navigation'; import { notFound } from 'next/navigation';
import { fetchLocationById } from '@/app/lib/actions/locationActions'; import { LocationDeleteForm, LocationDeleteFormSkeleton } from '@/app/ui/LocationDeleteForm';
import { LocationDeleteForm } from '@/app/ui/LocationDeleteForm'; import { WithId } from 'mongodb';
import { BillingLocation } from '@/app/lib/db-types';
import { useEffect, useState } from 'react';
export const LocationDeletePage = async ({ locationId }: { locationId:string }) => { const fetchLocationById = async (locationId: string) => {
const response = await fetch(`/api/locations/by-id?id=${locationId}`);
const json = await response.json();
return json.location as WithId<BillingLocation>;
}
const LocationDeletePage = ({ locationId }: { locationId:string }) => {
const [state, stateSet] = useState<{
status: 'loading' | 'error' | 'success';
location?: WithId<BillingLocation>;
error?: string;
}>({ status: 'loading' });
useEffect(() => {
const fetchLocation = async () => {
try {
const location = await fetchLocationById(locationId); const location = await fetchLocationById(locationId);
stateSet({ location, status: 'success' });
} catch(error:any) {
stateSet({ status: 'error', error: error.message });
}
};
if (!location) { fetchLocation();
}, [locationId]);
switch(state.status) {
case "error":
return(<div>Error: {state.error}</div>);
case "loading":
return(<LocationDeleteFormSkeleton />);
case "success":
if (!state.location) {
return(notFound()); return(notFound());
} }
return (<LocationDeleteForm location={location} />); return(<LocationDeleteForm location={state.location} />);
default:
return(<div>Error: Unknown status</div>);
}
} }
export default LocationDeletePage;

View File

@@ -1,17 +1,17 @@
import { notFound } from 'next/navigation';
import { fetchLocationById } from '@/app/lib/actions/locationActions';
import { LocationDeleteForm } from '@/app/ui/LocationDeleteForm';
import { Main } from '@/app/ui/Main'; import { Main } from '@/app/ui/Main';
import { Suspense } from 'react'; import dynamic from 'next/dynamic'
import { LocationDeletePage } from './LocationDeletePage';
const LocationDeletePage = dynamic(
() => import('./LocationDeletePage'),
{ ssr: false }
)
export default async function Page({ params:{ id } }: { params: { id:string } }) { export default async function Page({ params:{ id } }: { params: { id:string } }) {
return ( return (
<Main> <Main>
<Suspense fallback={<div>Loading...</div>}>
<LocationDeletePage locationId={id} /> <LocationDeletePage locationId={id} />
</Suspense>
</Main> </Main>
); );
} }

View File

@@ -1,16 +1,53 @@
"use client";
import { notFound } from 'next/navigation'; import { notFound } from 'next/navigation';
import { LocationEditForm } from '@/app/ui/LocationEditForm'; import { LocationEditForm, LocationEditFormSkeleton } from '@/app/ui/LocationEditForm';
import { fetchLocationById } from '@/app/lib/actions/locationActions'; import { useEffect, useState } from 'react';
import { WithId } from 'mongodb';
import { BillingLocation } from '@/app/lib/db-types';
export default async function LocationEditPage({ locationId }: { locationId:string }) {
const fetchLocationById = async (locationId: string) => {
const response = await fetch(`/api/locations/by-id?id=${locationId}`);
const json = await response.json();
return json.location as WithId<BillingLocation>;
}
export default function LocationEditPage({ locationId }: { locationId:string }) {
const [state, stateSet] = useState<{
status: 'loading' | 'error' | 'success';
location?: WithId<BillingLocation>;
error?: string;
}>({ status: 'loading' });
useEffect(() => {
const fetchLocation = async () => {
try {
const location = await fetchLocationById(locationId); const location = await fetchLocationById(locationId);
stateSet({ location, status: 'success' });
} catch(error:any) {
stateSet({ status: 'error', error: error.message });
}
};
if (!location) { fetchLocation();
}, [locationId]);
switch(state.status) {
case "error":
return(<div>Error: {state.error}</div>);
case "loading":
return(<LocationEditFormSkeleton />);
case "success":
if (!state.location) {
return(notFound()); return(notFound());
} }
const result = <LocationEditForm location={location} />; return(<LocationEditForm location={state.location} />);
default:
return (result); return(<div>Error: Unknown status</div>);
}
} }

View File

@@ -1,15 +1,17 @@
import { Suspense } from 'react';
import LocationEditPage from './LocationEditPage';
import { Main } from '@/app/ui/Main'; import { Main } from '@/app/ui/Main';
import { LocationEditFormSkeleton } from '@/app/ui/LocationEditForm'; import dynamic from 'next/dynamic'
const LocationEditPage = dynamic(
() => import('./LocationEditPage'),
{ ssr: false }
)
export default async function Page({ params:{ id } }: { params: { id:string } }) { export default async function Page({ params:{ id } }: { params: { id:string } }) {
return ( return (
<Main> <Main>
<Suspense fallback={<LocationEditFormSkeleton />}>
<LocationEditPage locationId={id} /> <LocationEditPage locationId={id} />
</Suspense>
</Main> </Main>
); );
} }

View File

@@ -1,7 +1,11 @@
import { FC, Suspense } from 'react'; import { FC, Suspense } from 'react';
import { Main } from './ui/Main'; import { Main } from './ui/Main';
import HomePage from './ui/HomePage'; import dynamic from 'next/dynamic'
import { HomePageSkeleton } from './ui/MonthCardSceleton';
const HomePage = dynamic(
() => import('./ui/HomePage'),
{ ssr: false }
)
export interface PageProps { export interface PageProps {
searchParams?: { searchParams?: {
@@ -14,9 +18,7 @@ const Page:FC<PageProps> = async ({ searchParams }) => {
return ( return (
<Main> <Main>
<Suspense fallback={<HomePageSkeleton />}> <HomePage />
<HomePage searchParams={searchParams} />
</Suspense>
</Main> </Main>
); );
} }

View File

@@ -6,7 +6,6 @@ import React, { FC } from "react";
import { useFormState } from "react-dom"; import { useFormState } from "react-dom";
import { updateOrAddBill } from "../lib/actions/billActions"; import { updateOrAddBill } from "../lib/actions/billActions";
import Link from "next/link"; import Link from "next/link";
import { gotoHome } from "../lib/actions/navigationActions";
import { formatYearMonth } from "../lib/format"; import { formatYearMonth } from "../lib/format";
// Next.js does not encode an utf-8 file name correctly when sending a form with a file attachment // Next.js does not encode an utf-8 file name correctly when sending a form with a file attachment
@@ -35,11 +34,6 @@ export const BillEditForm:FC<BillEditFormProps> = ({ location, bill }) => {
const [ isPaid, setIsPaid ] = React.useState<boolean>(paid); const [ isPaid, setIsPaid ] = React.useState<boolean>(paid);
// redirect to the main page
const handleCancel = () => {
gotoHome(location.yearMonth);
};
const billPaid_handleChange = (event: React.ChangeEvent<HTMLInputElement>) => { const billPaid_handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setIsPaid(event.target.checked); setIsPaid(event.target.checked);
} }

View File

@@ -1,39 +1,58 @@
import { fetchAllLocations } from '@/app/lib/actions/locationActions'; "use client";
import { fetchAvailableYears } from '@/app/lib/actions/monthActions';
import { BillingLocation, YearMonth } from '@/app/lib/db-types'; import { BillingLocation, YearMonth } from '@/app/lib/db-types';
import { FC } from 'react'; import { FC, useEffect, useState } from 'react';
import { MonthLocationList } from '@/app/ui/MonthLocationList'; import { MonthLocationList } from '@/app/ui/MonthLocationList';
import { WithId } from 'mongodb';
import { MonthCardSkeleton } from './MonthCardSkeleton';
import { useSearchParams } from 'next/navigation';
export interface HomePageProps { export interface HomePageProps {
searchParams?: {
year?: string;
month?: string;
};
} }
export const HomePage:FC<HomePageProps> = async ({ searchParams }) => { type MonthsLocations = {
[key:string]:{
yearMonth: YearMonth,
locations: BillingLocation[],
monthlyExpense: number
}
}
let availableYears: number[]; const fetchAllLocations = async (year: number) => {
const response = await fetch(`/api/locations/in-year/?year=${year}`);
const { locations } : { locations: WithId<BillingLocation>[] } = await response.json();
return locations;
}
// const asyncTimout = (ms:number) => new Promise(resolve => setTimeout(resolve, ms)); const fetchAvailableYears = async () => {
// await asyncTimout(5000); const response = await fetch(`/api/locations/available-years/`);
const { availableYears }: { availableYears: number[]} = await response.json();
return availableYears;
}
export const HomePage:FC<HomePageProps> = () => {
const searchParams = useSearchParams();
const year = searchParams.get('year');
const currentYear = year ? parseInt(year, 10) : new Date().getFullYear();
const [ homePageStatus, setHomePageStatus ] = useState<{
status: "loading" | "loaded" | "error",
availableYears: number[],
months?: MonthsLocations,
error?: string
}>({
status: "loading",
availableYears: [],
});
const {availableYears, months, status, error} = homePageStatus;
useEffect(() => {
const fetchData = async () => {
try { try {
availableYears = await fetchAvailableYears();
} catch (error:any) {
return (
<main className="flex min-h-screen flex-col p-6 bg-base-300">
<p className="text-center text-2xl text-red-500">{error.message}</p>
</main>);
}
// if the database is in it's initial state, show the add location button for the current month
if(availableYears.length === 0) {
return (<MonthLocationList />);
}
const currentYear = Number(searchParams?.year) || availableYears[0];
const locations = await fetchAllLocations(currentYear); const locations = await fetchAllLocations(currentYear);
// group locations by month // group locations by month
@@ -62,11 +81,44 @@ export const HomePage:FC<HomePageProps> = async ({ searchParams }) => {
monthlyExpense: location.bills.reduce((acc, bill) => bill.paid ? acc + (bill.payedAmount ?? 0) : acc, 0) monthlyExpense: location.bills.reduce((acc, bill) => bill.paid ? acc + (bill.payedAmount ?? 0) : acc, 0)
} }
}); });
}, {} as {[key:string]:{ }, {} as MonthsLocations);
yearMonth: YearMonth,
locations: BillingLocation[], setHomePageStatus({
monthlyExpense: number availableYears: await fetchAvailableYears(),
} }); months,
status: "loaded",
});
} catch (error: any) {
setHomePageStatus({
status: "error",
availableYears: [],
error: error.message
});
}
}
fetchData();
}, [currentYear]);
if(status === "loading") {
return (
<>
<MonthCardSkeleton checked={true} />
<MonthCardSkeleton />
<MonthCardSkeleton />
</>
);
}
if(status === "error") {
return(<p className="text-center text-2xl text-red-500">{error}</p>);
}
// if the database is in it's initial state, show the add location button for the current month
if(availableYears.length === 0) {
return (<MonthLocationList />);
}
return ( return (
<MonthLocationList availableYears={availableYears} months={months} /> <MonthLocationList availableYears={availableYears} months={months} />

View File

@@ -29,11 +29,23 @@ export const LocationDeleteForm:FC<LocationDeleteFormProps> = ({ location }) =>
Please confirm deletion of location <strong>{location.name}</strong>. Please confirm deletion of location <strong>{location.name}</strong>.
</p> </p>
<div className="pt-4 text-center"> <div className="pt-4 text-center">
<button className="btn btn-primary">Confim</button> <button className="btn btn-primary w-[5.5em]">Confim</button>
<Link className="btn btn-neutral ml-3" href={`/location/${location._id}/edit/`}>Cancel</Link> <Link className="btn btn-neutral w-[5.5em] ml-3" href={`/location/${location._id}/edit/`}>Cancel</Link>
</div> </div>
</form> </form>
</div> </div>
</div> </div>
); );
} }
export const LocationDeleteFormSkeleton:FC = () =>
<div className="card card-compact card-bordered min-w-[20em] max-w-[90em] bg-base-100 shadow-s my-1">
<div className="card-body">
<p className="py-6 px-6"></p>
<div className="pt-4 text-center">
<div className="btn skeleton w-[5.5em]"></div>
<div className="btn ml-3 skeleton w-[5.5em]"></div>
</div>
</div>
</div>

View File

@@ -6,7 +6,6 @@ import { BillingLocation, YearMonth } from "../lib/db-types";
import { updateOrAddLocation } from "../lib/actions/locationActions"; import { updateOrAddLocation } from "../lib/actions/locationActions";
import { useFormState } from "react-dom"; import { useFormState } from "react-dom";
import Link from "next/link"; import Link from "next/link";
import { gotoHome } from "../lib/actions/navigationActions";
export type LocationEditFormProps = { export type LocationEditFormProps = {
/** location which should be edited */ /** location which should be edited */
@@ -48,7 +47,7 @@ export const LocationEditForm:FC<LocationEditFormProps> = ({ location, yearMonth
))} ))}
</div> </div>
<textarea id="locationNotes" name="locationNotes" className="textarea textarea-bordered my-1 w-full block" placeholder="Opis" defaultValue={location?.notes ?? ""}></textarea> <textarea id="locationNotes" name="locationNotes" className="textarea textarea-bordered my-1 w-full block h-[8em]" placeholder="Opis" defaultValue={location?.notes ?? ""}></textarea>
<div id="status-error" aria-live="polite" aria-atomic="true"> <div id="status-error" aria-live="polite" aria-atomic="true">
{state.errors?.locationNotes && {state.errors?.locationNotes &&
state.errors.locationNotes.map((error: string) => ( state.errors.locationNotes.map((error: string) => (
@@ -66,10 +65,9 @@ export const LocationEditForm:FC<LocationEditFormProps> = ({ location, yearMonth
</p> </p>
} }
</div> </div>
<div className="pt-4"> <div className="pt-4">
<button className="btn btn-primary">Save</button> <button className="btn btn-primary w-[5.5em]">Save</button>
<Link className="btn btn-neutral ml-3" href={`/?year=${year}&month=${month}`}>Cancel</Link> <Link className="btn btn-neutral w-[5.5em] ml-3" href={`/?year=${year}&month=${month}`}>Cancel</Link>
</div> </div>
</form> </form>
</div> </div>
@@ -80,10 +78,14 @@ export const LocationEditForm:FC<LocationEditFormProps> = ({ location, yearMonth
export const LocationEditFormSkeleton:FC = () => export const LocationEditFormSkeleton:FC = () =>
{ {
return( return(
<div className="skeleton card card-compact card-bordered min-w-[20em] max-w-[90em] bg-base-100 shadow-s my-1"> <div className="card card-compact card-bordered min-w-[20em] max-w-[90em] bg-base-100 shadow-s my-1">
<div className="card-body"> <div className="card-body">
<input id="locationName" name="locationName" type="text" placeholder="Naziv lokacije" className="input input-bordered w-full" /> <div id="locationName" className="input w-full skeleton"></div>
<textarea id="locationNotes" name="locationNotes" className="textarea textarea-bordered my-1 w-full block" placeholder="Opis"></textarea> <div id="locationNotes" className="textarea my-1 w-full block h-[8em] skeleton"></div>
<div className="pt-4">
<div className="btn w-[5.5em] skeleton"></div>
<div className="btn w-[5.5em] ml-3 skeleton"></div>
</div>
</div> </div>
</div> </div>
) )

View File

@@ -15,18 +15,9 @@ export interface MonthCardSkeletonProps {
export const MonthCardSkeleton: React.FC<MonthCardSkeletonProps> = ({checked=false}) => export const MonthCardSkeleton: React.FC<MonthCardSkeletonProps> = ({checked=false}) =>
<div className={`skeleton collapse collapse-plus bg-base-200 my-1`}> <div className={`skeleton collapse collapse-plus bg-base-200 my-1`}>
<input type="checkbox" name="my-accordion-3" checked={checked} disabled /> <input type="checkbox" name="my-accordion-3" checked={checked} disabled />
<div className="collapse-title text-xl font-medium w-[15em]"> <div className="text-xl w-[15em]"></div>
</div>
<div className="collapse-content"> <div className="collapse-content">
<LocationCardSkeleton /> <LocationCardSkeleton />
<LocationCardSkeleton /> <LocationCardSkeleton />
</div> </div>
</div>; </div>;
export const HomePageSkeleton: React.FC = () =>
<>
<MonthCardSkeleton checked={true} />
<MonthCardSkeleton />
<MonthCardSkeleton />
</>;

View File

@@ -9,7 +9,7 @@ networks:
services: services:
web-app: web-app:
image: utility-bills-tracker:1.8.0 image: utility-bills-tracker:1.9.0
networks: networks:
- traefik-network - traefik-network
- mongo-network - mongo-network