Extract APIs to their own files #108

Merged
bustikiller merged 8 commits from extract-apis into main 2024-11-17 17:02:08 +00:00
11 changed files with 215 additions and 184 deletions

40
app/api/expenses.tsx Normal file
View File

@ -0,0 +1,40 @@
/* Copyright (C) 2024 Manuel Bustillo*/
import { Expense } from '@/app/lib/definitions';
import { getCsrfToken } from '@/app/lib/utils';
export function loadExpenses(onLoad?: (expenses: Expense[]) => void) {
fetch("/api/expenses")
.then((response) => response.json())
.then((data) => {
onLoad && onLoad(data.map((record: any) => {
return ({
id: record.id,
name: record.name,
amount: record.amount,
pricingType: record.pricing_type
});
}));
}, (error) => {
return [];
});
}
export function updateExpense(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));
}

27
app/api/groups.tsx Normal file
View File

@ -0,0 +1,27 @@
/* Copyright (C) 2024 Manuel Bustillo*/
import { Group } from '@/app/lib/definitions';
export function loadGroups(onLoad?: (groups: Group[]) => void) {
fetch("/api/groups")
.then((response) => response.json())
.then((data) => {
onLoad && onLoad(data.map((record: any) => {
return ({
id: record.id,
name: record.name,
color: record.color,
attendance: {
considered: record.considered,
invited: record.invited,
confirmed: record.confirmed,
tentative: record.tentative,
declined: record.declined,
total: record.total,
}
});
}));
}, (error) => {
return [];
});
}

50
app/api/guests.tsx Normal file
View File

@ -0,0 +1,50 @@
/* Copyright (C) 2024 Manuel Bustillo*/
import { Guest } from '@/app/lib/definitions';
import { getCsrfToken } from '@/app/lib/utils';
export function loadGuests(onLoad?: (guests: Guest[]) => void) {
fetch("/api/guests")
.then((response) => response.json())
.then((data) => {
onLoad && onLoad(data.map((record: any) => {
return ({
id: record.id,
name: record.name,
status: record.status,
group_name: record.group.name,
});
}));
}, (error) => {
return [];
});
};
export function updateGuest(guest: Guest) {
return fetch(`/api/guests/${guest.id}`,
{
method: 'PUT',
body: JSON.stringify({ guest: { name: guest.name, status: guest.status } }),
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': getCsrfToken(),
}
})
.catch((error) => console.error(error));
}
export function createGuest(name: string, group_id: string, onCreate?: () => void) {
fetch("/api/guests", {
method: 'POST',
body: JSON.stringify({ name: name, group_id: group_id }),
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': getCsrfToken(),
}
})
.then((response) => response.json())
.then((data) => {
onCreate && onCreate();
})
.catch((error) => console.error(error));
}

View File

@ -0,0 +1,19 @@
/* Copyright (C) 2024 Manuel Bustillo*/
import { TableArrangement } from '@/app/lib/definitions';
export function loadTableSimulations(onLoad?: (tableSimulations: TableArrangement[]) => void) {
fetch('/api/tables_arrangements')
.then((response) => response.json())
.then((data) => {
onLoad && onLoad(data.map((record: any) => {
return ({
id: record.id,
name: record.name,
discomfort: record.discomfort,
});
}));
}, (error) => {
return [];
});
}

View File

