72 lines
2.6 KiB
TypeScript
Raw Normal View History

2024-11-10 21:08:03 +01:00
/* Copyright (C) 2024 Manuel Bustillo*/
'use client'
import React, { useState } from "react"
import { Expense } from '@/app/lib/definitions';
import TableOfContents from "../components/table-of-contents";
2024-11-11 08:10:33 +01:00
import InlineTextField from "../components/form/inlineTextField";
import { getCsrfToken } from '@/app/lib/utils';
2024-11-10 21:08:03 +01:00
export default function ExpensesTable() {
const [expenses, setExpenses] = useState<Array<Expense>>([]);
2024-11-11 08:10:33 +01:00
const handleExpenseUpdate = (expense: Expense) => {
fetch(`/api/expenses/${expense.id}`,
{
method: 'PUT',
body: JSON.stringify({
expense: {
name: expense.name,
amount: expense.amount,
pricing_type: expense.pricingType,
}
}),
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': getCsrfToken(),
}
})
.catch((error) => console.error(error));
}
2024-11-10 21:08:03 +01:00
function loadExpenses() {
fetch("/api/expenses")
.then((response) => response.json())
.then((data) => {
setExpenses(data.map((record: any) => {
return ({
id: record.id,
name: record.name,
amount: record.amount,
pricingType: record.pricing_type
});
}));
}, (error) => {
return [];
});
}
expenses.length === 0 && loadExpenses();
return (
<TableOfContents
2024-11-11 08:10:33 +01:00
headers={['Name', 'Amount (€)', 'Pricing Type']}
2024-11-10 21:08:03 +01:00
caption='Expenses'
elements={expenses}
rowRender={(expense) => (
<tr key={expense.id} className="bg-white border-b odd:bg-white odd:dark:bg-gray-900 even:bg-gray-50 even:dark:bg-gray-800">
<th scope="row" className="px-6 py-4 font-medium text-gray-900 whitespace-nowrap dark:text-white">
2024-11-11 08:10:33 +01:00
<InlineTextField initialValue={expense.name} onChange={(value) => { expense.name = value; handleExpenseUpdate(expense) }} />
2024-11-10 21:08:03 +01:00
</th>
<td className="px-6 py-4">
2024-11-11 08:10:33 +01:00
<InlineTextField initialValue={expense.amount.toString()} onChange={(value) => { expense.amount = parseFloat(value); handleExpenseUpdate(expense) }} />
2024-11-10 21:08:03 +01:00
</td>
<td>
{expense.pricingType}
</td>
</tr>
)}
/>
);
}