Files
mwitnessing/components/availability/AvailabilityList.js
2024-02-22 04:19:38 +02:00

139 lines
5.8 KiB
JavaScript

import axiosInstance from '../../src/axiosSecure';
import { useEffect, useState } from "react";
import toast from "react-hot-toast";
import { useRouter } from "next/router";
import Link from "next/link";
import { DayOfWeek } from "../DayOfWeek";
const common = require('src/helpers/common');
import AvailabilityForm from "../availability/AvailabilityForm";
import { TrashIcon, PencilSquareIcon } from "@heroicons/react/24/outline";
export default function AvailabilityList({ publisher, showNew }) {
const [showAv, setShowAv] = useState(showNew || false);
const [selectedItem, setSelectedItem] = useState(null);
const [items, setItems] = useState(publisher.availabilities); // Convert items prop to state
useEffect(() => {
console.log('items set to:', items?.map(item => item.id));
}, [items])
const toggleAv = () => setShowAv(!showAv);
const editAvailability = (item) => {
setSelectedItem(item);
setShowAv(true)
};
const deleteAvailability = async (id) => {
try {
await axiosInstance.delete("/api/data/availabilities/" + id);
// Handle the successful deletion, maybe refresh the list or show a success message
const updatedItems = items.filter(item => item.id !== id);
setItems(updatedItems);
} catch (error) {
// Handle the error, maybe show an error message
console.error("Error deleting availability:", error);
}
};
const renderTable = () => (
<table className="min-w-full">
<thead className="border-b">
<tr>
<th scope="col" className="text-sm font-medium text-gray-900 px-6 py-4 text-left">
Ден от седмицата (дата)
</th>
<th scope="col" className="text-sm font-medium text-gray-900 px-6 py-4 text-left">
От-до
</th>
<th scope="col" className="text-sm font-medium text-gray-900 px-6 py-4 text-left">
Действия
</th>
</tr>
</thead>
<tbody>
{items?.sort((a, b) => new Date(a.startTime) - new Date(b.startTime)).map(item => (
<tr key={item.id} availability={item} disabled={!item.isactive} >
<td className="px-6 py-4 whitespace-nowrap">
{item.dayOfMonth ? `${common.getDateFormated(new Date(item.startTime))}` : `Всеки(Всяка) ${common.getDayOfWeekName(new Date(item.startTime))}`}
{/* {common.getDateFormated(new Date(item.startTime))} */}
</td>
<td className="px-6 py-4 whitespace-nowrap">
{common.getTimeRange(new Date(item.startTime), new Date(item.endTime))}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm">
<button className="bg-blue-200 hover:bg-blue-300 text-blue-600 py-1 px-2 rounded inline-flex items-center" onClick={() => editAvailability(item)}>
<PencilSquareIcon className="h-6 w-6" />
</button>
<button className="bg-red-200 hover:bg-red-300 text-red-600 py-1 px-2 rounded ml-2 inline-flex items-center" onClick={() => deleteAvailability(item.id)}>
<TrashIcon className="h-6 w-6" />
</button>
</td>
</tr>
))}
</tbody>
</table>
);
return (
<>
{items?.length === 0 ? (
<h1>No Availabilities</h1>
) : renderTable()}
{<div className="flex justify-center mt-2">
<button className="btn bg-blue-500 hover:bg-blue-600 text-white font-semibold py-2 px-4 rounded transition duration-300"
onClick={() => { setSelectedItem(null); setShowAv(true) }}>Ново разположение</button>
</div>
}
<div className="h-4 p-10">
{showAv && (
<AvailabilityForm
publisherId={publisher.id}
inline={true}
existingItem={selectedItem}
onDone={(item) => {
toggleAv();
setSelectedItem(null);
if (!item) {
// remove selected item from state
const updatedItems = items.filter(i => i.id !== selectedItem.id);
setItems([...updatedItems]);
return;
};
const itemIndex = items.findIndex(i => i.id === item.id); // assuming each item has a unique 'id' property
if (itemIndex !== -1) {
// Replace the existing item with the updated item
const updatedItems = [...items];
updatedItems[itemIndex] = item;
setItems(updatedItems);
} else {
// Append the new item to the end of the list
setItems([...items, item]);
}
}}
/>
)}
</div>
</>
);
}
export const getServerSideProps = async () => {
const { data: items } = await axiosInstance.get(
common.getBaseUrl("/api/data/availabilities")
);
return {
props: {
items,
},
};
};