@ -3,7 +3,6 @@
'use client';
import { Group, Guest } from '@/app/lib/definitions';
import { getCsrfToken } from '@/app/lib/utils';
import CreationDialog from '@/app/ui/components/creation-dialog';
import GroupsTable from '@/app/ui/groups/table';
import AffinityGroupsTree from '@/app/ui/guests/affinity-groups-tree';
@ -11,63 +10,22 @@ import SkeletonTable from '@/app/ui/guests/skeleton-row';
import GuestsTable from '@/app/ui/guests/table';
import { TabPanel, TabView } from 'primereact/tabview';
import { Suspense, useState } from 'react';
import { loadGuests } from '@/app/api/guests';
import { loadGroups } from '@/app/api/groups';
export default function Page() {
function loadGroups() {
fetch("/api/groups")
.then((response) => response.json())
.then((data) => {
setGroups(data.map((record: any) => {
return ({
id: record.id,
name: record.name,
color: record.color,
attendance: {
considered: record.considered,
invited: record.invited,
confirmed: record.confirmed,
tentative: record.tentative,
declined: record.declined,
total: record.total,
}
});
}));
setGroupsLoaded(true);
}, (error) => {
return [];
});
function refreshGuests() {
loadGuests((guests) => {
setGuests(guests);
setGuestsLoaded(true);
});
}
function loadGuests() {
fetch("/api/guests.json")
.then((response) => response.json())
.then((data) => {
setGuests(data.map((record: any) => {
return ({
id: record.id,
name: record.name,
status: record.status,
group_name: record.group.name,
});
}));
setGuestsLoaded(true);
}, (error) => {
return [];
});
};
const updateGuestStatus = (id: string, status: string) => {
fetch("/api/guests/bulk_update.json",
{
method: 'POST',
body: JSON.stringify({ properties: { status: status }, guest_ids: [id] }),
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': getCsrfToken(),
}
})
.then(() => loadGuests())
.catch((error) => console.error(error));
function refreshGroups() {
loadGroups((groups) => {
setGroups(groups);
setGroupsLoaded(true);
});
}
const [groupsLoaded, setGroupsLoaded] = useState(false);
@ -76,8 +34,8 @@ export default function Page() {
const [guestsLoaded, setGuestsLoaded] = useState(false);
const [guests, setGuests] = useState<Array<Guest>>([]);
!groupsLoaded && loadGroups();
!guestsLoaded && loadGuests();
!groupsLoaded && refreshGroups();
!guestsLoaded && refreshGuests();
return (
<div className="w-full">
@ -86,9 +44,9 @@ export default function Page() {
<TabView>
<TabPanel header="Guests" leftIcon="pi pi-users mx-2">
<div className="flex flex-col w-full items-center justify-between">
<CreationDialog groups={groups} onCreate={loadGuests} />;
<CreationDialog groups={groups} onCreate={refreshGuests} />
<Suspense fallback={<SkeletonTable />}>
<GuestsTable guests={guests} updateGuestStatus={updateGuestStatus} />
<GuestsTable guests={guests} onUpdate={refreshGuests} />
</Suspense>
</div>
</ TabPanel>

View File

@ -18,12 +18,13 @@ export type Customer = {
image_url: string;
};
export type GuestStatus = 'considered' | 'invited' | 'confirmed' | 'declined' | 'tentative';
export type Guest = {
id: string;
name: string;
group_name?: string;
color?: string;
status?: 'considered' | 'invited' | 'confirmed' | 'declined' | 'tentative';
status?: GuestStatus
}
export type Expense = {

View File

@ -6,31 +6,24 @@ import React, { useState } from "react"
import { TableArrangement } from '@/app/lib/definitions';
import { classNames } from "../components/button";
import TableOfContents from "../components/table-of-contents";
import { loadTableSimulations } from "@/app/api/tableSimulations";
export default function ArrangementsTable ({onArrangementSelected}: {onArrangementSelected: (arrangementId: string) => void}) {
const [arrangements, setArrangements] = useState<Array<TableArrangement>>([]);
const [arrangementsLoaded, setArrangementsLoaded] = useState(false);
function loadArrangements() {
fetch("/api/tables_arrangements")
.then((response) => response.json())
.then((data) => {
setArrangements(data.map((record: any) => {
return ({
id: record.id,
name: record.name,
discomfort: record.discomfort
});
}));
}, (error) => {
return [];
});
function refreshSimulations() {
loadTableSimulations((arrangements) => {
setArrangements(arrangements);
setArrangementsLoaded(true);
});
}
function arrangementClicked(e: React.MouseEvent<HTMLElement>) {
onArrangementSelected(e.currentTarget.getAttribute('data-arrangement-id') || '');
}
arrangements.length === 0 && loadArrangements();
!arrangementsLoaded && refreshSimulations();
return(
<TableOfContents

View File

@ -2,8 +2,8 @@
'use client';
import { createGuest } from '@/app/api/guests';
import { Group } from '@/app/lib/definitions';
import { getCsrfToken } from '@/app/lib/utils';
import { classNames } from '@/app/ui/components/button';
import { Dialog } from 'primereact/dialog';
import { Dropdown } from 'primereact/dropdown';
@ -16,22 +16,13 @@ export default function CreationDialog({ groups, onCreate }: { groups: Group[],
const [name, setName] = useState('');
const [group, setGroup] = useState(null);
function createGuest() {
fetch("/api/guests", {
method: 'POST',
body: JSON.stringify({ name: name, group_id: group }),
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': getCsrfToken(),
}
})
.then((response) => response.json())
.then((data) => {
console.log(data);
setVisible(false);
onCreate && onCreate();
})
.catch((error) => console.error(error));
function submitGuest() {
name && group && createGuest(name, group, () => {
setVisible(false);
setName('');
setGroup(null);
onCreate && onCreate();
});
}
return (
@ -52,7 +43,7 @@ export default function CreationDialog({ groups, onCreate }: { groups: Group[],
} />
<label htmlFor="group">Group</label>
</FloatLabel>
<button className={classNames('primary')} onClick={createGuest} disabled={!(name.length > 0 && group)}>Create</button>
<button className={classNames('primary')} onClick={submitGuest} disabled={!(name.length > 0 && group)}>Create</button>
</div>
</Dialog>
</>

View File

@ -2,71 +2,43 @@
'use client'
import React, { useState } from "react"
import { loadExpenses, updateExpense } from '@/app/api/expenses';
import { Expense } from '@/app/lib/definitions';
import TableOfContents from "../components/table-of-contents";
import { useState } from "react";
import InlineTextField from "../components/form/inlineTextField";
import { getCsrfToken } from '@/app/lib/utils';
import TableOfContents from "../components/table-of-contents";
export default function ExpensesTable() {
const [expenses, setExpenses] = useState<Array<Expense>>([]);
const [expenses, setExpenses] = useState<Array<Expense>>([]);
const [expensesLoaded, setExpensesLoaded] = useState(false);
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));
}
function refreshExpenses() {
loadExpenses((expenses) => {
setExpenses(expenses);
setExpensesLoaded(true);
});
}
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 [];
});
}
!expensesLoaded && refreshExpenses();
expenses.length === 0 && loadExpenses();
return (
<TableOfContents
headers={['Name', 'Amount (€)', 'Pricing Type']}
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">
<InlineTextField initialValue={expense.name} onChange={(value) => { expense.name = value; handleExpenseUpdate(expense) }} />
</th>
<td className="px-6 py-4">
<InlineTextField initialValue={expense.amount.toString()} onChange={(value) => { expense.amount = parseFloat(value); handleExpenseUpdate(expense) }} />
</td>
<td>
{expense.pricingType}
</td>
</tr>
)}
/>
);
return (
<TableOfContents
headers={['Name', 'Amount (€)', 'Pricing Type']}
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">
<InlineTextField initialValue={expense.name} onChange={(value) => { expense.name = value; updateExpense(expense) }} />
</th>
<td className="px-6 py-4">
<InlineTextField initialValue={expense.amount.toString()} onChange={(value) => { expense.amount = parseFloat(value); updateExpense(expense) }} />
</td>
<td>
{expense.pricingType}
</td>
</tr>
)}
/>
);
}

View File

@ -2,39 +2,19 @@
'use client';
import { Guest } from '@/app/lib/definitions';
import { getCsrfToken } from '@/app/lib/utils';
import { updateGuest } from '@/app/api/guests';
import { Guest, GuestStatus } from '@/app/lib/definitions';
import { classNames } from '@/app/ui/components/button';
import clsx from 'clsx';
import React from 'react';
import InlineTextField from '../components/form/inlineTextField';
import TableOfContents from '../components/table-of-contents';
export default function guestsTable({ guests, updateGuestStatus }: { guests: Guest[], updateGuestStatus: (id: string, status: string) => void }) {
const handleInviteGuest = (e: React.MouseEvent<HTMLElement>) => handleGuestChange(e, 'invited');
const handleConfirmGuest = (e: React.MouseEvent<HTMLElement>) => handleGuestChange(e, 'confirmed');
const handleDeclineGuest = (e: React.MouseEvent<HTMLElement>) => handleGuestChange(e, 'declined');
const handleTentativeGuest = (e: React.MouseEvent<HTMLElement>) => handleGuestChange(e, 'tentative');
const handleGuestUpdate = (guest: Guest) => {
fetch(`/api/guests/${guest.id}`,
{
method: 'PUT',
body: JSON.stringify({ guest: { name: guest.name } }),
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': getCsrfToken(),
}
})
.catch((error) => console.error(error));
export default function guestsTable({ guests, onUpdate }: { guests: Guest[], onUpdate: () => void }) {
const handleGuestChange = (guest: Guest, status: GuestStatus) => {
guest.status = status;
updateGuest(guest).then(() => onUpdate());
}
const handleGuestChange = (e: React.MouseEvent<HTMLElement>, status: string) => {
updateGuestStatus(e.currentTarget.getAttribute('data-guest-id') || '', status);
}
return (
<TableOfContents
headers={['Name', 'Group', 'Status', 'Actions']}
@ -43,7 +23,7 @@ export default function guestsTable({ guests, updateGuestStatus }: { guests: Gue
rowRender={(guest) => (
<tr key={guest.id} className="bg-white border-b odd:bg-white odd:dark:bg-gray-900 even:bg-gray-50 even:dark:bg-gray-800">
<td scope="row" className="px-6 py-4 font-medium text-gray-900 whitespace-nowrap dark:text-white">
<InlineTextField initialValue={guest.name} onChange={(newName) => { guest.name = newName; handleGuestUpdate(guest) }} />
<InlineTextField initialValue={guest.name} onChange={(newName) => { guest.name = newName; updateGuest(guest) }} />
</td>
<td className="px-6 py-4">
{guest.group_name}
@ -65,14 +45,14 @@ export default function guestsTable({ guests, updateGuestStatus }: { guests: Gue
</span>
</td>
<td>
{guest.status === 'considered' && (<button data-guest-id={guest.id} onClick={handleInviteGuest} className={classNames('blue')}>
{guest.status === 'considered' && (<button data-guest-id={guest.id} onClick={() => handleGuestChange(guest, 'invited')} className={classNames('blue')}>
Invite
</button>)}
{(guest.status === 'invited' || guest.status === 'tentative') && (
<>
<button data-guest-id={guest.id} onClick={handleConfirmGuest} className={classNames('green')}>Confirm</button>
{guest.status != 'tentative' && <button data-guest-id={guest.id} onClick={handleTentativeGuest} className={classNames('yellow')}>Tentative</button>}
<button data-guest-id={guest.id} onClick={handleDeclineGuest} className={classNames('red')}>Decline</button>
<button data-guest-id={guest.id} onClick={() => handleGuestChange(guest, 'confirmed')} className={classNames('green')}>Confirm</button>
{guest.status != 'tentative' && <button data-guest-id={guest.id} onClick={() => handleGuestChange(guest, 'tentative')} className={classNames('yellow')}>Tentative</button>}
<button data-guest-id={guest.id} onClick={() => handleGuestChange(guest, 'declined')} className={classNames('red')}>Decline</button>
</>
)}
</td>

View File

@ -1,7 +1,7 @@
import { test, expect, Page } from '@playwright/test'
const mockGuestsAPI = ({ page }: { page: Page }) => {
page.route('*/**/api/guests.json', async route => {
page.route('*/**/api/guests', async route => {
const json = [
{
"id": "f4a09c28-40ea-4553-90a5-96935a59cac6",