Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
5 changes: 2 additions & 3 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ name: CI

on:
push:
branches: [ main ]
branches: [main]
pull_request:
branches: [ main ]
branches: [main]

jobs:
build:
Expand Down Expand Up @@ -84,4 +84,3 @@ jobs:

- name: Build
run: npm run build

47 changes: 30 additions & 17 deletions __tests__/InvoicesPage.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,27 +14,32 @@ beforeEach(() => {
if (urlStr.endsWith('api/clients') || urlStr === 'api/clients') {
return Promise.resolve({
ok: true,
json: () => Promise.resolve({ clients: [{ id: '1', name: 'Test Client', hourlyRate: 100 }] }),
json: () =>
Promise.resolve({ clients: [{ id: '1', name: 'Test Client', hourlyRate: 100 }] }),
});
}
if (urlStr.endsWith('api/invoices') || urlStr === 'api/invoices') {
return Promise.resolve({
ok: true,
json: () => Promise.resolve({
invoices: [
{
id: '1',
totalHours: 10,
totalAmount: 1000,
createdAt: new Date().toISOString(),
client: { name: 'Test Client' },
isPaid: paid,
},
],
}),
json: () =>
Promise.resolve({
invoices: [
{
id: '1',
totalHours: 10,
totalAmount: 1000,
createdAt: new Date().toISOString(),
client: { name: 'Test Client' },
isPaid: paid,
},
],
}),
});
}
if ((urlStr.endsWith('/api/invoices/') || urlStr.includes('/api/invoices/')) && options?.method === 'PATCH') {
if (
(urlStr.endsWith('/api/invoices/') || urlStr.includes('/api/invoices/')) &&
options?.method === 'PATCH'
) {
paid = true;
return Promise.resolve({
ok: true,
Expand Down Expand Up @@ -83,10 +88,16 @@ describe('Invoices page', () => {
if (urlStr.endsWith('api/clients') || urlStr === 'api/clients') {
return Promise.resolve({
ok: true,
json: () => Promise.resolve({ clients: [{ id: '1', name: 'Test Client', hourlyRate: 100 }] }),
json: () =>
Promise.resolve({ clients: [{ id: '1', name: 'Test Client', hourlyRate: 100 }] }),
});
}
if ((urlStr.endsWith('/api/invoices') || urlStr === 'api/invoices' || urlStr.endsWith('api/invoices')) && options?.method === 'POST') {
if (
(urlStr.endsWith('/api/invoices') ||
urlStr === 'api/invoices' ||
urlStr.endsWith('api/invoices')) &&
options?.method === 'POST'
) {
lastPostBody = JSON.parse(String(options.body));
return Promise.resolve({ ok: true, json: () => Promise.resolve({}) });
}
Expand All @@ -112,7 +123,9 @@ describe('Invoices page', () => {

// fill required date inputs (native validation prevents submit otherwise)
const { container } = rendered;
const dateInputs = container.querySelectorAll('input[type="date"]') as NodeListOf<HTMLInputElement>;
const dateInputs = container.querySelectorAll(
'input[type="date"]',
) as NodeListOf<HTMLInputElement>;
const today = new Date().toISOString().slice(0, 10);
if (dateInputs.length >= 2) {
fireEvent.change(dateInputs[0], { target: { value: today } });
Expand Down
20 changes: 13 additions & 7 deletions app/api/invoices/[id]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,18 +63,24 @@ export async function GET(_req: Request, { params }: { params: Promise<{ id: str
};
});

return Response.json({ invoice, entries });
const now = new Date();
const invoiceWithOverdue = {
...invoice,
isOverdue: !invoice.isPaid && !!invoice.dueDate && new Date(invoice.dueDate) < now,
};

return Response.json({ invoice: invoiceWithOverdue, entries });
}

export async function PATCH(req: Request, {params}: { params: Promise<{id: string}> }) {
export async function PATCH(req: Request, { params }: { params: Promise<{ id: string }> }) {
validateEnv();
const session = await getServerSession(authOptions);

if(!session || !session.user?.email){
if (!session || !session.user?.email) {
return Response.json({ error: 'Unauthorized' }, { status: 401 });
}

const {id} = await params;
const { id } = await params;
let body: unknown;
try {
body = await req.json();
Expand All @@ -83,8 +89,8 @@ export async function PATCH(req: Request, {params}: { params: Promise<{id: strin
}
const { isPaid } = (body ?? {}) as { isPaid?: unknown };

if(typeof isPaid !== 'boolean'){
return Response.json({error: 'Missing or invalid isPaid'}, {status: 400});
if (typeof isPaid !== 'boolean') {
return Response.json({ error: 'Missing or invalid isPaid' }, { status: 400 });
}

const user = await prisma.user.findUnique({
Expand Down Expand Up @@ -112,4 +118,4 @@ export async function PATCH(req: Request, {params}: { params: Promise<{id: strin
console.error(error);
return Response.json({ error: 'Invoice not found or update failed' }, { status: 404 });
}
}
}
14 changes: 12 additions & 2 deletions app/api/invoices/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,13 @@ export async function GET() {
orderBy: { createdAt: 'desc' },
});

return Response.json({ invoices });
const now = new Date();
const invoicesWithOverdue = invoices.map((inv) => ({
...inv,
isOverdue: !inv.isPaid && !!inv.dueDate && new Date(inv.dueDate) < now,
}));

return Response.json({ invoices: invoicesWithOverdue });
}

export async function POST(req: Request) {
Expand All @@ -37,7 +43,7 @@ export async function POST(req: Request) {
return Response.json({ error: 'Unauthorized' }, { status: 401 });
}

const { clientId, startDate, endDate, hourlyRate } = await req.json();
const { clientId, startDate, endDate, hourlyRate, dueDate } = await req.json();

if (!clientId || !startDate || !endDate) {
return Response.json({ error: 'Missing required fields' }, { status: 400 });
Expand Down Expand Up @@ -105,6 +111,9 @@ export async function POST(req: Request) {

const totalAmount = totalHours * rate;

// default dueDate to 30 days from now if not provided
const due = dueDate ? new Date(dueDate) : new Date(Date.now() + 30 * 24 * 60 * 60 * 1000);

const invoiceData: Prisma.InvoiceUncheckedCreateInput = {
totalHours: parseFloat(totalHours.toFixed(2)),
totalAmount: parseFloat(totalAmount.toFixed(2)),
Expand All @@ -113,6 +122,7 @@ export async function POST(req: Request) {
periodEnd: to,
clientId,
userId: user.id,
dueDate: due,
};

const invoice = await prisma.invoice.create({
Expand Down
48 changes: 38 additions & 10 deletions app/invoices/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import { useState } from 'react';
import { jsPDF } from 'jspdf';
import { useQuery, useQueryClient } from '@tanstack/react-query';

const DEFAULT_DUE_DATE = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString().slice(0, 10);

interface Client {
id: string;
name: string;
Expand All @@ -19,6 +21,8 @@ interface Invoice {
periodEnd?: string | null;
client: { name: string };
isPaid: boolean;
dueDate?: string | null;
isOverdue?: boolean;
}

interface InvoiceEntry {
Expand All @@ -41,18 +45,20 @@ const buildInvoicePdf = (invoice: Invoice, entries: InvoiceEntry[]) => {
? new Date(invoice.periodStart).toLocaleDateString()
: 'N/A';
const periodEnd = invoice.periodEnd ? new Date(invoice.periodEnd).toLocaleDateString() : 'N/A';
const dueDate = invoice.dueDate ? new Date(invoice.dueDate).toLocaleDateString() : 'N/A';

doc.setFontSize(18);
doc.text('Worklog Invoice', 14, 20);

doc.setFontSize(12);
doc.text(`Client: ${invoice.client.name}`, 14, 32);
doc.text(`Period: ${periodStart} - ${periodEnd}`, 14, 40);
doc.text(`Created: ${createdAt}`, 14, 48);
doc.text(`Total Hours: ${invoice.totalHours.toFixed(2)}`, 14, 56);
doc.text(`Total Amount: $${invoice.totalAmount.toFixed(2)}`, 14, 64);
doc.text(`Due: ${dueDate}`, 14, 48);
doc.text(`Created: ${createdAt}`, 14, 56);
doc.text(`Total Hours: ${invoice.totalHours.toFixed(2)}`, 14, 64);
doc.text(`Total Amount: $${invoice.totalAmount.toFixed(2)}`, 14, 72);

let y = 76;
let y = 84;
doc.setFontSize(11);
doc.text('Entries', 14, y);
y += 8;
Expand Down Expand Up @@ -82,7 +88,8 @@ export default function InvoicesPage() {
clientId: '',
startDate: '',
endDate: '',
hourlyRate: ''
hourlyRate: '',
dueDate: DEFAULT_DUE_DATE,
});
const queryClient = useQueryClient();

Expand Down Expand Up @@ -126,7 +133,13 @@ export default function InvoicesPage() {
});

if (res.ok) {
setFormData({ clientId: '', startDate: '', endDate: '', hourlyRate: '' });
setFormData({
clientId: '',
startDate: '',
endDate: '',
hourlyRate: '',
dueDate: DEFAULT_DUE_DATE,
});
queryClient.invalidateQueries({ queryKey: ['invoices'] });
} else {
const error = await res.json();
Expand Down Expand Up @@ -236,7 +249,9 @@ export default function InvoicesPage() {

<div className="md:col-span-3">
<div className="mb-4">
<label className="block text-sm font-semibold text-slate-900 mb-2">Hourly Rate ($)</label>
<label className="block text-sm font-semibold text-slate-900 mb-2">
Hourly Rate ($)
</label>
<input
type="number"
value={formData.hourlyRate}
Expand All @@ -246,6 +261,15 @@ export default function InvoicesPage() {
step="0.01"
/>
</div>
<div className="mb-4">
<label className="block text-sm font-semibold text-slate-900 mb-2">Due Date</label>
<input
type="date"
value={formData.dueDate}
onChange={(e) => setFormData({ ...formData, dueDate: e.target.value })}
className="w-full px-4 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-slate-900"
/>
</div>
<button
type="submit"
className="px-6 py-3 bg-slate-900 text-white rounded-lg hover:bg-slate-800 transition-colors"
Expand Down Expand Up @@ -273,7 +297,9 @@ export default function InvoicesPage() {
<th className="px-6 py-4 text-right text-sm font-semibold text-slate-900">
Amount
</th>
<th className="px-6 py-4 text-center text-sm font-semibold text-slate-900">Status</th>
<th className="px-6 py-4 text-center text-sm font-semibold text-slate-900">
Status
</th>
<th className="px-6 py-4 text-right text-sm font-semibold text-slate-900">
Actions
</th>
Expand All @@ -294,7 +320,7 @@ export default function InvoicesPage() {
${invoice.totalAmount.toFixed(2)}
</td>
<td className="px-6 py-4 text-center">
{invoice.isPaid ? 'Paid' : 'Unpaid'}
{invoice.isOverdue ? 'Overdue' : invoice.isPaid ? 'Paid' : 'Unpaid'}
</td>
<td className="px-6 py-4 text-right space-x-2">
<button
Expand All @@ -309,7 +335,9 @@ export default function InvoicesPage() {
if (!res.ok) {
const errorBody = await res.json().catch(() => null);
const message =
errorBody?.error || errorBody?.message || 'Failed to update invoice status';
errorBody?.error ||
errorBody?.message ||
'Failed to update invoice status';
alert(message);
return;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "Invoice" ADD COLUMN "dueDate" TIMESTAMP(3);
2 changes: 2 additions & 0 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -66,4 +66,6 @@ model Invoice {
userId String
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
isPaid Boolean @default(false)
// Optional due date for the invoice; if not provided, default applied in server logic
dueDate DateTime?
}
Loading