feat: add multi-bill-edit page for batch bill status updates
- Add getLocationsByMonth server action with aggregation pipeline to calculate hasAttachment - Add updateMonth server action for bulk bill status updates with path revalidation - Create multi-bill-edit page at /home/multi-bill-edit/[year]/[month] - Implement MultiBillEdit component with toggle functionality for all bills - Add BillToggleBadge component integration for consistent bill display - Add "set all as paid/unpaid" toggle button for batch operations - Implement server-side redirect with success message after save - Add Suspense boundary with loading skeleton - Update translations for multi-bill-edit feature (Croatian and English) - Ensure data freshness with unstable_noStore and revalidatePath 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,24 @@
|
||||
import { FC } from "react"
|
||||
import { Bill } from "@/app/lib/db-types"
|
||||
import { TicketIcon } from "@heroicons/react/24/outline"
|
||||
|
||||
export interface BillBadgeProps {
|
||||
locationId: string,
|
||||
bill: Pick<Bill, 'name' | 'paid' | 'hasAttachment' | 'proofOfPayment'>,
|
||||
onClick?: () => void
|
||||
};
|
||||
|
||||
export const BillToggleBadge:FC<BillBadgeProps> = ({ bill: { name, paid, hasAttachment, proofOfPayment }, onClick}) => {
|
||||
|
||||
const className = `badge badge-lg ${paid?"badge-success":" badge-outline"} ${ !paid && hasAttachment ? "btn-outline btn-success" : "" } cursor-pointer`;
|
||||
|
||||
return (
|
||||
<div className={className} onClick={onClick}>
|
||||
{name}
|
||||
{
|
||||
proofOfPayment?.uploadedAt ?
|
||||
<TicketIcon className="h-[1em] w-[1em] inline-block ml-1" /> : null
|
||||
}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
'use client';
|
||||
|
||||
import { FC, useState } from "react";
|
||||
import { BillingLocation, YearMonth } from "../../../../../lib/db-types";
|
||||
import { formatYearMonth } from "../../../../../lib/format";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { updateMonth } from "../../../../../lib/actions/monthActions";
|
||||
import { toast, ToastContainer } from 'react-toastify';
|
||||
import 'react-toastify/dist/ReactToastify.css';
|
||||
import { BillToggleBadge } from "./BillToggleBadge";
|
||||
|
||||
export interface MultiBillEditProps {
|
||||
locations: BillingLocation[];
|
||||
year: number;
|
||||
month: number;
|
||||
}
|
||||
|
||||
interface BillState {
|
||||
locationId: string;
|
||||
billId: string;
|
||||
paid: boolean;
|
||||
}
|
||||
|
||||
export const MultiBillEdit: FC<MultiBillEditProps> = ({ locations, year, month }) => {
|
||||
const t = useTranslations("multi-bill-edit");
|
||||
const router = useRouter();
|
||||
|
||||
// Initialize bill states from locations
|
||||
const initialBillStates: BillState[] = locations.flatMap(location =>
|
||||
location.bills.map(bill => ({
|
||||
locationId: location._id,
|
||||
billId: bill._id,
|
||||
paid: bill.paid,
|
||||
}))
|
||||
);
|
||||
|
||||
const [billStates, setBillStates] = useState<BillState[]>(initialBillStates);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const [allPaidMode, setAllPaidMode] = useState(false);
|
||||
|
||||
// Toggle individual bill paid status
|
||||
const handleBillToggle = (locationId: string, billId: string) => {
|
||||
setBillStates(prevStates =>
|
||||
prevStates.map(state =>
|
||||
state.locationId === locationId && state.billId === billId
|
||||
? { ...state, paid: !state.paid }
|
||||
: state
|
||||
)
|
||||
);
|
||||
};
|
||||
|
||||
// Toggle all bills paid status
|
||||
const handleSetAllAsPayed = () => {
|
||||
const newPaidState = !allPaidMode;
|
||||
setAllPaidMode(newPaidState);
|
||||
setBillStates(prevStates =>
|
||||
prevStates.map(state => ({ ...state, paid: newPaidState }))
|
||||
);
|
||||
};
|
||||
|
||||
// Save changes to database
|
||||
const handleSave = async () => {
|
||||
setIsSaving(true);
|
||||
try {
|
||||
const updates = billStates.map(state => ({
|
||||
locationId: state.locationId,
|
||||
billId: state.billId,
|
||||
paid: state.paid,
|
||||
}));
|
||||
|
||||
await updateMonth({ year, month }, updates);
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error saving bill updates:', error);
|
||||
toast.error(t("save-error-message"), { theme: "dark" });
|
||||
setIsSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Cancel and return to home page
|
||||
const handleCancel = () => {
|
||||
router.push(`/home?year=${year}`);
|
||||
};
|
||||
|
||||
// Get bill state for a specific bill
|
||||
const getBillState = (locationId: string, billId: string): boolean => {
|
||||
const state = billStates.find(
|
||||
s => s.locationId === locationId && s.billId === billId
|
||||
);
|
||||
return state?.paid ?? false;
|
||||
};
|
||||
|
||||
const yearMonth: YearMonth = { year, month };
|
||||
|
||||
return (
|
||||
<div className={`collapse bg-base-200 my-1 sm:min-w-[25em] border-2 border-neutral`}>
|
||||
<h1 className="text-xl font-medium text-white collapse-title ml-1">{formatYearMonth(yearMonth)}</h1>
|
||||
<div className="absolute cursor-pointer top-4 right-[20px]">
|
||||
<BillToggleBadge locationId={"dummy"}
|
||||
bill={{ paid:allPaidMode, name: allPaidMode ? t("set-all-as-unpaid-button") : t("set-all-as-paid-button"), hasAttachment: false, proofOfPayment: undefined }}
|
||||
onClick={handleSetAllAsPayed}
|
||||
/>
|
||||
</div>
|
||||
<div className="p-[16px] pt-0">
|
||||
{locations.map(location => (
|
||||
<div key={location._id} className="card card-compact card-bordered max-w-[30em] bg-base-100 border-1 border-neutral mb-2">
|
||||
<div className="card-body">
|
||||
<h2 className="card-title text-[1rem]">
|
||||
{formatYearMonth(yearMonth)} {location.name}
|
||||
</h2>
|
||||
<div className="space-y-4 mt-[-.5rem]">
|
||||
{location.bills.length > 0 ? (
|
||||
<div className="flex flex-wrap gap-2 mt-2">
|
||||
{location.bills.map(bill => {
|
||||
const isPaid = getBillState(location._id, bill._id);
|
||||
return (
|
||||
<BillToggleBadge
|
||||
key={bill._id}
|
||||
locationId={location._id}
|
||||
bill={{ ...bill, paid: isPaid }}
|
||||
onClick={() => handleBillToggle(location._id, bill._id)}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-sm text-gray-500">{t("no-bills-message")}</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{/* Action buttons */}
|
||||
<div className="pt-4">
|
||||
<button
|
||||
onClick={handleSave}
|
||||
className="btn btn-primary ml-3"
|
||||
disabled={isSaving}
|
||||
>
|
||||
{isSaving ? (
|
||||
<>
|
||||
<span className="loading loading-spinner loading-sm"></span>
|
||||
{t("saving-button")}
|
||||
</>
|
||||
) : (
|
||||
t("save-button")
|
||||
)}
|
||||
</button>
|
||||
<button
|
||||
onClick={handleCancel}
|
||||
className="btn btn-neutral ml-3"
|
||||
disabled={isSaving}
|
||||
>
|
||||
{t("cancel-button")}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<ToastContainer />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,26 @@
|
||||
"use client";
|
||||
|
||||
import { InboxStackIcon, Square3Stack3DIcon } from '@heroicons/react/24/outline';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { YearMonth } from '../../../../../lib/db-types';
|
||||
import Link from 'next/link';
|
||||
|
||||
export interface MultiBillEditButtonProps {
|
||||
yearMonth: YearMonth;
|
||||
}
|
||||
|
||||
export const MultiBillEditButton: React.FC<MultiBillEditButtonProps> = ({ yearMonth }) => {
|
||||
|
||||
const t = useTranslations("home-page.multi-bill-edit-button");
|
||||
|
||||
return (
|
||||
<div className="card card-compact card-bordered bg-base-100 shadow-s my-1">
|
||||
<Link href={`/home/multi-bill-edit/${yearMonth.year}/${yearMonth.month}`} className="card-body tooltip self-center" data-tip={t("tooltip")} data-umami-event="add-new-location">
|
||||
<span className='flex self-center'>
|
||||
<Square3Stack3DIcon className="h-[1em] w-[1em] cursor-pointer text-4xl" />
|
||||
<span className="ml-1 self-center text-xs text-left leading-[1.2em] w-[5.5em]">{t("tooltip")}</span>
|
||||
</span>
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,16 @@
|
||||
import { notFound } from 'next/navigation';
|
||||
import { MultiBillEdit } from '@/app/[locale]/home/multi-bill-edit/[year]/[month]/MultiBillEdit';
|
||||
import { getLocationsByMonth } from '@/app/lib/actions/monthActions';
|
||||
|
||||
export default async function MultiBillEditPage({ year, month }: { year: number; month: number }) {
|
||||
|
||||
const locations = await getLocationsByMonth({ year, month });
|
||||
|
||||
if (!locations || locations.length === 0) {
|
||||
return(notFound());
|
||||
}
|
||||
|
||||
const result = <MultiBillEdit locations={locations} year={year} month={month} />;
|
||||
|
||||
return (result);
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import { NotFoundPage } from '@/app/ui/NotFoundPage';
|
||||
|
||||
const MultiBillEditNotFound = () =>
|
||||
<NotFoundPage title="404 Month Not Found" description="Could not find the requested month." />;
|
||||
|
||||
export default MultiBillEditNotFound;
|
||||
21
app/[locale]/home/multi-bill-edit/[year]/[month]/page.tsx
Normal file
21
app/[locale]/home/multi-bill-edit/[year]/[month]/page.tsx
Normal file
@@ -0,0 +1,21 @@
|
||||
import { Suspense } from 'react';
|
||||
import MultiBillEditPage from './MultiBillEditPage';
|
||||
import { Main } from '@/app/ui/Main';
|
||||
|
||||
const MultiBillEditSkeleton = () => (
|
||||
<div className="flex min-h-screen flex-col items-center justify-center p-6 bg-base-300">
|
||||
<span className="loading loading-spinner loading-lg"></span>
|
||||
<p className="mt-4">Loading...</p>
|
||||
</div>
|
||||
);
|
||||
|
||||
export default async function Page({ params }: { params: { year: string; month: string } }) {
|
||||
|
||||
return (
|
||||
<Main>
|
||||
<Suspense fallback={<MultiBillEditSkeleton />}>
|
||||
<MultiBillEditPage year={parseInt(params.year)} month={parseInt(params.month)} />
|
||||
</Suspense>
|
||||
</Main>
|
||||
);
|
||||
}
|
||||
@@ -5,7 +5,9 @@ import { ObjectId } from 'mongodb';
|
||||
import { Bill, BillingLocation, YearMonth } from '../db-types';
|
||||
import { AuthenticatedUser } from '../types/next-auth';
|
||||
import { withUser } from '../auth';
|
||||
import { unstable_noStore as noStore } from 'next/cache';
|
||||
import { unstable_noStore as noStore, unstable_noStore, revalidatePath } from 'next/cache';
|
||||
import { getLocale } from 'next-intl/server';
|
||||
import { gotoHomeWithMessage } from './navigationActions';
|
||||
|
||||
/**
|
||||
* Server-side action which adds a new month to the database
|
||||
@@ -82,3 +84,137 @@ export const fetchAvailableYears = withUser(async (user:AuthenticatedUser) => {
|
||||
|
||||
return(sortedYears);
|
||||
})
|
||||
|
||||
/**
|
||||
* Fetches all locations for a specific month for the authenticated user
|
||||
* Only projects essential fields needed for the multi-bill-edit page
|
||||
* @param yearMonth - The year and month to fetch
|
||||
* @returns Array of locations with minimal bill data
|
||||
*/
|
||||
export const getLocationsByMonth = withUser(async (user: AuthenticatedUser, yearMonth: YearMonth) => {
|
||||
|
||||
unstable_noStore();
|
||||
|
||||
const { id: userId } = user;
|
||||
const dbClient = await getDbClient();
|
||||
|
||||
// Use aggregation pipeline to calculate hasAttachment field
|
||||
const locations = await dbClient.collection<BillingLocation>("lokacije")
|
||||
.aggregate([
|
||||
{
|
||||
$match: {
|
||||
userId,
|
||||
yearMonth: {
|
||||
year: yearMonth.year,
|
||||
month: yearMonth.month,
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
$addFields: {
|
||||
_id: { $toString: "$_id" },
|
||||
bills: {
|
||||
$map: {
|
||||
input: "$bills",
|
||||
as: "bill",
|
||||
in: {
|
||||
_id: { $toString: "$$bill._id" },
|
||||
name: "$$bill.name",
|
||||
paid: "$$bill.paid",
|
||||
hasAttachment: { $ne: ["$$bill.attachment", null] },
|
||||
proofOfPayment: "$$bill.proofOfPayment",
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
$project: {
|
||||
"_id": 1,
|
||||
"name": 1,
|
||||
"yearMonth.year": 1,
|
||||
"yearMonth.month": 1,
|
||||
"bills._id": 1,
|
||||
"bills.name": 1,
|
||||
"bills.paid": 1,
|
||||
"bills.hasAttachment": 1,
|
||||
"bills.proofOfPayment.uploadedAt": 1,
|
||||
}
|
||||
},
|
||||
{
|
||||
$sort: {
|
||||
name: 1,
|
||||
},
|
||||
},
|
||||
])
|
||||
.toArray();
|
||||
|
||||
return locations as Array<BillingLocation>;
|
||||
});
|
||||
|
||||
/**
|
||||
* Updates the paid status of bills for locations in a specific month
|
||||
* @param yearMonth - The year and month to update
|
||||
* @param updates - Array of updates with locationId, billId, and paid status
|
||||
* @returns Success status
|
||||
*/
|
||||
export const updateMonth = withUser(async (
|
||||
user: AuthenticatedUser,
|
||||
yearMonth: YearMonth,
|
||||
updates: Array<{ locationId: string; billId: string; paid: boolean }>
|
||||
) => {
|
||||
unstable_noStore();
|
||||
|
||||
const { id: userId } = user;
|
||||
const dbClient = await getDbClient();
|
||||
|
||||
// Group updates by location to minimize database operations
|
||||
const updatesByLocation = updates.reduce((acc, update) => {
|
||||
if (!acc[update.locationId]) {
|
||||
acc[update.locationId] = [];
|
||||
}
|
||||
acc[update.locationId].push(update);
|
||||
return acc;
|
||||
}, {} as Record<string, typeof updates>);
|
||||
|
||||
// Perform bulk updates
|
||||
const updatePromises = Object.entries(updatesByLocation).map(
|
||||
async ([locationId, locationUpdates]) => {
|
||||
// For each bill update in this location
|
||||
const billUpdatePromises = locationUpdates.map(({ billId, paid }) =>
|
||||
dbClient.collection<BillingLocation>("lokacije").updateOne(
|
||||
{
|
||||
_id: locationId,
|
||||
userId, // Ensure the location belongs to the authenticated user
|
||||
yearMonth: {
|
||||
year: yearMonth.year,
|
||||
month: yearMonth.month,
|
||||
},
|
||||
'bills._id': billId,
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
'bills.$.paid': paid,
|
||||
},
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
return Promise.all(billUpdatePromises);
|
||||
}
|
||||
);
|
||||
|
||||
await Promise.all(updatePromises);
|
||||
|
||||
// Revalidate the home page and multi-edit page to show fresh data
|
||||
revalidatePath('/home');
|
||||
revalidatePath(`/home/multi-bill-edit/${yearMonth.year}/${yearMonth.month}`);
|
||||
|
||||
// Redirect to home page with year and month parameters, including success message
|
||||
if (yearMonth) {
|
||||
const locale = await getLocale();
|
||||
await gotoHomeWithMessage(locale, 'bill-multi-edit-saved', yearMonth);
|
||||
}
|
||||
|
||||
return { success: true };
|
||||
});
|
||||
|
||||
@@ -12,6 +12,7 @@ import { useRouter, useSearchParams } from "next/navigation";
|
||||
import { ToastContainer, toast } from 'react-toastify';
|
||||
import 'react-toastify/dist/ReactToastify.css';
|
||||
import { useTranslations } from "next-intl";
|
||||
import { MultiBillEditButton } from "../[locale]/home/multi-bill-edit/[year]/[month]/MultiBillEditButton";
|
||||
|
||||
const getNextYearMonth = (yearMonth:YearMonth) => {
|
||||
const {year, month} = yearMonth;
|
||||
@@ -84,6 +85,12 @@ export const MonthLocationList:React.FC<MonthLocationListProps > = ({
|
||||
params.delete('locationDeleted');
|
||||
messageShown = true;
|
||||
}
|
||||
|
||||
if (search.get('bill-multi-edit-saved') === 'true') {
|
||||
toast.success(t("bill-multi-edit-save-success-message"), { theme: "dark" });
|
||||
params.delete('bill-multi-edit-saved');
|
||||
messageShown = true;
|
||||
}
|
||||
}, [search, router, t]);
|
||||
|
||||
if(!availableYears || !months) {
|
||||
@@ -128,6 +135,7 @@ export const MonthLocationList:React.FC<MonthLocationListProps > = ({
|
||||
<div className="flex gap-2 justify-center">
|
||||
<AddLocationButton yearMonth={yearMonth} />
|
||||
<PrintButton yearMonth={yearMonth} />
|
||||
<MultiBillEditButton yearMonth={yearMonth} />
|
||||
</div>
|
||||
</MonthCard>
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user