mahmoud commited on
Commit
b21d90b
ยท
1 Parent(s): 903310d

hanlde edit useDebounce delay time

Browse files
frontend/.vite/deps/_metadata.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "hash": "1e25009f",
3
+ "configHash": "99d79daa",
4
+ "lockfileHash": "146fc05e",
5
+ "browserHash": "8652e288",
6
+ "optimized": {},
7
+ "chunks": {}
8
+ }
frontend/.vite/deps/package.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ {
2
+ "type": "module"
3
+ }
frontend/src/components/Customers/CustomersWorkspace.jsx CHANGED
@@ -1,4 +1,5 @@
1
  import { useState } from "react";
 
2
  import axios from "axios";
3
  import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
4
  import { Link } from "react-router-dom";
@@ -22,17 +23,18 @@ const CustomersWorkspace = () => {
22
  const currency = user?.tenant?.settings?.currency || "EGP";
23
  const queryClient = useQueryClient();
24
  const [searchTerm, setSearchTerm] = useState("");
 
25
  const [page, setPage] = useState(1);
26
  const [activeCustomerId, setActiveCustomerId] = useState(null);
27
  const [pendingDeleteId, setPendingDeleteId] = useState(null);
28
 
29
  const { data: response, isLoading } = useQuery({
30
- queryKey: ["customers", page, searchTerm],
31
  queryFn: () => axios.get(`${apiUrl}/customers`, {
32
  params: {
33
  page,
34
  limit: 5,
35
- search: searchTerm
36
  }
37
  }),
38
  refetchOnWindowFocus: false,
@@ -81,7 +83,7 @@ const CustomersWorkspace = () => {
81
 
82
  const handleSearchChange = (e) => {
83
  setSearchTerm(e.target.value);
84
- setPage(1); // Reset to page 1 when searching
85
  };
86
 
87
  if (isLoading) {
 
1
  import { useState } from "react";
2
+ import useDebounce from "../../hooks/useDebounce";
3
  import axios from "axios";
4
  import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
5
  import { Link } from "react-router-dom";
 
23
  const currency = user?.tenant?.settings?.currency || "EGP";
24
  const queryClient = useQueryClient();
25
  const [searchTerm, setSearchTerm] = useState("");
26
+ const debouncedSearch = useDebounce(searchTerm, 2000);
27
  const [page, setPage] = useState(1);
28
  const [activeCustomerId, setActiveCustomerId] = useState(null);
29
  const [pendingDeleteId, setPendingDeleteId] = useState(null);
30
 
31
  const { data: response, isLoading } = useQuery({
32
+ queryKey: ["customers", page, debouncedSearch],
33
  queryFn: () => axios.get(`${apiUrl}/customers`, {
34
  params: {
35
  page,
36
  limit: 5,
37
+ search: debouncedSearch
38
  }
39
  }),
40
  refetchOnWindowFocus: false,
 
83
 
84
  const handleSearchChange = (e) => {
85
  setSearchTerm(e.target.value);
86
+ setPage(1);
87
  };
88
 
89
  if (isLoading) {
frontend/src/components/Dashboard/DashboardTab.jsx CHANGED
@@ -69,7 +69,7 @@ const DashboardTab = () => {
69
  if (isLoading) {
70
  return <LodderSpinner />;
71
  }
72
-
73
  return (
74
  <div className="space-y-6">
75
  <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
 
69
  if (isLoading) {
70
  return <LodderSpinner />;
71
  }
72
+ console.log(overview?.lowStockItems?.data)
73
  return (
74
  <div className="space-y-6">
75
  <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
frontend/src/components/Inventory/InventoryWorkspace.jsx CHANGED
@@ -1,4 +1,5 @@
1
  import { useState } from "react";
 
2
  import axios from "axios";
3
  import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
4
  import { AlertTriangle, Boxes, Loader2, PackagePlus, Search, Share2, SquarePen, Trash2 } from "lucide-react";
@@ -22,18 +23,19 @@ const InventoryWorkspace = () => {
22
  const companyName = user?.tenant?.name || "ุงู„ุดุฑูƒุฉ";
23
  const queryClient = useQueryClient();
24
  const [searchTerm, setSearchTerm] = useState("");
 
25
  const [page, setPage] = useState(1);
26
  const [filterMode, setFilterMode] = useState("all");
27
  const [isModalOpen, setIsModalOpen] = useState(false);
28
  const [editingProduct, setEditingProduct] = useState(null);
29
 
30
  const { data: response, isLoading } = useQuery({
31
- queryKey: ["products", page, searchTerm, filterMode],
32
  queryFn: () => axios.get(`${apiUrl}/products`, {
33
  params: {
34
  page,
35
  limit: 5,
36
- search: searchTerm,
37
  filter: filterMode
38
  }
39
  }),
@@ -45,7 +47,7 @@ const InventoryWorkspace = () => {
45
  id ? axios.put(`${apiUrl}/products/${id}`, values) : axios.post(`${apiUrl}/products`, values),
46
  onSuccess: () => {
47
  queryClient.invalidateQueries({ queryKey: ["products"] });
48
- queryClient.invalidateQueries({ queryKey: ["reports", "overview"] });
49
  toast.success(editingProduct ? "ุชู… ุชุญุฏูŠุซ ุงู„ู…ู†ุชุฌ" : "ุชู… ุฅู†ุดุงุก ุงู„ู…ู†ุชุฌ");
50
  setIsModalOpen(false);
51
  setEditingProduct(null);
 
1
  import { useState } from "react";
2
+ import useDebounce from "../../hooks/useDebounce";
3
  import axios from "axios";
4
  import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
5
  import { AlertTriangle, Boxes, Loader2, PackagePlus, Search, Share2, SquarePen, Trash2 } from "lucide-react";
 
23
  const companyName = user?.tenant?.name || "ุงู„ุดุฑูƒุฉ";
24
  const queryClient = useQueryClient();
25
  const [searchTerm, setSearchTerm] = useState("");
26
+ const debouncedSearch = useDebounce(searchTerm, 2000);
27
  const [page, setPage] = useState(1);
28
  const [filterMode, setFilterMode] = useState("all");
29
  const [isModalOpen, setIsModalOpen] = useState(false);
30
  const [editingProduct, setEditingProduct] = useState(null);
31
 
32
  const { data: response, isLoading } = useQuery({
33
+ queryKey: ["products", page, debouncedSearch, filterMode],
34
  queryFn: () => axios.get(`${apiUrl}/products`, {
35
  params: {
36
  page,
37
  limit: 5,
38
+ search: debouncedSearch,
39
  filter: filterMode
40
  }
41
  }),
 
47
  id ? axios.put(`${apiUrl}/products/${id}`, values) : axios.post(`${apiUrl}/products`, values),
48
  onSuccess: () => {
49
  queryClient.invalidateQueries({ queryKey: ["products"] });
50
+ queryClient.invalidateQueries({ queryKey: ["reports"], exact: false });
51
  toast.success(editingProduct ? "ุชู… ุชุญุฏูŠุซ ุงู„ู…ู†ุชุฌ" : "ุชู… ุฅู†ุดุงุก ุงู„ู…ู†ุชุฌ");
52
  setIsModalOpen(false);
53
  setEditingProduct(null);
frontend/src/components/Reports/DailyReport.jsx CHANGED
@@ -1,28 +1,41 @@
1
  import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
2
  import axios from "axios";
3
  import LodderSpinner from "../../common/LoaderSpinner";
4
- import { Banknote, TrendingUp, ReceiptText, Clock, ArrowDownRight, PlusCircle, Trash2, Wallet } from "lucide-react";
5
  import { useState } from "react";
6
  import { toast } from "react-toastify";
7
  import { useFormik } from "formik";
8
  import * as Yup from "yup";
9
 
10
  const apiUrl = import.meta.env.VITE_API_URL;
 
11
 
12
  const DailyReport = () => {
13
  const [openExpenseModal, setOpenExpenseModal] = useState(false);
 
 
14
 
15
  const { data, isLoading, refetch } = useQuery({
16
- queryKey: ["dailyReport"],
17
- queryFn: () => axios.get(`${apiUrl}/reports/daily`),
 
 
18
  refetchInterval: 30000,
19
  });
20
  if (isLoading) return <LodderSpinner />;
21
 
22
  const report = data?.data;
23
- const recentPayments = Array.isArray(report?.recentPayments) ? report.recentPayments : [];
24
- const expensesList = Array.isArray(report?.expensesList) ? report.expensesList : [];
 
 
 
25
 
 
 
 
 
 
26
  return (
27
  <div className="space-y-6">
28
  {/* Header Row */}
@@ -112,28 +125,37 @@ const DailyReport = () => {
112
  <p className="text-slate-500 font-bold">ู„ุง ุชูˆุฌุฏ ุฅูŠุฑุงุฏุงุช ูƒุงุด ู…ุณุฌู„ุฉ ุงู„ูŠูˆู…</p>
113
  </div>
114
  ) : (
115
- <div className="overflow-x-auto overflow-y-auto max-h-[350px] custom-scroll rounded-2xl border border-slate-100 relative">
116
- <table className="w-full text-right border-collapse">
117
- <thead className="sticky top-0 z-10 bg-slate-50 shadow-sm border-b border-slate-200">
118
- <tr>
119
- <th className="py-3 px-4 font-bold text-slate-500 text-sm">ุงู„ุนู…ูŠู„</th>
120
- <th className="py-3 px-4 font-bold text-slate-500 text-sm">ุงู„ู…ุจู„ุบ</th>
121
- <th className="py-3 px-4 font-bold text-slate-500 text-sm">ุงู„ุชูˆู‚ูŠุช</th>
122
- </tr>
123
- </thead>
124
- <tbody className="divide-y divide-slate-100 bg-white">
125
- {recentPayments?.map((payment, idx) => (
126
- <tr key={idx} className="hover:bg-slate-50">
127
- <td className="py-3 px-4 font-bold text-slate-700">{payment.customerName}</td>
128
- <td className="py-3 px-4 font-black text-emerald-600">+{payment.amount.toFixed(2)}</td>
129
- <td className="py-3 px-4 text-xs font-bold text-slate-400">
130
- {new Date(payment.date).toLocaleTimeString("ar-EG", { hour: '2-digit', minute: '2-digit', hour12: true })}
131
- </td>
132
  </tr>
133
- ))}
134
- </tbody>
135
- </table>
136
- </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
137
  )}
138
  </div>
139
 
@@ -151,33 +173,42 @@ const DailyReport = () => {
151
  <p className="text-slate-500 font-bold">ู„ู… ูŠุชู… ุชุณุฌูŠู„ ุฃูŠ ู…ุตุงุฑูŠู ุญุชู‰ ุงู„ุขู†</p>
152
  </div>
153
  ) : (
154
- <div className="overflow-x-auto overflow-y-auto max-h-[350px] custom-scroll rounded-2xl border border-slate-100 relative w-full">
155
- <table className="w-full text-right border-collapse">
156
- <thead className="sticky top-0 z-10 bg-slate-50 shadow-sm border-b border-slate-200">
157
- <tr>
158
- <th className="py-3 px-4 font-bold text-slate-500 text-sm">ุจูŠุงู† ุงู„ู…ุตุฑูˆู</th>
159
- <th className="py-3 px-4 font-bold text-slate-500 text-sm">ุงู„ู‚ูŠู…ุฉ</th>
160
- <th className="py-3 px-4 font-bold text-slate-500 text-sm text-center">ุฅู„ุบุงุก</th>
161
- </tr>
162
- </thead>
163
- <tbody className="divide-y divide-slate-100 bg-white">
164
- {expensesList?.map((expense) => (
165
- <tr key={expense._id} className="hover:bg-slate-50 relative">
166
- <td className="py-3 px-4 font-bold text-slate-700">
167
- {expense.title}
168
- <div className="text-xs text-slate-400 font-normal mt-0.5">
169
- {new Date(expense.date).toLocaleTimeString("ar-EG", { hour: '2-digit', minute: '2-digit', hour12: true })}
170
- </div>
171
- </td>
172
- <td className="py-3 px-4 font-black text-rose-600">-{expense.amount.toFixed(2)}</td>
173
- <td className="py-3 px-4 text-center">
174
- <DeleteExpenseButton expenseId={expense._id} />
175
- </td>
176
  </tr>
177
- ))}
178
- </tbody>
179
- </table>
180
- </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
181
  )}
182
  </div>
183
  </div>
@@ -187,6 +218,47 @@ const DailyReport = () => {
187
  );
188
  };
189
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
190
  // --- Add Expense Modal ---
191
  const AddExpenseModal = ({ onClose }) => {
192
  const queryClient = useQueryClient();
@@ -194,7 +266,7 @@ const AddExpenseModal = ({ onClose }) => {
194
  const { mutate, isPending } = useMutation({
195
  mutationFn: (values) => axios.post(`${apiUrl}/expenses`, values),
196
  onSuccess: () => {
197
- queryClient.invalidateQueries(["dailyReport"]);
198
  toast.success("ุชู… ุชุณุฌูŠู„ ุงู„ู…ุตุฑูˆู ุจู†ุฌุงุญ ูˆุฎุตู…ู‡ ู…ู† ุงู„ุฏุฑุฌ");
199
  onClose();
200
  },
@@ -259,7 +331,7 @@ const DeleteExpenseButton = ({ expenseId }) => {
259
  const { mutate, isPending } = useMutation({
260
  mutationFn: () => axios.delete(`${apiUrl}/expenses/${expenseId}`),
261
  onSuccess: () => {
262
- queryClient.invalidateQueries(["dailyReport"]);
263
  toast.success("ุชู… ุงู„ุชุฑุงุฌุน ุนู† ุงู„ู…ุตุฑูˆู ูˆุฑุฏ ุงู„ู…ุจู„ุบ ู„ู„ุฏุฑุฌ");
264
  }
265
  });
 
1
  import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
2
  import axios from "axios";
3
  import LodderSpinner from "../../common/LoaderSpinner";
4
+ import { Banknote, TrendingUp, ReceiptText, Clock, ArrowDownRight, PlusCircle, Trash2, Wallet, ChevronRight, ChevronLeft } from "lucide-react";
5
  import { useState } from "react";
6
  import { toast } from "react-toastify";
7
  import { useFormik } from "formik";
8
  import * as Yup from "yup";
9
 
10
  const apiUrl = import.meta.env.VITE_API_URL;
11
+ const LIMIT = 5;
12
 
13
  const DailyReport = () => {
14
  const [openExpenseModal, setOpenExpenseModal] = useState(false);
15
+ const [paymentsPage, setPaymentsPage] = useState(1);
16
+ const [expensesPage, setExpensesPage] = useState(1);
17
 
18
  const { data, isLoading, refetch } = useQuery({
19
+ queryKey: ["dailyReport", paymentsPage, expensesPage],
20
+ queryFn: () => axios.get(`${apiUrl}/reports/daily`, {
21
+ params: { limit: LIMIT, paymentsPage, expensesPage }
22
+ }),
23
  refetchInterval: 30000,
24
  });
25
  if (isLoading) return <LodderSpinner />;
26
 
27
  const report = data?.data;
28
+ // Backend returns { data: [...], pagination: {...} } for both lists
29
+ const recentPayments = Array.isArray(report?.recentPayments?.data)
30
+ ? report.recentPayments.data
31
+ : [];
32
+ const paymentsPagination = report?.recentPayments?.pagination ?? { totalPages: 0, total: 0 };
33
 
34
+ const expensesList = Array.isArray(report?.expensesList?.data)
35
+ ? report.expensesList.data
36
+ : [];
37
+ const expensesPagination = report?.expensesList?.pagination ?? { totalPages: 0, total: 0 };
38
+
39
  return (
40
  <div className="space-y-6">
41
  {/* Header Row */}
 
125
  <p className="text-slate-500 font-bold">ู„ุง ุชูˆุฌุฏ ุฅูŠุฑุงุฏุงุช ูƒุงุด ู…ุณุฌู„ุฉ ุงู„ูŠูˆู…</p>
126
  </div>
127
  ) : (
128
+ <>
129
+ <div className="overflow-x-auto overflow-y-auto max-h-[350px] custom-scroll rounded-2xl border border-slate-100 relative">
130
+ <table className="w-full text-right border-collapse">
131
+ <thead className="sticky top-0 z-10 bg-slate-50 shadow-sm border-b border-slate-200">
132
+ <tr>
133
+ <th className="py-3 px-4 font-bold text-slate-500 text-sm">ุงู„ุนู…ูŠู„</th>
134
+ <th className="py-3 px-4 font-bold text-slate-500 text-sm">ุงู„ู…ุจู„ุบ</th>
135
+ <th className="py-3 px-4 font-bold text-slate-500 text-sm">ุงู„ุชูˆู‚ูŠุช</th>
 
 
 
 
 
 
 
 
 
136
  </tr>
137
+ </thead>
138
+ <tbody className="divide-y divide-slate-100 bg-white">
139
+ {recentPayments?.map((payment, idx) => (
140
+ <tr key={idx} className="hover:bg-slate-50">
141
+ <td className="py-3 px-4 font-bold text-slate-700">{payment.customerName}</td>
142
+ <td className="py-3 px-4 font-black text-emerald-600">+{payment.amount.toFixed(2)}</td>
143
+ <td className="py-3 px-4 text-xs font-bold text-slate-400">
144
+ {new Date(payment.date).toLocaleTimeString("ar-EG", { hour: '2-digit', minute: '2-digit', hour12: true })}
145
+ </td>
146
+ </tr>
147
+ ))}
148
+ </tbody>
149
+ </table>
150
+ </div>
151
+ {paymentsPagination && paymentsPagination.totalPages > 1 && (
152
+ <MiniPagination
153
+ pagination={paymentsPagination}
154
+ page={paymentsPage}
155
+ setPage={setPaymentsPage}
156
+ />
157
+ )}
158
+ </>
159
  )}
160
  </div>
161
 
 
173
  <p className="text-slate-500 font-bold">ู„ู… ูŠุชู… ุชุณุฌูŠู„ ุฃูŠ ู…ุตุงุฑูŠู ุญุชู‰ ุงู„ุขู†</p>
174
  </div>
175
  ) : (
176
+ <>
177
+ <div className="overflow-x-auto overflow-y-auto max-h-[350px] custom-scroll rounded-2xl border border-slate-100 relative w-full">
178
+ <table className="w-full text-right border-collapse">
179
+ <thead className="sticky top-0 z-10 bg-slate-50 shadow-sm border-b border-slate-200">
180
+ <tr>
181
+ <th className="py-3 px-4 font-bold text-slate-500 text-sm">ุจูŠุงู† ุงู„ู…ุตุฑูˆู</th>
182
+ <th className="py-3 px-4 font-bold text-slate-500 text-sm">ุงู„ู‚ูŠู…ุฉ</th>
183
+ <th className="py-3 px-4 font-bold text-slate-500 text-sm text-center">ุฅู„ุบุงุก</th>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
184
  </tr>
185
+ </thead>
186
+ <tbody className="divide-y divide-slate-100 bg-white">
187
+ {expensesList?.map((expense) => (
188
+ <tr key={expense._id} className="hover:bg-slate-50 relative">
189
+ <td className="py-3 px-4 font-bold text-slate-700">
190
+ {expense.title}
191
+ <div className="text-xs text-slate-400 font-normal mt-0.5">
192
+ {new Date(expense.date).toLocaleTimeString("ar-EG", { hour: '2-digit', minute: '2-digit', hour12: true })}
193
+ </div>
194
+ </td>
195
+ <td className="py-3 px-4 font-black text-rose-600">-{expense.amount.toFixed(2)}</td>
196
+ <td className="py-3 px-4 text-center">
197
+ <DeleteExpenseButton expenseId={expense._id} />
198
+ </td>
199
+ </tr>
200
+ ))}
201
+ </tbody>
202
+ </table>
203
+ </div>
204
+ {expensesPagination && expensesPagination.totalPages > 1 && (
205
+ <MiniPagination
206
+ pagination={expensesPagination}
207
+ page={expensesPage}
208
+ setPage={setExpensesPage}
209
+ />
210
+ )}
211
+ </>
212
  )}
213
  </div>
214
  </div>
 
218
  );
219
  };
220
 
221
+ // โ”€โ”€ Mini pagination for DailyReport tables โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
222
+ const MiniPagination = ({ pagination, page, setPage }) => {
223
+ const { total, totalPages } = pagination;
224
+ return (
225
+ <div className="flex items-center justify-between mt-3 pt-3 border-t border-slate-100">
226
+ <span className="text-xs font-bold text-slate-400">
227
+ {total} ู†ุชูŠุฌุฉ ยท ุตูุญุฉ {page} ู…ู† {totalPages}
228
+ </span>
229
+ <div className="flex gap-1.5">
230
+ <button
231
+ onClick={() => setPage((p) => Math.max(1, p - 1))}
232
+ disabled={page === 1}
233
+ className="w-8 h-8 flex items-center justify-center rounded-lg border border-slate-200 text-slate-500 hover:bg-slate-100 disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
234
+ >
235
+ <ChevronRight size={15} />
236
+ </button>
237
+ {Array.from({ length: totalPages }, (_, i) => i + 1).map((p) => (
238
+ <button
239
+ key={p}
240
+ onClick={() => setPage(p)}
241
+ className={`w-8 h-8 flex items-center justify-center rounded-lg border text-xs font-bold transition-colors ${
242
+ p === page
243
+ ? "bg-slate-800 border-slate-800 text-white"
244
+ : "border-slate-200 text-slate-500 hover:bg-slate-100"
245
+ }`}
246
+ >
247
+ {p}
248
+ </button>
249
+ ))}
250
+ <button
251
+ onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
252
+ disabled={page === totalPages}
253
+ className="w-8 h-8 flex items-center justify-center rounded-lg border border-slate-200 text-slate-500 hover:bg-slate-100 disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
254
+ >
255
+ <ChevronLeft size={15} />
256
+ </button>
257
+ </div>
258
+ </div>
259
+ );
260
+ };
261
+
262
  // --- Add Expense Modal ---
263
  const AddExpenseModal = ({ onClose }) => {
264
  const queryClient = useQueryClient();
 
266
  const { mutate, isPending } = useMutation({
267
  mutationFn: (values) => axios.post(`${apiUrl}/expenses`, values),
268
  onSuccess: () => {
269
+ queryClient.invalidateQueries({ queryKey: ["dailyReport"] });
270
  toast.success("ุชู… ุชุณุฌูŠู„ ุงู„ู…ุตุฑูˆู ุจู†ุฌุงุญ ูˆุฎุตู…ู‡ ู…ู† ุงู„ุฏุฑุฌ");
271
  onClose();
272
  },
 
331
  const { mutate, isPending } = useMutation({
332
  mutationFn: () => axios.delete(`${apiUrl}/expenses/${expenseId}`),
333
  onSuccess: () => {
334
+ queryClient.invalidateQueries({ queryKey: ["dailyReport"] });
335
  toast.success("ุชู… ุงู„ุชุฑุงุฌุน ุนู† ุงู„ู…ุตุฑูˆู ูˆุฑุฏ ุงู„ู…ุจู„ุบ ู„ู„ุฏุฑุฌ");
336
  }
337
  });
frontend/src/components/Suppliers/SuppliersWorkspace.jsx CHANGED
@@ -1,4 +1,5 @@
1
  import { useState } from "react";
 
2
  import axios from "axios";
3
  import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
4
  import { ArrowUpRight, Boxes, Factory, Loader2, MessageCircle, PlusCircle, Search, Trash2 } from "lucide-react";
@@ -19,17 +20,18 @@ const SuppliersWorkspace = () => {
19
  const companyName = user?.tenant?.name || "ุงู„ุดุฑูƒุฉ";
20
  const queryClient = useQueryClient();
21
  const [searchTerm, setSearchTerm] = useState("");
 
22
  const [page, setPage] = useState(1);
23
  const [purchaseSupplier, setPurchaseSupplier] = useState(null);
24
  const [paymentSupplier, setPaymentSupplier] = useState(null);
25
 
26
  const { data: response, isLoading } = useQuery({
27
- queryKey: ["suppliers", page, searchTerm],
28
  queryFn: () => axios.get(`${apiUrl}/suppliers`, {
29
  params: {
30
  page,
31
  limit: 5,
32
- search: searchTerm
33
  }
34
  }),
35
  refetchOnWindowFocus: false,
 
1
  import { useState } from "react";
2
+ import useDebounce from "../../hooks/useDebounce";
3
  import axios from "axios";
4
  import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
5
  import { ArrowUpRight, Boxes, Factory, Loader2, MessageCircle, PlusCircle, Search, Trash2 } from "lucide-react";
 
20
  const companyName = user?.tenant?.name || "ุงู„ุดุฑูƒุฉ";
21
  const queryClient = useQueryClient();
22
  const [searchTerm, setSearchTerm] = useState("");
23
+ const debouncedSearch = useDebounce(searchTerm, 2000);
24
  const [page, setPage] = useState(1);
25
  const [purchaseSupplier, setPurchaseSupplier] = useState(null);
26
  const [paymentSupplier, setPaymentSupplier] = useState(null);
27
 
28
  const { data: response, isLoading } = useQuery({
29
+ queryKey: ["suppliers", page, debouncedSearch],
30
  queryFn: () => axios.get(`${apiUrl}/suppliers`, {
31
  params: {
32
  page,
33
  limit: 5,
34
+ search: debouncedSearch
35
  }
36
  }),
37
  refetchOnWindowFocus: false,
frontend/src/hooks/useDebounce.js ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useState, useEffect } from "react";
2
+
3
+ /**
4
+ * useDebounce
5
+ * Delays updating the returned value until `delay` ms have passed
6
+ * since the last change to `value`. Use this to avoid triggering
7
+ * a server request on every keystroke in a search input.
8
+ *
9
+ * @param {*} value - the value to debounce (e.g. a search string)
10
+ * @param {number} delay - debounce delay in milliseconds (default: 400)
11
+ * @returns debounced value
12
+ *
13
+ * @example
14
+ * const debouncedSearch = useDebounce(searchTerm, 400);
15
+ * useQuery({ queryKey: ["customers", debouncedSearch], ... });
16
+ */
17
+ const useDebounce = (value, delay = 400) => {
18
+ const [debouncedValue, setDebouncedValue] = useState(value);
19
+
20
+ useEffect(() => {
21
+ const timer = setTimeout(() => {
22
+ setDebouncedValue(value);
23
+ }, delay);
24
+
25
+ // Cancel the timeout if value changes before delay elapses
26
+ return () => clearTimeout(timer);
27
+ }, [value, delay]);
28
+
29
+ return debouncedValue;
30
+ };
31
+
32
+ export default useDebounce;