FPSMS-frontend
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 

250 rader
9.3 KiB

  1. "use client";
  2. import React, { useCallback, useEffect, useMemo, useState } from "react";
  3. import SearchBox, { Criterion } from "../SearchBox";
  4. import { ItemsResult } from "@/app/api/settings/item";
  5. import SearchResults, { Column } from "../SearchResults";
  6. import { EditNote } from "@mui/icons-material";
  7. import { useRouter, useSearchParams } from "next/navigation";
  8. import { GridDeleteIcon } from "@mui/x-data-grid";
  9. import { TypeEnum } from "@/app/utils/typeEnum";
  10. import axios from "axios";
  11. import { BASE_API_URL, NEXT_PUBLIC_API_URL } from "@/config/api";
  12. import { useTranslation } from "react-i18next";
  13. import axiosInstance from "@/app/(main)/axios/axiosInstance";
  14. import Qs from 'qs';
  15. import EditableSearchResults from "@/components/SearchResults/EditableSearchResults"; // Make sure to import Qs
  16. import { ProdScheduleResult, ProdScheduleResultByPage, SearchProdSchedule, fetchProdSchedules } from "@/app/api/scheduling/actions";
  17. import { arrayToDateString, decimalFormatter } from "@/app/utils/formatUtil";
  18. import { isEqual, uniqBy } from "lodash";
  19. import dayjs from "dayjs";
  20. import { defaultPagingController } from "../SearchResults/SearchResults";
  21. import { ScheduleType } from "@/app/api/scheduling";
  22. // type RecordStructure ={
  23. // id: number,
  24. // schedulePeriod: string,
  25. // scheduleAt: string
  26. // };
  27. type Props = {
  28. type: ScheduleType;
  29. // initProdSchedules: ProdScheduleResultByPage;
  30. defaultInputs: SearchProdSchedule;
  31. };
  32. type SearchQuery = Partial<Omit<SearchProdSchedule, "id" | "types" | "pageSize" | "pageNum">>;
  33. type SearchParamNames = keyof SearchQuery;
  34. const RSOverview: React.FC<Props> = ({ type, defaultInputs }) => {
  35. const [filteredSchedules, setFilteredSchedules] = useState<ProdScheduleResult[]>([]);
  36. const { t } = useTranslation("schedule");
  37. const router = useRouter();
  38. // const [filterObj, setFilterObj] = useState({});
  39. // const [tempSelectedValue, setTempSelectedValue] = useState({});
  40. const [pagingController, setPagingController] = useState(defaultPagingController)
  41. const [totalCount, setTotalCount] = useState(0)
  42. const [inputs, setInputs] = useState(defaultInputs)
  43. const searchCriteria: Criterion<SearchParamNames>[] = useMemo(
  44. () => {
  45. var searchCriteria: Criterion<SearchParamNames>[] = [
  46. { label: t("Schedule Period"), label2: t("Schedule Period To"), paramName: "schedulePeriod", type: "dateRange" },
  47. { label: t("Scheduled At"), paramName: "scheduleAt", type: "date" },
  48. { label: t("Product Count"), paramName: "totalEstProdCount", type: "text" },
  49. ]
  50. return searchCriteria
  51. },
  52. [t]
  53. );
  54. // const onDetailClick = useCallback(
  55. // (item: ItemsResult) => {
  56. // router.push(`/settings/items/edit?id=${item.id}`);
  57. // },
  58. // [router]
  59. // );
  60. // const onDeleteClick = useCallback(
  61. // (item: ItemsResult) => { },
  62. // [router]
  63. // );
  64. const onDetailClick = (record: ProdScheduleResult) => {
  65. console.log("[debug] record", record);
  66. router.push(`/scheduling/rough/edit?id=${record.id}`);
  67. }
  68. const columns = useMemo<Column<ProdScheduleResult>[]>(
  69. () => [
  70. {
  71. name: "id",
  72. label: t("Details"),
  73. onClick: (record) => onDetailClick(record),
  74. buttonIcon: <EditNote />,
  75. },
  76. {
  77. name: "schedulePeriod",
  78. label: t("Demand Forecast Period"),
  79. renderCell: (params) => {
  80. return `${arrayToDateString(params.schedulePeriod)} - ${arrayToDateString(params.schedulePeriodTo)}`
  81. }
  82. },
  83. {
  84. name: "scheduleAt",
  85. label: t("Schedule At"),
  86. renderCell: (params) => {
  87. return arrayToDateString(params.scheduleAt)
  88. }
  89. },
  90. {
  91. name: "totalEstProdCount",
  92. label: t("Product Count(s)"),
  93. headerAlign: "right",
  94. align: "right",
  95. renderCell: (params) => {
  96. return decimalFormatter.format(params.totalEstProdCount)
  97. }
  98. },
  99. // {
  100. // name: "action",
  101. // label: t(""),
  102. // buttonIcon: <GridDeleteIcon />,
  103. // onClick: onDeleteClick,
  104. // },
  105. ],
  106. [filteredSchedules]
  107. );
  108. // useEffect(() => {
  109. // refetchData(filterObj);
  110. // }, [filterObj, pagingController.pageNum, pagingController.pageSize]);
  111. const refetchData = useCallback(async (query: Record<SearchParamNames, string> | SearchProdSchedule, actionType: "reset" | "search" | "paging") => {
  112. // console.log(query)
  113. const params: SearchProdSchedule = {
  114. scheduleAt: dayjs(query?.scheduleAt).isValid() ? query?.scheduleAt : undefined,
  115. schedulePeriod: dayjs(query?.schedulePeriod).isValid() ? query?.schedulePeriod : undefined,
  116. schedulePeriodTo: dayjs(query?.schedulePeriodTo).isValid() ? query?.schedulePeriodTo : undefined,
  117. totalEstProdCount: query?.totalEstProdCount ? Number(query?.totalEstProdCount) : undefined,
  118. types: ["rough"],
  119. pageNum: pagingController.pageNum - 1,
  120. pageSize: pagingController.pageSize
  121. }
  122. const response = await fetchProdSchedules(params)
  123. // console.log(response)
  124. if (response) {
  125. setTotalCount(response.total)
  126. switch (actionType) {
  127. case "reset":
  128. case "search":
  129. setFilteredSchedules(() => response.records)
  130. break;
  131. case "paging":
  132. setFilteredSchedules((fs) => uniqBy([...fs, ...response.records], "id"))
  133. break;
  134. }
  135. }
  136. }, [pagingController, setPagingController])
  137. useEffect(() => {
  138. refetchData(inputs, "paging")
  139. }, [pagingController])
  140. // const refetchData = async (filterObj: SearchQuery) => {
  141. // const authHeader = axiosInstance.defaults.headers['Authorization'];
  142. // if (!authHeader) {
  143. // return; // Exit the function if the token is not set
  144. // }
  145. // const params ={
  146. // pageNum: pagingController.pageNum,
  147. // pageSize: pagingController.pageSize,
  148. // ...filterObj,
  149. // ...tempSelectedValue,
  150. // }
  151. // try {
  152. // // const response = await axiosInstance.get<ItemsResult[]>(`${NEXT_PUBLIC_API_URL}/items/getRecordByPage`, {
  153. // // params,
  154. // // paramsSerializer: (params) => {
  155. // // return Qs.stringify(params, { arrayFormat: 'repeat' });
  156. // // },
  157. // // });
  158. // //setFilteredSchedules(response.data.records);
  159. // // setFilteredSchedules([
  160. // // {
  161. // // id: 1,
  162. // // scheduledPeriod: "2025-05-11 to 2025-05-17",
  163. // // scheduledAt: "2025-05-07",
  164. // // productCount: 13,
  165. // // },
  166. // // {
  167. // // id: 2,
  168. // // scheduledPeriod: "2025-05-18 to 2025-05-24",
  169. // // scheduledAt: "2025-05-14",
  170. // // productCount: 15,
  171. // // },
  172. // // {
  173. // // id: 3,
  174. // // scheduledPeriod: "2025-05-25 to 2025-05-31",
  175. // // scheduledAt: "2025-05-21",
  176. // // productCount: 13,
  177. // // },
  178. // // ])
  179. // setPagingController({
  180. // ...pagingController,
  181. // // totalCount: response.data.total
  182. // })
  183. // // return response; // Return the data from the response
  184. // } catch (error) {
  185. // console.error('Error fetching items:', error);
  186. // throw error; // Rethrow the error for further handling
  187. // }
  188. // };
  189. const onReset = useCallback(() => {
  190. // setFilteredSchedules(items ?? []);
  191. // setFilterObj({});
  192. // setTempSelectedValue({});
  193. refetchData(inputs, "reset");
  194. }, []);
  195. return (
  196. <>
  197. <SearchBox
  198. criteria={searchCriteria}
  199. onSearch={(query) => {
  200. // resetPagingController()
  201. setInputs(() => (
  202. {
  203. scheduleAt: query?.scheduleAt,
  204. schedulePeriod: query?.schedulePeriod,
  205. schedulePeriodTo: query?.schedulePeriodTo,
  206. totalEstProdCount: Number(query?.totalEstProdCount)
  207. }
  208. ))
  209. refetchData(query, "search")
  210. // setFilterObj({
  211. // ...query
  212. // })
  213. }}
  214. onReset={onReset}
  215. />
  216. <SearchResults<ProdScheduleResult>
  217. items={filteredSchedules}
  218. columns={columns}
  219. setPagingController={setPagingController}
  220. pagingController={pagingController}
  221. totalCount={totalCount}
  222. // isAutoPaging={false}
  223. />
  224. </>
  225. );
  226. };
  227. export default RSOverview;