| @@ -0,0 +1,44 @@ | |||
| import { Suspense } from "react"; | |||
| import { Metadata } from "next"; | |||
| import Typography from "@mui/material/Typography"; | |||
| import { getServerI18n } from "@/i18n"; | |||
| import QrCodeHandleSearchWrapper from "@/components/qrCodeHandles/qrCodeHandleSearchWrapper"; | |||
| import QrCodeHandleEquipmentSearchWrapper from "@/components/qrCodeHandles/qrCodeHandleEquipmentSearchWrapper"; | |||
| import QrCodeHandleTabs from "@/components/qrCodeHandles/qrCodeHandleTabs"; | |||
| import { I18nProvider } from "@/i18n"; | |||
| import Box from "@mui/material/Box"; | |||
| export const metadata: Metadata = { title: "QR Code Handle" }; | |||
| const QrCodeHandlePage: React.FC = async () => { | |||
| const { t } = await getServerI18n("common"); | |||
| return ( | |||
| <Box sx={{ width: "100%" }}> | |||
| <Typography variant="h5" sx={{ mb: 3 }}> | |||
| {t("QR Code Handle")} | |||
| </Typography> | |||
| <I18nProvider namespaces={["common", "user"]}> | |||
| <QrCodeHandleTabs | |||
| userTabContent={ | |||
| <Suspense fallback={<QrCodeHandleSearchWrapper.Loading />}> | |||
| <I18nProvider namespaces={["user", "common", "dashboard"]}> | |||
| <QrCodeHandleSearchWrapper /> | |||
| </I18nProvider> | |||
| </Suspense> | |||
| } | |||
| equipmentTabContent={ | |||
| <Suspense fallback={<QrCodeHandleEquipmentSearchWrapper.Loading />}> | |||
| <I18nProvider namespaces={["common", "project", "dashboard"]}> | |||
| <QrCodeHandleEquipmentSearchWrapper /> | |||
| </I18nProvider> | |||
| </Suspense> | |||
| } | |||
| /> | |||
| </I18nProvider> | |||
| </Box> | |||
| ); | |||
| }; | |||
| export default QrCodeHandlePage; | |||
| @@ -34,7 +34,7 @@ const User: React.FC = async () => { | |||
| {t("Create User")} | |||
| </Button> | |||
| </Stack> | |||
| <I18nProvider namespaces={["user", "common"]}> | |||
| <I18nProvider namespaces={["user", "common", "dashboard"]}> | |||
| <Suspense fallback={<UserSearch.Loading />}> | |||
| <UserSearch /> | |||
| </Suspense> | |||
| @@ -14,9 +14,11 @@ import { cache } from "react"; | |||
| export interface UserInputs { | |||
| username: string; | |||
| // name: string; | |||
| staffNo?: string; | |||
| addAuthIds?: number[]; | |||
| removeAuthIds?: number[]; | |||
| password?: string; | |||
| confirmPassword?: string; | |||
| } | |||
| export interface PasswordInputs { | |||
| @@ -0,0 +1,32 @@ | |||
| "use client"; | |||
| import { NEXT_PUBLIC_API_URL } from "@/config/api"; | |||
| export const exportUserQrCode = async (userIds: number[]): Promise<{ blobValue: Uint8Array; filename: string }> => { | |||
| const token = localStorage.getItem("accessToken"); | |||
| const response = await fetch(`${NEXT_PUBLIC_API_URL}/user/export-qrcode`, { | |||
| method: "POST", | |||
| headers: { | |||
| "Content-Type": "application/json", | |||
| ...(token && { Authorization: `Bearer ${token}` }), | |||
| }, | |||
| body: JSON.stringify({ userIds }), | |||
| }); | |||
| if (!response.ok) { | |||
| if (response.status === 401) { | |||
| throw new Error("Unauthorized: Please log in again"); | |||
| } | |||
| throw new Error(`Failed to export QR code: ${response.status} ${response.statusText}`); | |||
| } | |||
| const filename = response.headers.get("Content-Disposition")?.split("filename=")[1]?.replace(/"/g, "") || "user_qrcode.pdf"; | |||
| const blob = await response.blob(); | |||
| const arrayBuffer = await blob.arrayBuffer(); | |||
| const blobValue = new Uint8Array(arrayBuffer); | |||
| return { blobValue, filename }; | |||
| }; | |||
| @@ -7,6 +7,7 @@ export interface UserResult { | |||
| action: any; | |||
| id: number; | |||
| username: string; | |||
| staffNo: number; | |||
| // name: string; | |||
| } | |||
| @@ -71,3 +72,26 @@ export const fetchEscalationCombo = cache(async () => { | |||
| next: { tags: ["escalationCombo"]} | |||
| }) | |||
| }) | |||
| export const exportUserQrCode = async (userIds: number[]): Promise<{ blobValue: Uint8Array; filename: string }> => { | |||
| const response = await fetch(`${BASE_API_URL}/user/export-qrcode`, { | |||
| method: "POST", | |||
| headers: { | |||
| "Content-Type": "application/json", | |||
| }, | |||
| body: JSON.stringify({ userIds }), | |||
| }); | |||
| if (!response.ok) { | |||
| throw new Error("Failed to export QR code"); | |||
| } | |||
| const filename = response.headers.get("Content-Disposition")?.split("filename=")[1]?.replace(/"/g, "") || "user_qrcode.pdf"; | |||
| const blob = await response.blob(); | |||
| const arrayBuffer = await blob.arrayBuffer(); | |||
| const blobValue = new Uint8Array(arrayBuffer); | |||
| return { blobValue, filename }; | |||
| }; | |||
| @@ -14,6 +14,7 @@ const pathToLabelMap: { [path: string]: string } = { | |||
| "/tasks": "Task Template", | |||
| "/tasks/create": "Create Task Template", | |||
| "/settings/qcItem": "Qc Item", | |||
| "/settings/qrCodeHandle": "QR Code Handle", | |||
| "/settings/rss": "Demand Forecast Setting", | |||
| "/scheduling/rough": "Demand Forecast", | |||
| "/scheduling/rough/edit": "FG & Material Demand Forecast Detail", | |||
| @@ -47,7 +47,7 @@ interface Props { | |||
| auths: auth[]; | |||
| } | |||
| const EditUser: React.FC<Props> = async ({ user, rules, auths }) => { | |||
| const EditUser: React.FC<Props> = ({ user, rules, auths }) => { | |||
| console.log(user); | |||
| const { t } = useTranslation("user"); | |||
| const formProps = useForm<UserInputs>(); | |||
| @@ -73,28 +73,31 @@ const EditUser: React.FC<Props> = async ({ user, rules, auths }) => { | |||
| const errors = formProps.formState.errors; | |||
| const resetForm = React.useCallback(() => { | |||
| const resetForm = React.useCallback((e?: React.MouseEvent<HTMLButtonElement>) => { | |||
| e?.preventDefault(); | |||
| e?.stopPropagation(); | |||
| console.log("triggerred"); | |||
| console.log(addAuthIds); | |||
| try { | |||
| formProps.reset({ | |||
| username: user.username, | |||
| // name: user.name, | |||
| // email: user.email, | |||
| staffNo: user.staffNo?.toString() ??"", | |||
| addAuthIds: addAuthIds, | |||
| removeAuthIds: [], | |||
| password: "", | |||
| confirmPassword: "", | |||
| }); | |||
| formProps.clearErrors(); | |||
| console.log(formProps.formState.defaultValues); | |||
| } catch (error) { | |||
| console.log(error); | |||
| setServerError(t("An error has occurred. Please try again later.")); | |||
| } | |||
| }, [auths, user]); | |||
| }, [formProps, auths, user, addAuthIds, t]); | |||
| useEffect(() => { | |||
| resetForm(); | |||
| }, []); | |||
| }, [user.id]); | |||
| const hasErrorsInTab = ( | |||
| tabIndex: number, | |||
| @@ -146,6 +149,7 @@ const EditUser: React.FC<Props> = async ({ user, rules, auths }) => { | |||
| } | |||
| const userData = { | |||
| username: data.username, | |||
| staffNo: data.staffNo, | |||
| // name: user.name, | |||
| locked: false, | |||
| addAuthIds: data.addAuthIds || [], | |||
| @@ -218,17 +222,25 @@ const EditUser: React.FC<Props> = async ({ user, rules, auths }) => { | |||
| {tabIndex == 0 && <UserDetail />} | |||
| {tabIndex === 1 && <AuthAllocation auths={auths!} />} | |||
| <Stack direction="row" justifyContent="flex-end" gap={1}> | |||
| <Button | |||
| variant="text" | |||
| startIcon={<RestartAlt />} | |||
| onClick={resetForm} | |||
| > | |||
| {t("Reset")} | |||
| </Button> | |||
| <Button | |||
| variant="text" | |||
| startIcon={<RestartAlt />} | |||
| onClick={(e) => { | |||
| e.preventDefault(); | |||
| e.stopPropagation(); | |||
| resetForm(e); | |||
| }} | |||
| type="button" | |||
| > | |||
| {t("Reset")} | |||
| </Button> | |||
| <Button | |||
| variant="outlined" | |||
| startIcon={<Close />} | |||
| onClick={handleCancel} | |||
| type="button" | |||
| > | |||
| {t("Cancel")} | |||
| </Button> | |||
| @@ -20,8 +20,14 @@ const UserDetail: React.FC = () => { | |||
| register, | |||
| formState: { errors }, | |||
| control, | |||
| watch, | |||
| } = useFormContext<UserInputs>(); | |||
| const password = watch("password"); | |||
| const confirmPassword = watch("confirmPassword"); | |||
| const username = watch("username"); | |||
| const staffNo = watch("staffNo"); | |||
| return ( | |||
| <Card> | |||
| <CardContent component={Stack} spacing={4}> | |||
| @@ -33,35 +39,55 @@ const UserDetail: React.FC = () => { | |||
| <TextField | |||
| label={t("username")} | |||
| fullWidth | |||
| variant="filled" | |||
| InputLabelProps={{ | |||
| shrink: !!username, | |||
| sx: { fontSize: "0.9375rem" }, | |||
| }} | |||
| InputProps={{ | |||
| sx: { paddingTop: "8px" }, | |||
| }} | |||
| {...register("username", { | |||
| required: "username required!", | |||
| })} | |||
| error={Boolean(errors.username)} | |||
| /> | |||
| </Grid> | |||
| <Grid item xs={6}> | |||
| <TextField | |||
| label={t("staffNo")} | |||
| fullWidth | |||
| variant="filled" | |||
| InputLabelProps={{ | |||
| shrink: !!staffNo, | |||
| sx: { fontSize: "0.9375rem" }, | |||
| }} | |||
| InputProps={{ | |||
| sx: { paddingTop: "8px" }, | |||
| }} | |||
| {...register("staffNo")} | |||
| error={Boolean(errors.staffNo)} | |||
| helperText={ | |||
| Boolean(errors.staffNo) && errors.staffNo?.message | |||
| ? t(errors.staffNo.message) | |||
| : "" | |||
| } | |||
| /> | |||
| </Grid> | |||
| <Grid item xs={6}> | |||
| <TextField | |||
| label={t("password")} | |||
| fullWidth | |||
| type="password" | |||
| variant="filled" | |||
| InputLabelProps={{ | |||
| shrink: !!password, | |||
| sx: { fontSize: "0.9375rem" }, | |||
| }} | |||
| InputProps={{ | |||
| sx: { paddingTop: "8px" }, | |||
| }} | |||
| {...register("password")} | |||
| // helperText={ | |||
| // Boolean(errors.password) && | |||
| // (errors.password?.message | |||
| // ? t(errors.password.message) | |||
| // : | |||
| // (<> | |||
| // - 8-20 characters | |||
| // <br/> | |||
| // - Uppercase letters | |||
| // <br/> | |||
| // - Lowercase letters | |||
| // <br/> | |||
| // - Numbers | |||
| // <br/> | |||
| // - Symbols | |||
| // </>) | |||
| // ) | |||
| // } | |||
| helperText={ | |||
| Boolean(errors.password) && | |||
| (errors.password?.message | |||
| @@ -71,6 +97,36 @@ const UserDetail: React.FC = () => { | |||
| error={Boolean(errors.password)} | |||
| /> | |||
| </Grid> | |||
| <Grid item xs={6}> | |||
| <TextField | |||
| label={t("Confirm Password")} | |||
| fullWidth | |||
| type="password" | |||
| variant="filled" | |||
| InputLabelProps={{ | |||
| shrink: !!confirmPassword, | |||
| sx: { fontSize: "0.9375rem" }, | |||
| }} | |||
| InputProps={{ | |||
| sx: { paddingTop: "8px" }, | |||
| }} | |||
| {...register("confirmPassword", { | |||
| validate: (value) => { | |||
| if (password && value !== password) { | |||
| return "Passwords do not match"; | |||
| } | |||
| return true; | |||
| }, | |||
| })} | |||
| error={Boolean(errors.confirmPassword)} | |||
| helperText={ | |||
| Boolean(errors.confirmPassword) && | |||
| (errors.confirmPassword?.message | |||
| ? t(errors.confirmPassword.message) | |||
| : "") | |||
| } | |||
| /> | |||
| </Grid> | |||
| {/* <Grid item xs={6}> | |||
| <TextField | |||
| label={t("name")} | |||
| @@ -89,16 +145,3 @@ const UserDetail: React.FC = () => { | |||
| export default UserDetail; | |||
| { | |||
| /* <> | |||
| - 8-20 characters | |||
| <br/> | |||
| - Uppercase letters | |||
| <br/> | |||
| - Lowercase letters | |||
| <br/> | |||
| - Numbers | |||
| <br/> | |||
| - Symbols | |||
| </> */ | |||
| } | |||
| @@ -17,6 +17,7 @@ import Assignment from "@mui/icons-material/Assignment"; | |||
| import Settings from "@mui/icons-material/Settings"; | |||
| import Analytics from "@mui/icons-material/Analytics"; | |||
| import Payments from "@mui/icons-material/Payments"; | |||
| import QrCodeIcon from "@mui/icons-material/QrCode"; | |||
| import { useTranslation } from "react-i18next"; | |||
| import Typography from "@mui/material/Typography"; | |||
| import { usePathname } from "next/navigation"; | |||
| @@ -268,11 +269,11 @@ const NavigationContent: React.FC = () => { | |||
| label: "Demand Forecast Setting", | |||
| path: "/settings/rss", | |||
| }, | |||
| { | |||
| icon: <RequestQuote />, | |||
| label: "Equipment Type", | |||
| path: "/settings/equipmentType", | |||
| }, | |||
| //{ | |||
| // icon: <RequestQuote />, | |||
| // label: "Equipment Type", | |||
| // path: "/settings/equipmentType", | |||
| //}, | |||
| { | |||
| icon: <RequestQuote />, | |||
| label: "Equipment", | |||
| @@ -308,6 +309,11 @@ const NavigationContent: React.FC = () => { | |||
| label: "QC Check Template", | |||
| path: "/settings/user", | |||
| }, | |||
| { | |||
| icon: <QrCodeIcon />, | |||
| label: "QR Code Handle", | |||
| path: "/settings/qrCodeHandle", | |||
| }, | |||
| // { | |||
| // icon: <RequestQuote />, | |||
| // label: "Mail", | |||
| @@ -8,8 +8,11 @@ import EditNote from "@mui/icons-material/EditNote"; | |||
| import DeleteIcon from "@mui/icons-material/Delete"; | |||
| import { useRouter } from "next/navigation"; | |||
| import { deleteDialog, successDialog } from "../Swal/CustomAlerts"; | |||
| import useUploadContext from "../UploadProvider/useUploadContext"; | |||
| import { downloadFile } from "@/app/utils/commonUtil"; | |||
| import { UserResult } from "@/app/api/user"; | |||
| import { deleteUser } from "@/app/api/user/actions"; | |||
| import QrCodeIcon from "@mui/icons-material/QrCode"; | |||
| import UserSearchLoading from "./UserSearchLoading"; | |||
| interface Props { | |||
| @@ -22,7 +25,12 @@ type SearchParamNames = keyof SearchQuery; | |||
| const UserSearch: React.FC<Props> = ({ users }) => { | |||
| const { t } = useTranslation("user"); | |||
| const [filteredUser, setFilteredUser] = useState(users); | |||
| const [pagingController, setPagingController] = useState({ | |||
| pageNum: 1, | |||
| pageSize: 10, | |||
| }); | |||
| const router = useRouter(); | |||
| const { setIsUploading } = useUploadContext(); | |||
| const searchCriteria: Criterion<SearchParamNames>[] = useMemo( | |||
| () => [ | |||
| @@ -31,6 +39,11 @@ const UserSearch: React.FC<Props> = ({ users }) => { | |||
| paramName: "username", | |||
| type: "text", | |||
| }, | |||
| { | |||
| label: t("staffNo"), | |||
| paramName: "staffNo", | |||
| type: "text", | |||
| }, | |||
| ], | |||
| [t], | |||
| ); | |||
| @@ -43,6 +56,20 @@ const UserSearch: React.FC<Props> = ({ users }) => { | |||
| [router, t], | |||
| ); | |||
| {/* | |||
| const printQrcode = useCallback(async (lotLineId: number) => { | |||
| setIsUploading(true); | |||
| // const postData = { stockInLineIds: [42,43,44] }; | |||
| const postData: LotLineToQrcode = { | |||
| inventoryLotLineId: lotLineId | |||
| } | |||
| const response = await fetchQrCodeByLotLineId(postData); | |||
| if (response) { | |||
| downloadFile(new Uint8Array(response.blobValue), response.filename!); | |||
| } | |||
| setIsUploading(false); | |||
| }, [setIsUploading]); | |||
| */} | |||
| const onDeleteClick = useCallback((users: UserResult) => { | |||
| deleteDialog(async () => { | |||
| await deleteUser(users.id); | |||
| @@ -50,6 +77,9 @@ const UserSearch: React.FC<Props> = ({ users }) => { | |||
| }, t); | |||
| }, []); | |||
| const columns = useMemo<Column<UserResult>[]>( | |||
| () => [ | |||
| { | |||
| @@ -59,6 +89,7 @@ const UserSearch: React.FC<Props> = ({ users }) => { | |||
| buttonIcon: <EditNote />, | |||
| }, | |||
| { name: "username", label: t("Username") }, | |||
| { name: "staffNo", label: t("staffNo") }, | |||
| { | |||
| name: "action", | |||
| label: t("Delete"), | |||
| @@ -75,20 +106,23 @@ const UserSearch: React.FC<Props> = ({ users }) => { | |||
| <SearchBox | |||
| criteria={searchCriteria} | |||
| onSearch={(query) => { | |||
| // setFilteredUser( | |||
| // users.filter( | |||
| // (t) => | |||
| // t.name.toLowerCase().includes(query.name.toLowerCase()) && | |||
| // t.code.toLowerCase().includes(query.code.toLowerCase()) && | |||
| // t.description.toLowerCase().includes(query.description.toLowerCase()) | |||
| // ) | |||
| // ) | |||
| setFilteredUser( | |||
| users.filter((user) => { | |||
| const usernameMatch = !query.username || | |||
| user.username.toLowerCase().includes(query.username.toLowerCase()); | |||
| const staffNoMatch = !query.staffNo || | |||
| String(user.staffNo).includes(String(query.staffNo)); | |||
| return usernameMatch && staffNoMatch; | |||
| }) | |||
| ); | |||
| setPagingController({ pageNum: 1, pageSize: pagingController.pageSize }); | |||
| }} | |||
| /> | |||
| <SearchResults<UserResult> | |||
| items={filteredUser} | |||
| columns={columns} | |||
| pagingController={{ pageNum: 1, pageSize: 10 }} | |||
| pagingController={pagingController} | |||
| setPagingController={setPagingController} | |||
| /> | |||
| </> | |||
| ); | |||
| @@ -1 +1,2 @@ | |||
| export { default } from "./UserSearchWrapper"; | |||
| @@ -0,0 +1,3 @@ | |||
| export { default } from "./qrCodeHandleSearchWrapper"; | |||
| export { default as QrCodeHandleSearch } from "./qrCodeHandleSearch"; | |||
| export { default as QrCodeHandleEquipmentSearch } from "./qrCodeHandleEquipmentSearch"; | |||
| @@ -0,0 +1,156 @@ | |||
| "use client"; | |||
| import { useCallback, useEffect, useMemo, useState } from "react"; | |||
| import SearchBox, { Criterion } from "../SearchBox"; | |||
| import { EquipmentResult } from "@/app/api/settings/equipment"; | |||
| import { useTranslation } from "react-i18next"; | |||
| import SearchResults, { Column } from "../SearchResults"; | |||
| import { EditNote } from "@mui/icons-material"; | |||
| import { useRouter } from "next/navigation"; | |||
| import { GridDeleteIcon } from "@mui/x-data-grid"; | |||
| import axiosInstance from "@/app/(main)/axios/axiosInstance"; | |||
| import { NEXT_PUBLIC_API_URL } from "@/config/api"; | |||
| type Props = { | |||
| equipments: EquipmentResult[]; | |||
| }; | |||
| type SearchQuery = Partial<Omit<EquipmentResult, "id">>; | |||
| type SearchParamNames = keyof SearchQuery; | |||
| const QrCodeHandleEquipmentSearch: React.FC<Props> = ({ equipments }) => { | |||
| const [filteredEquipments, setFilteredEquipments] = | |||
| useState<EquipmentResult[]>([]); | |||
| const { t } = useTranslation("common"); | |||
| const router = useRouter(); | |||
| const [filterObj, setFilterObj] = useState({}); | |||
| const [pagingController, setPagingController] = useState({ | |||
| pageNum: 1, | |||
| pageSize: 10, | |||
| }); | |||
| const [totalCount, setTotalCount] = useState(0); | |||
| const searchCriteria: Criterion<SearchParamNames>[] = useMemo(() => { | |||
| const searchCriteria: Criterion<SearchParamNames>[] = [ | |||
| { label: t("Code"), paramName: "code", type: "text" }, | |||
| { label: t("Description"), paramName: "description", type: "text" }, | |||
| ]; | |||
| return searchCriteria; | |||
| }, [t, equipments]); | |||
| const onDetailClick = useCallback( | |||
| (equipment: EquipmentResult) => { | |||
| router.push(`/settings/equipment/edit?id=${equipment.id}`); | |||
| }, | |||
| [router], | |||
| ); | |||
| const onDeleteClick = useCallback( | |||
| (equipment: EquipmentResult) => {}, | |||
| [router], | |||
| ); | |||
| const columns = useMemo<Column<EquipmentResult>[]>( | |||
| () => [ | |||
| { | |||
| name: "id", | |||
| label: t("Details"), | |||
| onClick: onDetailClick, | |||
| buttonIcon: <EditNote />, | |||
| }, | |||
| { | |||
| name: "code", | |||
| label: t("Code"), | |||
| }, | |||
| { | |||
| name: "equipmentTypeId", | |||
| label: t("Equipment Type"), | |||
| sx: {minWidth: 180}, | |||
| }, | |||
| { | |||
| name: "description", | |||
| label: t("Description"), | |||
| }, | |||
| { | |||
| name: "action", | |||
| label: t(""), | |||
| buttonIcon: <GridDeleteIcon />, | |||
| onClick: onDeleteClick, | |||
| }, | |||
| ], | |||
| [filteredEquipments], | |||
| ); | |||
| interface ApiResponse<T> { | |||
| records: T[]; | |||
| total: number; | |||
| } | |||
| const refetchData = useCallback( | |||
| async (filterObj: SearchQuery, pageNum: number, pageSize: number) => { | |||
| const authHeader = axiosInstance.defaults.headers["Authorization"]; | |||
| if (!authHeader) { | |||
| setTimeout(() => { | |||
| refetchData(filterObj, pageNum, pageSize); | |||
| }, 10); | |||
| return; | |||
| } | |||
| const params = { | |||
| pageNum: pageNum, | |||
| pageSize: pageSize, | |||
| ...filterObj, | |||
| }; | |||
| try { | |||
| const response = await axiosInstance.get<ApiResponse<EquipmentResult>>( | |||
| `${NEXT_PUBLIC_API_URL}/Equipment/getRecordByPage`, | |||
| { params }, | |||
| ); | |||
| console.log(response); | |||
| if (response.status == 200) { | |||
| setFilteredEquipments(response.data.records); | |||
| setTotalCount(response.data.total); | |||
| return response; | |||
| } else { | |||
| throw "400"; | |||
| } | |||
| } catch (error) { | |||
| console.error("Error fetching equipment types:", error); | |||
| throw error; | |||
| } | |||
| }, | |||
| [], | |||
| ); | |||
| useEffect(() => { | |||
| refetchData(filterObj, pagingController.pageNum, pagingController.pageSize); | |||
| }, [filterObj, pagingController.pageNum, pagingController.pageSize]); | |||
| const onReset = useCallback(() => { | |||
| setFilterObj({}); | |||
| setPagingController({ pageNum: 1, pageSize: 10 }); | |||
| }, []); | |||
| return ( | |||
| <> | |||
| <SearchBox | |||
| criteria={searchCriteria} | |||
| onSearch={(query) => { | |||
| setFilterObj({ | |||
| ...query, | |||
| }); | |||
| }} | |||
| onReset={onReset} | |||
| /> | |||
| <SearchResults<EquipmentResult> | |||
| items={filteredEquipments} | |||
| columns={columns} | |||
| setPagingController={setPagingController} | |||
| pagingController={pagingController} | |||
| totalCount={totalCount} | |||
| isAutoPaging={false} | |||
| /> | |||
| </> | |||
| ); | |||
| }; | |||
| export default QrCodeHandleEquipmentSearch; | |||
| @@ -0,0 +1,17 @@ | |||
| import React from "react"; | |||
| import QrCodeHandleEquipmentSearch from "./qrCodeHandleEquipmentSearch"; | |||
| import EquipmentSearchLoading from "../EquipmentSearch/EquipmentSearchLoading"; | |||
| import { fetchAllEquipments } from "@/app/api/settings/equipment"; | |||
| interface SubComponents { | |||
| Loading: typeof EquipmentSearchLoading; | |||
| } | |||
| const QrCodeHandleEquipmentSearchWrapper: React.FC & SubComponents = async () => { | |||
| const equipments = await fetchAllEquipments(); | |||
| return <QrCodeHandleEquipmentSearch equipments={equipments} />; | |||
| }; | |||
| QrCodeHandleEquipmentSearchWrapper.Loading = EquipmentSearchLoading; | |||
| export default QrCodeHandleEquipmentSearchWrapper; | |||
| @@ -0,0 +1,410 @@ | |||
| "use client"; | |||
| import SearchBox, { Criterion } from "../SearchBox"; | |||
| import { useCallback, useMemo, useState, useEffect } from "react"; | |||
| import { useTranslation } from "react-i18next"; | |||
| import SearchResults, { Column } from "../SearchResults"; | |||
| import DeleteIcon from "@mui/icons-material/Delete"; | |||
| import { useRouter } from "next/navigation"; | |||
| import { deleteDialog, successDialog } from "../Swal/CustomAlerts"; | |||
| import useUploadContext from "../UploadProvider/useUploadContext"; | |||
| import { downloadFile } from "@/app/utils/commonUtil"; | |||
| import { UserResult } from "@/app/api/user"; | |||
| import { deleteUser } from "@/app/api/user/actions"; | |||
| import QrCodeIcon from "@mui/icons-material/QrCode"; | |||
| import { exportUserQrCode } from "@/app/api/user/client"; | |||
| import { Checkbox, Box, Button, TextField, Stack, Autocomplete, Modal, Card, IconButton } from "@mui/material"; | |||
| import DownloadIcon from "@mui/icons-material/Download"; | |||
| import PrintIcon from "@mui/icons-material/Print"; | |||
| import CloseIcon from "@mui/icons-material/Close"; | |||
| import { PrinterCombo } from "@/app/api/settings/printer"; | |||
| interface Props { | |||
| users: UserResult[]; | |||
| printerCombo: PrinterCombo[]; | |||
| } | |||
| type SearchQuery = Partial<Omit<UserResult, "id">>; | |||
| type SearchParamNames = keyof SearchQuery; | |||
| const QrCodeHandleSearch: React.FC<Props> = ({ users, printerCombo }) => { | |||
| const { t } = useTranslation("user"); | |||
| const [filteredUser, setFilteredUser] = useState(users); | |||
| const router = useRouter(); | |||
| const { setIsUploading } = useUploadContext(); | |||
| const [pagingController, setPagingController] = useState({ | |||
| pageNum: 1, | |||
| pageSize: 10, | |||
| }); | |||
| const [checkboxIds, setCheckboxIds] = useState<number[]>([]); | |||
| const [selectAll, setSelectAll] = useState(false); | |||
| const [printQty, setPrintQty] = useState(1); | |||
| // Preview modal state | |||
| const [previewOpen, setPreviewOpen] = useState(false); | |||
| const [previewUrl, setPreviewUrl] = useState<string | null>(null); | |||
| const filteredPrinters = useMemo(() => { | |||
| const allowedPrinterNames = [ | |||
| "A4印機 測試用 Local", | |||
| "A4印機 測試用 Server", | |||
| "A4 2F Office", | |||
| "A4 2F 雪庫", | |||
| ]; | |||
| return printerCombo.filter((printer) => { | |||
| const printerName = printer.name || printer.label || printer.code || ""; | |||
| return allowedPrinterNames.includes(printerName); | |||
| }); | |||
| }, [printerCombo]); | |||
| const [selectedPrinter, setSelectedPrinter] = useState<PrinterCombo | undefined>( | |||
| filteredPrinters.length > 0 ? filteredPrinters[0] : undefined | |||
| ); | |||
| useEffect(() => { | |||
| if (!selectedPrinter || !filteredPrinters.find(p => p.id === selectedPrinter.id)) { | |||
| setSelectedPrinter(filteredPrinters.length > 0 ? filteredPrinters[0] : undefined); | |||
| } | |||
| }, [filteredPrinters, selectedPrinter]); | |||
| const searchCriteria: Criterion<SearchParamNames>[] = useMemo( | |||
| () => [ | |||
| { | |||
| label: t("Username"), | |||
| paramName: "username", | |||
| type: "text", | |||
| }, | |||
| { | |||
| label: t("staffNo"), | |||
| paramName: "staffNo", | |||
| type: "text", | |||
| }, | |||
| ], | |||
| [t], | |||
| ); | |||
| const onDeleteClick = useCallback((user: UserResult) => { | |||
| deleteDialog(async () => { | |||
| await deleteUser(user.id); | |||
| successDialog(t("Delete Success"), t); | |||
| }, t); | |||
| }, [t]); | |||
| const handleSelectUser = useCallback((userId: number, checked: boolean) => { | |||
| if (checked) { | |||
| setCheckboxIds(prev => [...prev, userId]); | |||
| } else { | |||
| setCheckboxIds(prev => prev.filter(id => id !== userId)); | |||
| setSelectAll(false); | |||
| } | |||
| }, []); | |||
| const handleSelectAll = useCallback((checked: boolean) => { | |||
| if (checked) { | |||
| setCheckboxIds(filteredUser.map(user => user.id)); | |||
| setSelectAll(true); | |||
| } else { | |||
| setCheckboxIds([]); | |||
| setSelectAll(false); | |||
| } | |||
| }, [filteredUser]); | |||
| const showPdfPreview = useCallback(async (userIds: number[]) => { | |||
| if (userIds.length === 0) { | |||
| return; | |||
| } | |||
| try { | |||
| setIsUploading(true); | |||
| const response = await exportUserQrCode(userIds); | |||
| const blob = new Blob([new Uint8Array(response.blobValue)], { type: "application/pdf" }); | |||
| const url = URL.createObjectURL(blob); | |||
| setPreviewUrl(`${url}#toolbar=0`); | |||
| setPreviewOpen(true); | |||
| } catch (error) { | |||
| console.error("Error exporting QR code:", error); | |||
| } finally { | |||
| setIsUploading(false); | |||
| } | |||
| }, [setIsUploading]); | |||
| const handleClosePreview = useCallback(() => { | |||
| setPreviewOpen(false); | |||
| if (previewUrl) { | |||
| URL.revokeObjectURL(previewUrl); | |||
| setPreviewUrl(null); | |||
| } | |||
| }, [previewUrl]); | |||
| const handleDownloadQrCode = useCallback(async (userIds: number[]) => { | |||
| if (userIds.length === 0) { | |||
| return; | |||
| } | |||
| try { | |||
| setIsUploading(true); | |||
| const response = await exportUserQrCode(userIds); | |||
| downloadFile(response.blobValue, response.filename); | |||
| successDialog(t("QR Code exported successfully"), t); | |||
| } catch (error) { | |||
| console.error("Error exporting QR code:", error); | |||
| } finally { | |||
| setIsUploading(false); | |||
| } | |||
| }, [setIsUploading, t]); | |||
| const handlePrint = useCallback(async () => { | |||
| if (checkboxIds.length === 0) { | |||
| return; | |||
| } | |||
| try { | |||
| setIsUploading(true); | |||
| const response = await exportUserQrCode(checkboxIds); | |||
| const blob = new Blob([new Uint8Array(response.blobValue)], { type: "application/pdf" }); | |||
| const url = URL.createObjectURL(blob); | |||
| const printWindow = window.open(url, '_blank'); | |||
| if (printWindow) { | |||
| printWindow.onload = () => { | |||
| for (let i = 0; i < printQty; i++) { | |||
| setTimeout(() => { | |||
| printWindow.print(); | |||
| }, i * 500); | |||
| } | |||
| }; | |||
| } | |||
| setTimeout(() => { | |||
| URL.revokeObjectURL(url); | |||
| }, 1000); | |||
| } catch (error) { | |||
| console.error("Error printing QR code:", error); | |||
| } finally { | |||
| setIsUploading(false); | |||
| } | |||
| }, [checkboxIds, printQty, setIsUploading]); | |||
| const handleViewSelectedQrCodes = useCallback(async () => { | |||
| await handleDownloadQrCode(checkboxIds); | |||
| }, [checkboxIds, handleDownloadQrCode]); | |||
| const columns = useMemo<Column<UserResult>[]>( | |||
| () => [ | |||
| { | |||
| name: "id", | |||
| label: "", | |||
| renderCell: (params) => ( | |||
| <Checkbox | |||
| checked={checkboxIds.includes(params.id)} | |||
| onChange={(e) => handleSelectUser(params.id, e.target.checked)} | |||
| onClick={(e) => e.stopPropagation()} | |||
| /> | |||
| ), | |||
| }, | |||
| { | |||
| name: "username", | |||
| label: t("Username"), | |||
| align: "left", | |||
| headerAlign: "left", | |||
| }, | |||
| { | |||
| name: "staffNo", | |||
| label: t("staffNo"), | |||
| align: "left", | |||
| headerAlign: "left", | |||
| }, | |||
| { | |||
| name: "staffNo", | |||
| label: t("qrcode"), | |||
| align: "center", | |||
| headerAlign: "center", | |||
| onClick: async (user: UserResult) => { | |||
| await showPdfPreview([user.id]); | |||
| }, | |||
| buttonIcon: <QrCodeIcon />, | |||
| }, | |||
| ], | |||
| [t, checkboxIds, handleSelectUser, showPdfPreview], | |||
| ); | |||
| const onReset = useCallback(() => { | |||
| setFilteredUser(users); | |||
| }, [users]); | |||
| return ( | |||
| <> | |||
| <SearchBox | |||
| criteria={searchCriteria} | |||
| onSearch={(query) => { | |||
| setFilteredUser( | |||
| users.filter((user) => { | |||
| const usernameMatch = !query.username || | |||
| user.username?.toLowerCase().includes(query.username?.toLowerCase() || ""); | |||
| const staffNoMatch = !query.staffNo || | |||
| user.staffNo?.toString().includes(query.staffNo?.toString() || ""); | |||
| return usernameMatch && staffNoMatch; | |||
| }) | |||
| ); | |||
| setPagingController({ pageNum: 1, pageSize: 10 }); | |||
| }} | |||
| onReset={onReset} | |||
| /> | |||
| <SearchResults<UserResult> | |||
| items={filteredUser} | |||
| columns={columns} | |||
| pagingController={pagingController} | |||
| setPagingController={setPagingController} | |||
| totalCount={filteredUser.length} | |||
| isAutoPaging={true} | |||
| /> | |||
| {/* Add select all and view selected buttons */} | |||
| <Box sx={{ mb: 2, display: 'flex', alignItems: 'center', gap: 2 }}> | |||
| <Button | |||
| variant="outlined" | |||
| onClick={() => handleSelectAll(!selectAll)} | |||
| startIcon={<Checkbox checked={selectAll} />} | |||
| > | |||
| 選擇全部用戶 ({checkboxIds.length} / {filteredUser.length}) | |||
| </Button> | |||
| <Button | |||
| variant="contained" | |||
| onClick={handleViewSelectedQrCodes} | |||
| disabled={checkboxIds.length === 0} | |||
| color="primary" | |||
| > | |||
| 查看已選擇用戶二維碼 ({checkboxIds.length}) | |||
| </Button> | |||
| </Box> | |||
| {/* Print and Download Section */} | |||
| <Box | |||
| sx={{ | |||
| p: 2, | |||
| borderTop: 1, | |||
| borderColor: 'divider', | |||
| bgcolor: 'background.paper', | |||
| mt: 2, | |||
| }} | |||
| > | |||
| <Stack direction="row" justifyContent="flex-end" alignItems="center" gap={2}> | |||
| <Autocomplete<PrinterCombo> | |||
| options={filteredPrinters} | |||
| value={selectedPrinter ?? null} | |||
| onChange={(event, value) => { | |||
| setSelectedPrinter(value ?? undefined); | |||
| }} | |||
| getOptionLabel={(option) => option.name || option.label || option.code || String(option.id)} | |||
| renderInput={(params) => ( | |||
| <TextField | |||
| {...params} | |||
| variant="outlined" | |||
| label="列印機" | |||
| sx={{ width: 300 }} | |||
| /> | |||
| )} | |||
| /> | |||
| <TextField | |||
| variant="outlined" | |||
| label="列印數量" | |||
| type="number" | |||
| value={printQty} | |||
| onChange={(e) => { | |||
| const value = parseInt(e.target.value) || 1; | |||
| setPrintQty(Math.max(1, value)); | |||
| }} | |||
| inputProps={{ min: 1 }} | |||
| sx={{ width: 120 }} | |||
| /> | |||
| <Button | |||
| variant="contained" | |||
| startIcon={<PrintIcon />} | |||
| onClick={handlePrint} | |||
| disabled={checkboxIds.length === 0 || filteredPrinters.length === 0} | |||
| color="primary" | |||
| > | |||
| 列印 | |||
| </Button> | |||
| <Button | |||
| variant="contained" | |||
| startIcon={<DownloadIcon />} | |||
| onClick={handleViewSelectedQrCodes} | |||
| disabled={checkboxIds.length === 0} | |||
| color="primary" | |||
| > | |||
| 下載QR碼 | |||
| </Button> | |||
| </Stack> | |||
| </Box> | |||
| {/* PDF Preview Modal - Simple preview only */} | |||
| <Modal | |||
| open={previewOpen} | |||
| onClose={handleClosePreview} | |||
| sx={{ | |||
| display: 'flex', | |||
| alignItems: 'center', | |||
| justifyContent: 'center', | |||
| }} | |||
| > | |||
| <Card | |||
| sx={{ | |||
| position: 'relative', | |||
| width: '90%', | |||
| maxWidth: '900px', | |||
| maxHeight: '90vh', | |||
| display: 'flex', | |||
| flexDirection: 'column', | |||
| outline: 'none', | |||
| }} | |||
| > | |||
| {/* Header with close button only */} | |||
| <Box | |||
| sx={{ | |||
| display: 'flex', | |||
| justifyContent: 'flex-end', | |||
| alignItems: 'center', | |||
| p: 2, | |||
| borderBottom: 1, | |||
| borderColor: 'divider', | |||
| }} | |||
| > | |||
| <IconButton | |||
| onClick={handleClosePreview} | |||
| > | |||
| <CloseIcon /> | |||
| </IconButton> | |||
| </Box> | |||
| {/* PDF Preview */} | |||
| <Box | |||
| sx={{ | |||
| flex: 1, | |||
| overflow: 'auto', | |||
| p: 2, | |||
| }} | |||
| > | |||
| {previewUrl && ( | |||
| <iframe | |||
| src={previewUrl} | |||
| width="100%" | |||
| height="600px" | |||
| style={{ | |||
| border: 'none', | |||
| }} | |||
| title="PDF Preview" | |||
| /> | |||
| )} | |||
| </Box> | |||
| </Card> | |||
| </Modal> | |||
| </> | |||
| ); | |||
| }; | |||
| export default QrCodeHandleSearch; | |||
| @@ -0,0 +1,40 @@ | |||
| import Card from "@mui/material/Card"; | |||
| import CardContent from "@mui/material/CardContent"; | |||
| import Skeleton from "@mui/material/Skeleton"; | |||
| import Stack from "@mui/material/Stack"; | |||
| import React from "react"; | |||
| // Can make this nicer | |||
| export const qrCodeHandleSearchLoading: React.FC = () => { | |||
| return ( | |||
| <> | |||
| <Card> | |||
| <CardContent> | |||
| <Stack spacing={2}> | |||
| <Skeleton variant="rounded" height={60} /> | |||
| <Skeleton variant="rounded" height={60} /> | |||
| <Skeleton variant="rounded" height={60} /> | |||
| <Skeleton | |||
| variant="rounded" | |||
| height={50} | |||
| width={100} | |||
| sx={{ alignSelf: "flex-end" }} | |||
| /> | |||
| </Stack> | |||
| </CardContent> | |||
| </Card> | |||
| <Card> | |||
| <CardContent> | |||
| <Stack spacing={2}> | |||
| <Skeleton variant="rounded" height={40} /> | |||
| <Skeleton variant="rounded" height={40} /> | |||
| <Skeleton variant="rounded" height={40} /> | |||
| <Skeleton variant="rounded" height={40} /> | |||
| </Stack> | |||
| </CardContent> | |||
| </Card> | |||
| </> | |||
| ); | |||
| }; | |||
| export default qrCodeHandleSearchLoading; | |||
| @@ -0,0 +1,21 @@ | |||
| import React from "react"; | |||
| import QrCodeHandleSearch from "./qrCodeHandleSearch"; | |||
| import QrCodeHandleSearchLoading from "./qrCodeHandleSearchLoading"; | |||
| import { fetchUser } from "@/app/api/user"; | |||
| import { fetchPrinterCombo } from "@/app/api/settings/printer"; | |||
| interface SubComponents { | |||
| Loading: typeof QrCodeHandleSearchLoading; | |||
| } | |||
| const QrCodeHandleSearchWrapper: React.FC & SubComponents = async () => { | |||
| const [users, printerCombo] = await Promise.all([ | |||
| fetchUser(), | |||
| fetchPrinterCombo(), | |||
| ]); | |||
| return <QrCodeHandleSearch users={users} printerCombo={printerCombo} />; | |||
| }; | |||
| QrCodeHandleSearchWrapper.Loading = QrCodeHandleSearchLoading; | |||
| export default QrCodeHandleSearchWrapper; | |||
| @@ -0,0 +1,66 @@ | |||
| "use client"; | |||
| import { useState, ReactNode } from "react"; | |||
| import { Box, Tabs, Tab } from "@mui/material"; | |||
| import { useTranslation } from "react-i18next"; | |||
| interface TabPanelProps { | |||
| children?: ReactNode; | |||
| index: number; | |||
| value: number; | |||
| } | |||
| function TabPanel(props: TabPanelProps) { | |||
| const { children, value, index, ...other } = props; | |||
| return ( | |||
| <div | |||
| role="tabpanel" | |||
| hidden={value !== index} | |||
| id={`qr-code-handle-tabpanel-${index}`} | |||
| aria-labelledby={`qr-code-handle-tab-${index}`} | |||
| {...other} | |||
| > | |||
| {value === index && <Box sx={{ py: 3 }}>{children}</Box>} | |||
| </div> | |||
| ); | |||
| } | |||
| interface QrCodeHandleTabsProps { | |||
| userTabContent: ReactNode; | |||
| equipmentTabContent: ReactNode; | |||
| } | |||
| const QrCodeHandleTabs: React.FC<QrCodeHandleTabsProps> = ({ | |||
| userTabContent, | |||
| equipmentTabContent, | |||
| }) => { | |||
| const { t } = useTranslation("common"); | |||
| const { t: tUser } = useTranslation("user"); | |||
| const [currentTab, setCurrentTab] = useState(0); | |||
| const handleTabChange = (event: React.SyntheticEvent, newValue: number) => { | |||
| setCurrentTab(newValue); | |||
| }; | |||
| return ( | |||
| <Box sx={{ width: "100%" }}> | |||
| <Box sx={{ borderBottom: 1, borderColor: "divider" }}> | |||
| <Tabs value={currentTab} onChange={handleTabChange}> | |||
| <Tab label={tUser("User")} /> | |||
| <Tab label={t("Equipment")} /> | |||
| </Tabs> | |||
| </Box> | |||
| <TabPanel value={currentTab} index={0}> | |||
| {userTabContent} | |||
| </TabPanel> | |||
| <TabPanel value={currentTab} index={1}> | |||
| {equipmentTabContent} | |||
| </TabPanel> | |||
| </Box> | |||
| ); | |||
| }; | |||
| export default QrCodeHandleTabs; | |||
| @@ -0,0 +1,3 @@ | |||
| @@ -0,0 +1,3 @@ | |||