25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

314 lines
11 KiB

  1. //src\components\ReportSearchBox\SearchBox.tsx
  2. "use client";
  3. import Grid from "@mui/material/Grid";
  4. import Card from "@mui/material/Card";
  5. import CardContent from "@mui/material/CardContent";
  6. import Typography from "@mui/material/Typography";
  7. import React, { useCallback, useMemo, useState } from "react";
  8. import { useTranslation } from "react-i18next";
  9. import TextField from "@mui/material/TextField";
  10. import FormControl from "@mui/material/FormControl";
  11. import InputLabel from "@mui/material/InputLabel";
  12. import Select, { SelectChangeEvent } from "@mui/material/Select";
  13. import MenuItem from "@mui/material/MenuItem";
  14. import CardActions from "@mui/material/CardActions";
  15. import Button from "@mui/material/Button";
  16. import RestartAlt from "@mui/icons-material/RestartAlt";
  17. import Search from "@mui/icons-material/Search";
  18. import dayjs from "dayjs";
  19. import "dayjs/locale/zh-hk";
  20. import { DatePicker } from "@mui/x-date-pickers/DatePicker";
  21. import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
  22. import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
  23. import { Box } from "@mui/material";
  24. import * as XLSX from 'xlsx-js-style';
  25. //import { DownloadReportButton } from '../LateStartReportGen/DownloadReportButton';
  26. interface BaseCriterion<T extends string> {
  27. label: string;
  28. label2?: string;
  29. paramName: T;
  30. paramName2?: T;
  31. }
  32. interface TextCriterion<T extends string> extends BaseCriterion<T> {
  33. type: "text";
  34. }
  35. interface SelectCriterion<T extends string> extends BaseCriterion<T> {
  36. type: "select";
  37. options: string[];
  38. }
  39. interface DateRangeCriterion<T extends string> extends BaseCriterion<T> {
  40. type: "dateRange";
  41. }
  42. export type Criterion<T extends string> =
  43. | TextCriterion<T>
  44. | SelectCriterion<T>
  45. | DateRangeCriterion<T>;
  46. interface Props<T extends string> {
  47. criteria: Criterion<T>[];
  48. onSearch: (inputs: Record<T, string>) => void;
  49. onReset?: () => void;
  50. }
  51. function SearchBox<T extends string>({
  52. criteria,
  53. onSearch,
  54. onReset,
  55. }: Props<T>) {
  56. const { t } = useTranslation("common");
  57. const defaultInputs = useMemo(
  58. () =>
  59. criteria.reduce<Record<T, string>>(
  60. (acc, c) => {
  61. return { ...acc, [c.paramName]: c.type === "select" ? "All" : "" };
  62. },
  63. {} as Record<T, string>,
  64. ),
  65. [criteria],
  66. );
  67. const [inputs, setInputs] = useState(defaultInputs);
  68. const makeInputChangeHandler = useCallback(
  69. (paramName: T): React.ChangeEventHandler<HTMLInputElement> => {
  70. return (e) => {
  71. setInputs((i) => ({ ...i, [paramName]: e.target.value }));
  72. };
  73. },
  74. [],
  75. );
  76. const makeSelectChangeHandler = useCallback((paramName: T) => {
  77. return (e: SelectChangeEvent) => {
  78. setInputs((i) => ({ ...i, [paramName]: e.target.value }));
  79. };
  80. }, []);
  81. const makeDateChangeHandler = useCallback((paramName: T) => {
  82. return (e: any) => {
  83. setInputs((i) => ({ ...i, [paramName]: dayjs(e).format("YYYY-MM-DD") }));
  84. };
  85. }, []);
  86. const makeDateToChangeHandler = useCallback((paramName: T) => {
  87. return (e: any) => {
  88. setInputs((i) => ({
  89. ...i,
  90. [paramName + "To"]: dayjs(e).format("YYYY-MM-DD"),
  91. }));
  92. };
  93. }, []);
  94. const handleReset = () => {
  95. setInputs(defaultInputs);
  96. onReset?.();
  97. };
  98. const handleSearch = () => {
  99. onSearch(inputs);
  100. };
  101. const handleDownload = async () => {
  102. //setIsLoading(true);
  103. try {
  104. const response = await fetch('/temp/AR01_Late Start Report.xlsx', {
  105. headers: {
  106. 'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  107. },
  108. });
  109. if (!response.ok) throw new Error('Network response was not ok.');
  110. const data = await response.blob();
  111. const reader = new FileReader();
  112. reader.onload = (e) => {
  113. if (e.target && e.target.result) {
  114. const ab = e.target.result as ArrayBuffer;
  115. const workbook = XLSX.read(ab, { type: 'array' });
  116. const firstSheetName = workbook.SheetNames[0];
  117. const worksheet = workbook.Sheets[firstSheetName];
  118. // Add the current date to cell C2
  119. const cellAddress = 'C2';
  120. const date = new Date().toISOString().split('T')[0]; // Format YYYY-MM-DD
  121. const formattedDate = date.replace(/-/g, '/'); // Change format to YYYY/MM/DD
  122. XLSX.utils.sheet_add_aoa(worksheet, [[formattedDate]], { origin: cellAddress });
  123. // Calculate the maximum length of content in each column and set column width
  124. const colWidths: number[] = [];
  125. const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1, defval: "", blankrows: true }) as (string | number)[][];
  126. jsonData.forEach((row: (string | number)[]) => {
  127. row.forEach((cell: string | number, index: number) => {
  128. const valueLength = cell.toString().length;
  129. colWidths[index] = Math.max(colWidths[index] || 0, valueLength);
  130. });
  131. });
  132. // Style for cell A1: Font size 16 and bold
  133. if (worksheet['A1']) {
  134. worksheet['A1'].s = {
  135. font: {
  136. bold: true,
  137. sz: 16, // Font size 16
  138. //name: 'Times New Roman' // Specify font
  139. }
  140. };
  141. }
  142. // Apply styles from A2 to A4 (bold)
  143. ['A2', 'A3', 'A4'].forEach(cell => {
  144. if (worksheet[cell]) {
  145. worksheet[cell].s = { font: { bold: true } };
  146. }
  147. });
  148. // Formatting from A6 to J6
  149. // Apply styles from A6 to J6 (bold, bottom border, center alignment)
  150. for (let col = 0; col < 10; col++) { // Columns A to J
  151. const cellRef = XLSX.utils.encode_col(col) + '6';
  152. if (worksheet[cellRef]) {
  153. worksheet[cellRef].s = {
  154. font: { bold: true },
  155. alignment: { horizontal: 'center' },
  156. border: {
  157. bottom: { style: 'thin', color: { auto: 1 } }
  158. }
  159. };
  160. }
  161. }
  162. const firstTableData = [
  163. ['Column1', 'Column2', 'Column3'], // Row 1
  164. ['Data1', 'Data2', 'Data3'], // Row 2
  165. // ... more rows as needed
  166. ];
  167. // Find the last row of the first table
  168. let lastRowOfFirstTable = 6; // Starting row for data in the first table
  169. while (worksheet[XLSX.utils.encode_cell({ c: 0, r: lastRowOfFirstTable })]) {
  170. lastRowOfFirstTable++;
  171. }
  172. // Apply calculated widths to each column, skipping column A
  173. worksheet['!cols'] = colWidths.map((width, index) => {
  174. if (index === 0) {
  175. return { wch: 8 }; // Set default or specific width for column A if needed
  176. }
  177. return { wch: width + 2 }; // Add padding to width
  178. });
  179. // Format filename with date
  180. const today = new Date().toISOString().split('T')[0].replace(/-/g, '_'); // Get current date and format as YYYY_MM_DD
  181. const filename = `AR01_Late_Start_Report_${today}.xlsx`; // Append formatted date to the filename
  182. // Convert workbook back to XLSX file
  183. XLSX.writeFile(workbook, filename);
  184. } else {
  185. throw new Error('Failed to load file');
  186. }
  187. };
  188. reader.readAsArrayBuffer(data);
  189. } catch (error) {
  190. console.error('Error downloading the file: ', error);
  191. }
  192. //setIsLoading(false);
  193. };
  194. return (
  195. <Card>
  196. <CardContent sx={{ display: "flex", flexDirection: "column", gap: 1 }}>
  197. <Typography variant="overline">{t("Search Criteria")}</Typography>
  198. <Grid container spacing={2} columns={{ xs: 6, sm: 12 }}>
  199. {criteria.map((c) => {
  200. return (
  201. <Grid key={c.paramName} item xs={6}>
  202. {c.type === "text" && (
  203. <TextField
  204. label={c.label}
  205. fullWidth
  206. onChange={makeInputChangeHandler(c.paramName)}
  207. value={inputs[c.paramName]}
  208. />
  209. )}
  210. {c.type === "select" && (
  211. <FormControl fullWidth>
  212. <InputLabel>{c.label}</InputLabel>
  213. <Select
  214. label={c.label}
  215. onChange={makeSelectChangeHandler(c.paramName)}
  216. value={inputs[c.paramName]}
  217. >
  218. <MenuItem value={"All"}>{t("All")}</MenuItem>
  219. {c.options.map((option, index) => (
  220. <MenuItem key={`${option}-${index}`} value={option}>
  221. {option}
  222. </MenuItem>
  223. ))}
  224. </Select>
  225. </FormControl>
  226. )}
  227. {c.type === "dateRange" && (
  228. <LocalizationProvider
  229. dateAdapter={AdapterDayjs}
  230. // TODO: Should maybe use a custom adapterLocale here to support YYYY-MM-DD
  231. adapterLocale="zh-hk"
  232. >
  233. <Box display="flex">
  234. <FormControl fullWidth>
  235. <DatePicker
  236. label={c.label}
  237. onChange={makeDateChangeHandler(c.paramName)}
  238. value={inputs[c.paramName] ? dayjs(inputs[c.paramName]) : null}
  239. />
  240. </FormControl>
  241. <Box
  242. display="flex"
  243. alignItems="center"
  244. justifyContent="center"
  245. marginInline={2}
  246. >
  247. {"-"}
  248. </Box>
  249. <FormControl fullWidth>
  250. <DatePicker
  251. label={c.label2}
  252. onChange={makeDateToChangeHandler(c.paramName)}
  253. value={inputs[c.paramName.concat("To") as T] ? dayjs(inputs[c.paramName.concat("To") as T]) : null}
  254. />
  255. </FormControl>
  256. </Box>
  257. </LocalizationProvider>
  258. )}
  259. </Grid>
  260. );
  261. })}
  262. </Grid>
  263. <CardActions sx={{ justifyContent: "flex-end" }}>
  264. <Button
  265. variant="text"
  266. startIcon={<RestartAlt />}
  267. onClick={handleReset}
  268. >
  269. {t("Reset")}
  270. </Button>
  271. <Button
  272. variant="outlined"
  273. startIcon={<Search />}
  274. onClick={handleDownload}
  275. >
  276. {t("Download")}
  277. </Button>
  278. </CardActions>
  279. </CardContent>
  280. </Card>
  281. );
  282. }
  283. export default SearchBox;