prices panel

This commit is contained in:
Jurgis Sakalauskas
2025-10-14 14:27:28 +03:00
parent e30e116187
commit 0d97a497ea
4 changed files with 244 additions and 219 deletions
+6
View File
@@ -73,3 +73,9 @@ export const createItemPrice = async (
return response.data; return response.data;
}; };
export const deleteItemPrice = async (priceId: string): Promise<void> => {
await apiFetch<null>(`/prices/${priceId}`, {
method: 'DELETE'
});
};
@@ -1,67 +0,0 @@
import { useEffect } from 'react';
import type { Item } from '@shared/models/item';
import { ItemPricesPanel } from './item-prices-panel';
interface ItemPricesModalProps {
isOpen: boolean;
item: Item | null;
projectId: string | undefined;
onClose: () => void;
}
export function ItemPricesModal({
isOpen,
item,
projectId,
onClose
}: ItemPricesModalProps) {
useEffect(() => {
if (!isOpen) {
return;
}
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === 'Escape') {
onClose();
}
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [isOpen, onClose]);
if (!isOpen || !item) {
return null;
}
const itemTitle = item.manufacturer ? `${item.manufacturer} ${item.model}` : item.model;
return (
<div
className="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/40 px-4 py-10 md:py-16"
role="dialog"
aria-modal="true"
onClick={onClose}
>
<div
className="relative flex w-full max-w-4xl flex-col overflow-hidden rounded-2xl bg-white shadow-2xl max-h-[calc(100vh-5rem)] md:max-h-[calc(100vh-8rem)]"
onClick={(event) => event.stopPropagation()}
>
<button
type="button"
onClick={onClose}
className="absolute right-4 top-4 rounded-full bg-slate-100 px-3 py-1 text-xs font-semibold uppercase tracking-wide text-slate-500 transition hover:bg-slate-200"
>
Close
</button>
<div className="flex-1 overflow-y-auto px-6 py-6 md:px-8 md:py-8">
<header className="mb-5 flex flex-col gap-1">
<h2 className="text-xl font-semibold text-slate-900">Edit Item Prices</h2>
<p className="text-sm text-slate-500">{itemTitle}</p>
</header>
<ItemPricesPanel itemId={item.id} projectId={projectId} />
</div>
</div>
</div>
);
}
@@ -1,6 +1,12 @@
import { FormEvent, useMemo, useState } from 'react'; import { FormEvent, useMemo, useState } from 'react';
import { useCreateItemPriceMutation, useItemPricesQuery } from '../../query/item-prices'; import { Trash2 } from 'lucide-react';
import {
useCreateItemPriceMutation,
useDeleteItemPriceMutation,
useItemPricesQuery
} from '../../query/item-prices';
import type { PriceCondition } from '../../api/item-prices'; import type { PriceCondition } from '../../api/item-prices';
import { formatRelativeTime } from '../../utils/relative-time';
const priceConditionOptions: PriceCondition[] = ['new', 'used']; const priceConditionOptions: PriceCondition[] = ['new', 'used'];
@@ -12,23 +18,39 @@ interface ItemPricesPanelProps {
export function ItemPricesPanel({ itemId, projectId }: ItemPricesPanelProps) { export function ItemPricesPanel({ itemId, projectId }: ItemPricesPanelProps) {
const [condition, setCondition] = useState<PriceCondition>('new'); const [condition, setCondition] = useState<PriceCondition>('new');
const [amount, setAmount] = useState(''); const [amount, setAmount] = useState('');
const [currency, setCurrency] = useState('USD'); const [currency, setCurrency] = useState('EUR');
const [sourceUrl, setSourceUrl] = useState(''); const [sourceUrl, setSourceUrl] = useState('');
const [note, setNote] = useState(''); const [note, setNote] = useState('');
const [formError, setFormError] = useState<string | null>(null); const [formError, setFormError] = useState<string | null>(null);
const [actionError, setActionError] = useState<string | null>(null);
const [pendingDeletionId, setPendingDeletionId] = useState<string | null>(null);
const pricesQuery = useItemPricesQuery(itemId, true); const pricesQuery = useItemPricesQuery(itemId, true);
const createPriceMutation = useCreateItemPriceMutation(itemId, projectId); const createPriceMutation = useCreateItemPriceMutation(itemId, projectId);
const deletePriceMutation = useDeleteItemPriceMutation(itemId, projectId);
const prices = pricesQuery.data?.data ?? []; const prices = pricesQuery.data?.data ?? [];
const creationError = useMemo( const errorMessage = useMemo(
() => formError ?? (createPriceMutation.isError ? createPriceMutation.error.message : null), () =>
[formError, createPriceMutation.isError, createPriceMutation.error] formError ??
actionError ??
(createPriceMutation.isError ? createPriceMutation.error.message : null) ??
(deletePriceMutation.isError ? deletePriceMutation.error.message : null),
[
formError,
actionError,
createPriceMutation.isError,
createPriceMutation.error,
deletePriceMutation.isError,
deletePriceMutation.error
]
); );
const handleSubmit = async (event: FormEvent<HTMLFormElement>) => { const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault(); event.preventDefault();
setFormError(null); setFormError(null);
setActionError(null);
createPriceMutation.reset();
const parsedAmount = Number(amount); const parsedAmount = Number(amount);
@@ -50,7 +72,21 @@ export function ItemPricesPanel({ itemId, projectId }: ItemPricesPanelProps) {
setSourceUrl(''); setSourceUrl('');
setNote(''); setNote('');
} catch (error) { } catch (error) {
setFormError((error as Error).message); setActionError((error as Error).message);
}
};
const handleDeletePrice = async (priceId: string) => {
setActionError(null);
deletePriceMutation.reset();
setPendingDeletionId(priceId);
try {
await deletePriceMutation.mutateAsync(priceId);
} catch (error) {
setActionError((error as Error).message);
} finally {
setPendingDeletionId(null);
} }
}; };
@@ -78,154 +114,183 @@ export function ItemPricesPanel({ itemId, projectId }: ItemPricesPanelProps) {
</p> </p>
) : null} ) : null}
<div className="mt-4 grid gap-4 md:grid-cols-2"> <form onSubmit={handleSubmit} className="mt-4">
<form <div className="overflow-x-auto rounded-lg border border-slate-200">
className="flex flex-col gap-3 rounded-lg border border-slate-200 bg-slate-50 p-4" <table className="min-w-full divide-y divide-slate-200 text-sm">
onSubmit={handleSubmit} <thead className="bg-slate-50">
> <tr>
<div className="grid grid-cols-2 gap-3"> <th scope="col" className="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wide text-slate-500">
<div className="flex flex-col gap-1.5"> Condition
<label className="text-xs font-medium text-slate-600" htmlFor={`price-condition-${itemId}`}> </th>
Condition <th scope="col" className="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wide text-slate-500">
</label> Amount
<select </th>
id={`price-condition-${itemId}`} <th scope="col" className="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wide text-slate-500">
value={condition} Currency
onChange={(event) => setCondition(event.target.value as PriceCondition)} </th>
className="rounded-md border border-slate-300 px-2 py-2 text-sm shadow-sm focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-200" <th scope="col" className="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wide text-slate-500">
> Source
{priceConditionOptions.map((option) => ( </th>
<option key={option} value={option}> <th scope="col" className="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wide text-slate-500">
{option} Notes
</option> </th>
))} <th scope="col" className="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wide text-slate-500">
</select> Updated
</div> </th>
<div className="flex flex-col gap-1.5"> <th scope="col" className="px-4 py-3 text-right text-xs font-semibold uppercase tracking-wide text-slate-500">
<label className="text-xs font-medium text-slate-600" htmlFor={`price-amount-${itemId}`}> Actions
Amount </th>
</label> </tr>
<input </thead>
id={`price-amount-${itemId}`} <tbody className="divide-y divide-slate-100 bg-white">
type="number" {pricesQuery.isLoading ? (
min={0} <tr>
step="0.01" <td colSpan={7} className="px-4 py-6 text-center text-xs text-slate-500">
value={amount} Loading prices
onChange={(event) => setAmount(event.target.value)} </td>
className="rounded-md border border-slate-300 px-2 py-2 text-sm shadow-sm focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-200" </tr>
placeholder="129.99" ) : prices.length ? (
required prices.map((price) => {
/> const lastUpdated = price.updatedAt ?? price.createdAt;
</div>
</div>
<div className="flex flex-col gap-1.5"> return (
<label className="text-xs font-medium text-slate-600" htmlFor={`price-currency-${itemId}`}> <tr key={price.id}>
Currency <td className="px-4 py-3 capitalize text-slate-800">{price.condition}</td>
</label> <td className="px-4 py-3 text-slate-800">{price.amount.toFixed(2)}</td>
<input <td className="px-4 py-3 text-slate-800">{price.currency}</td>
id={`price-currency-${itemId}`} <td className="px-4 py-3 text-slate-800">
type="text" {price.sourceUrl ? (
value={currency} <a
onChange={(event) => setCurrency(event.target.value.toUpperCase())} href={price.sourceUrl}
maxLength={3} target="_blank"
className="uppercase rounded-md border border-slate-300 px-2 py-2 text-sm shadow-sm focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-200" rel="noreferrer"
placeholder="USD" className="text-blue-600 hover:text-blue-700"
required >
/> View source
</div> </a>
) : (
<div className="flex flex-col gap-1.5"> <span className="text-slate-400"></span>
<label className="text-xs font-medium text-slate-600" htmlFor={`price-source-url-${itemId}`}> )}
Source URL </td>
</label> <td className="px-4 py-3 text-slate-800">
<input {price.note ? price.note : <span className="text-slate-400"></span>}
id={`price-source-url-${itemId}`} </td>
type="url" <td className="px-4 py-3 text-slate-600">
value={sourceUrl} {lastUpdated ? formatRelativeTime(lastUpdated) : <span className="text-slate-400"></span>}
onChange={(event) => setSourceUrl(event.target.value)} </td>
className="rounded-md border border-slate-300 px-2 py-2 text-sm shadow-sm focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-200" <td className="px-4 py-3 text-right">
placeholder="https://shop.example.com/deal" <button
/> type="button"
</div> onClick={() => handleDeletePrice(price.id)}
className="inline-flex items-center gap-1 rounded-md border border-red-200 bg-red-50 px-2 py-1.5 text-xs font-semibold text-red-600 transition hover:bg-red-100 focus:outline-none focus-visible:ring-2 focus-visible:ring-red-500 focus-visible:ring-offset-2 focus-visible:ring-offset-white disabled:cursor-not-allowed disabled:opacity-60"
<div className="flex flex-col gap-1.5"> disabled={deletePriceMutation.isPending && pendingDeletionId === price.id}
<label className="text-xs font-medium text-slate-600" htmlFor={`price-note-${itemId}`}> >
Notes <Trash2 aria-hidden className="h-4 w-4" />
</label> </button>
<textarea </td>
id={`price-note-${itemId}`} </tr>
value={note} );
onChange={(event) => setNote(event.target.value)} })
rows={2} ) : (
className="rounded-md border border-slate-300 px-2 py-2 text-sm shadow-sm focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-200" <tr>
placeholder="Includes extra grip kit" <td colSpan={7} className="px-4 py-6 text-center text-xs text-slate-500">
/> No prices recorded yet.
</div> </td>
</tr>
{creationError ? ( )}
<p className="rounded-md bg-red-50 px-3 py-2 text-xs text-red-600">{creationError}</p> <tr className="bg-slate-50">
) : null} <td className="px-4 py-3">
<label className="sr-only" htmlFor={`price-condition-${itemId}`}>
<div className="flex items-center justify-end gap-3 pt-1"> Condition
<button </label>
type="submit" <select
className="rounded-md bg-blue-600 px-4 py-2 text-sm font-semibold text-white transition hover:bg-blue-700 disabled:cursor-not-allowed disabled:bg-blue-400" id={`price-condition-${itemId}`}
disabled={createPriceMutation.isPending} value={condition}
> onChange={(event) => setCondition(event.target.value as PriceCondition)}
{createPriceMutation.isPending ? 'Adding…' : 'Add Price'} className="w-full rounded-md border border-slate-300 px-2 py-2 text-sm shadow-sm focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-200"
</button> >
</div> {priceConditionOptions.map((option) => (
</form> <option key={option} value={option}>
{option}
<div className="space-y-3"> </option>
{prices.map((price) => ( ))}
<article </select>
key={price.id} </td>
className="rounded-lg border border-slate-200 bg-white px-4 py-3 text-sm shadow-sm" <td className="px-4 py-3">
> <label className="sr-only" htmlFor={`price-amount-${itemId}`}>
<header className="flex items-center justify-between"> Amount
<span className="font-semibold text-slate-900"> </label>
{price.condition} {price.amount.toFixed(2)} {price.currency} <input
</span> id={`price-amount-${itemId}`}
</header> type="number"
<dl className="mt-2 space-y-1 text-xs text-slate-600"> min={0}
{price.sourceUrl ? ( step="0.01"
<div> value={amount}
<dt className="font-medium text-slate-500">Source URL</dt> onChange={(event) => setAmount(event.target.value)}
<dd> className="w-full rounded-md border border-slate-300 px-2 py-2 text-sm shadow-sm focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-200"
<a placeholder="129.99"
href={price.sourceUrl} required
target="_blank" />
rel="noreferrer" </td>
className="text-blue-600 hover:text-blue-700" <td className="px-4 py-3">
> <label className="sr-only" htmlFor={`price-currency-${itemId}`}>
View source Currency
</a> </label>
</dd> <input
</div> id={`price-currency-${itemId}`}
) : null} type="text"
{price.note ? ( value={currency}
<div> onChange={(event) => setCurrency(event.target.value.toUpperCase())}
<dt className="font-medium text-slate-500">Notes</dt> maxLength={3}
<dd>{price.note}</dd> className="w-full rounded-md border border-slate-300 px-2 py-2 text-sm uppercase shadow-sm focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-200"
</div> placeholder="EUR"
) : null} required
<div> />
<dt className="font-medium text-slate-500">Created</dt> </td>
<dd>{new Date(price.createdAt).toLocaleString()}</dd> <td className="px-4 py-3">
</div> <label className="sr-only" htmlFor={`price-source-url-${itemId}`}>
{price.updatedAt !== price.createdAt ? ( Source URL
<div> </label>
<dt className="font-medium text-slate-500">Updated</dt> <input
<dd>{new Date(price.updatedAt).toLocaleString()}</dd> id={`price-source-url-${itemId}`}
</div> type="url"
) : null} value={sourceUrl}
</dl> onChange={(event) => setSourceUrl(event.target.value)}
</article> className="w-full rounded-md border border-slate-300 px-2 py-2 text-sm shadow-sm focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-200"
))} placeholder="https://shop.example.com/deal"
/>
</td>
<td className="px-4 py-3">
<label className="sr-only" htmlFor={`price-note-${itemId}`}>
Notes
</label>
<textarea
id={`price-note-${itemId}`}
value={note}
onChange={(event) => setNote(event.target.value)}
rows={1}
className="w-full rounded-md border border-slate-300 px-2 py-2 text-sm shadow-sm focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-200"
placeholder="Includes extra grip kit"
/>
</td>
<td className="px-4 py-3 text-slate-400"></td>
<td className="px-4 py-3 text-right">
<button
type="submit"
className="rounded-md bg-blue-600 px-3 py-2 text-sm font-semibold text-white transition hover:bg-blue-700 disabled:cursor-not-allowed disabled:bg-blue-400"
disabled={createPriceMutation.isPending}
>
{createPriceMutation.isPending ? 'Adding…' : 'Add Price'}
</button>
</td>
</tr>
</tbody>
</table>
</div> </div>
</div> {errorMessage ? (
<p className="mt-3 rounded-md bg-red-50 px-3 py-2 text-xs text-red-600">{errorMessage}</p>
) : null}
</form>
</div> </div>
); );
} }
+21
View File
@@ -1,6 +1,7 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { import {
createItemPrice, createItemPrice,
deleteItemPrice,
fetchItemPrices, fetchItemPrices,
type CreateItemPricePayload, type CreateItemPricePayload,
type ItemPricesResponse type ItemPricesResponse
@@ -50,3 +51,23 @@ export const useCreateItemPriceMutation = (
} }
}); });
}; };
export const useDeleteItemPriceMutation = (
itemId: string | undefined,
projectId: string | undefined
) => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (priceId: string) => deleteItemPrice(priceId),
onSuccess: () => {
if (itemId) {
queryClient.invalidateQueries({ queryKey: itemPricesKeys.list(itemId) });
}
if (projectId) {
queryClient.invalidateQueries({ queryKey: projectsKeys.items(projectId) });
queryClient.invalidateQueries({ queryKey: projectsKeys.detail(projectId) });
}
}
});
};