phx-react
Version:
PHX REACT
323 lines • 18.8 kB
JavaScript
import { PHXAxiosInstance, PHXBanner, PHXCard, PHXClientQueryV3, PHXDatePicker, PHXFuncGetLoggedInfo, PHXModal, PHXSearchResultListV3, PHXSelect, PHXSelectBox, PHXSkeleton, PHXTextarea, } from '../../../../..';
import { useEffect, useState } from 'react';
import { useForm } from 'react-hook-form';
import BookBorrowInfo from './book-borrow-info';
import { ACTION_LIBRARY_CREATE_TICKET, BORROWED_TICKET_CODE, CODE_BORROW_USER, DEFAULT_TOTAL_BORROW_DAY, IN_BOOKSHELF_STATE_CODE, IN_WAREHOUSE_STATE_CODE, KEY_GIAO_VIEN_CODE, KEY_HOC_SINH_CODE, KEY_STUDYING_STUDENT_STATUS, STUDENT_BORROW_INDIVIDUAL_CODE, TOTAL_BORROW_DAY_STUDENT, } from '../constants';
import useBookState from '../library-return-ticket/use-book-state';
import { FORM_TYPE, TIEU_HOC_CODE } from '../../../constant';
import { formatDateMMDDYY, getDateOffsetByDays, getProfile, getRoleName, sortClassroomByName, triggerMessage, } from '../helper';
import { getDataSelectQuery, searchUserBorrow } from '../query';
import React from 'react';
export default function ModalCreateBorrowTicket({ currentSchoolYearId, educationalCodes, onHide, show, }) {
var _a, _b;
const { listBookState } = useBookState();
const [warehouseId, setWarehouseId] = useState(null);
const studentCondition = educationalCodes.includes(TIEU_HOC_CODE)
? `grade: { educational_level: { code: { _eq: ${TIEU_HOC_CODE} } } }`
: `grade: { educational_level: { code: { _neq: ${TIEU_HOC_CODE} } } }`;
const defaultFilterProfile = `
profile_student: {
${studentCondition}
student_status: { _eq: ${KEY_STUDYING_STUDENT_STATUS} }
}
`;
const [filterProfile, setFilterProfile] = useState(defaultFilterProfile);
const { formState: { errors }, handleSubmit, register, reset, setValue, watch, } = useForm();
const staffAndTeacherLevel = `[${educationalCodes.join(',')}]`;
const [defaultExpectReturnDate, setDefaultExpectReturnDate] = useState(null);
const userInfo = PHXFuncGetLoggedInfo();
const [loading, setLoading] = useState(true);
const [submitLoading, setSubmitLoading] = useState(false);
const [userId, setUserId] = useState(null);
const [bannerDescription, setBannerDescription] = useState('');
const [bookBorrowerCode, setBookBorrowerCode] = useState(CODE_BORROW_USER.HS);
const [listBook, setListBook] = useState([]);
const [dataSelect, setDataSelect] = useState({
bookBorrower: [],
classrooms: [],
ticketStates: [],
prefixQrCode: '',
});
const disabledSubmit = listBook.length === 0 || !userId || !watch('user_id') || !watch('expect_return_date');
const handleRenderSelectSearchResultList = (data) => {
var _a, _b;
const classroom = (_b = (_a = data === null || data === void 0 ? void 0 : data.classroom_students) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.classroom;
const profile = getProfile(data);
const roleName = getRoleName(data === null || data === void 0 ? void 0 : data.user_roles);
return `${data === null || data === void 0 ? void 0 : data.full_name} - ${profile === null || profile === void 0 ? void 0 : profile.user_code} - ${roleName}${classroom && !classroom.name ? ' - ' + (classroom === null || classroom === void 0 ? void 0 : classroom.grade.name) : ''}${classroom ? ' - ' + classroom.name : ''}`;
};
const defaultBookBorrower = (_a = dataSelect.bookBorrower.find((item) => item.code === CODE_BORROW_USER.HS && item.default)) === null || _a === void 0 ? void 0 : _a.id;
const getBorrowerRoleCode = (user) => {
var _a, _b, _c;
const { profile_staff, profile_student, profile_teacher } = user;
if (profile_staff === null || profile_staff === void 0 ? void 0 : profile_staff.user_code) {
return CODE_BORROW_USER.NV;
}
if (profile_student === null || profile_student === void 0 ? void 0 : profile_student.user_code) {
return KEY_HOC_SINH_CODE;
}
if (profile_teacher === null || profile_teacher === void 0 ? void 0 : profile_teacher.user_code) {
return KEY_GIAO_VIEN_CODE;
}
return (_c = (_b = (_a = user === null || user === void 0 ? void 0 : user.user_roles) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.role) === null || _c === void 0 ? void 0 : _c.role_code;
};
const handleChangeBookBorrower = (user) => {
var _a, _b, _c, _d;
const { library_borrow_tickets: tickets } = user;
if ((tickets === null || tickets === void 0 ? void 0 : tickets.length) > 0) {
setBannerDescription(`Người dùng này hiện có ${tickets === null || tickets === void 0 ? void 0 : tickets.length} phiếu mượn sách`);
}
else {
setBannerDescription('');
}
const roleCode = getBorrowerRoleCode(user);
if (roleCode === KEY_HOC_SINH_CODE) {
const expectReturnDate = getDateOffsetByDays(TOTAL_BORROW_DAY_STUDENT, 'datePicker');
// Lưu code của chủ thể mượn sách
const borrowerCode = ((_b = (_a = dataSelect.bookBorrower) === null || _a === void 0 ? void 0 : _a.find((item) => item.code === STUDENT_BORROW_INDIVIDUAL_CODE)) === null || _b === void 0 ? void 0 : _b.code) ||
CODE_BORROW_USER.HS;
setBookBorrowerCode(borrowerCode);
setValue('expect_return_date', expectReturnDate);
setDefaultExpectReturnDate(expectReturnDate);
return;
}
const expectReturnDate = getDateOffsetByDays(DEFAULT_TOTAL_BORROW_DAY, 'datePicker');
const book_borrower_id = Number(watch('book_borrower_id'));
const borrowerCode = ((_d = (_c = dataSelect.bookBorrower) === null || _c === void 0 ? void 0 : _c.find((item) => item.id === book_borrower_id)) === null || _d === void 0 ? void 0 : _d.code) ||
(roleCode === CODE_BORROW_USER.GV ? CODE_BORROW_USER.GV : CODE_BORROW_USER.NV);
setBookBorrowerCode(borrowerCode);
setValue('expect_return_date', expectReturnDate);
setDefaultExpectReturnDate(expectReturnDate);
};
const getData = async () => {
var _a, _b, _c;
try {
const { data: { classroom, library_book_borrower: bookBorrowerData, library_warehouse_educational_level, ticketStates }, } = await PHXClientQueryV3({
query: getDataSelectQuery(educationalCodes[0]),
variables: {
school_id: userInfo === null || userInfo === void 0 ? void 0 : userInfo.school_id,
school_year_id: currentSchoolYearId,
educationalLevelCode: educationalCodes[0],
},
});
setDataSelect({
bookBorrower: bookBorrowerData,
classrooms: sortClassroomByName(classroom).map((item) => ({
id: item.id,
value: item.name,
})),
ticketStates,
prefixQrCode: (_b = (_a = library_warehouse_educational_level === null || library_warehouse_educational_level === void 0 ? void 0 : library_warehouse_educational_level[0]) === null || _a === void 0 ? void 0 : _a.library_warehouse) === null || _b === void 0 ? void 0 : _b.qr_code_prefix,
});
setWarehouseId((_c = library_warehouse_educational_level === null || library_warehouse_educational_level === void 0 ? void 0 : library_warehouse_educational_level[0]) === null || _c === void 0 ? void 0 : _c.warehouse_id);
}
catch (e) {
console.log(e);
}
finally {
setLoading(false);
}
};
const handleProfile = (code) => {
if (code === CODE_BORROW_USER.HS || code === CODE_BORROW_USER.HS_CLASSROOM) {
return `
profile_student: {
${studentCondition}
student_status: { _eq: ${KEY_STUDYING_STUDENT_STATUS} }
}
`;
}
if (code === CODE_BORROW_USER.GV || code === CODE_BORROW_USER.GV_CLASSROOM) {
return `
profile_teacher: {
educational_level_group: {
educational_level_map_groups: {
educational_level: {
code: { _in: ${staffAndTeacherLevel} }
}
}
}
}
`;
}
if (code === CODE_BORROW_USER.NV) {
return `
profile_staff: {
educational_level_group: {
educational_level_map_groups: {
educational_level: {
code: { _in: ${staffAndTeacherLevel} }
}
}
}
}
`;
}
return ``;
};
const handleBookBorrow = () => {
const dataInsert = [];
const school_id = userInfo === null || userInfo === void 0 ? void 0 : userInfo.school_id;
listBook.forEach((book) => {
dataInsert.push({
created_at: 'now',
school_id,
dang_ki_ca_biet_id: book.id,
});
});
return dataInsert;
};
const getPreStateBook = () => {
const result = [];
listBook.forEach((book) => {
result.push({
dang_ki_ca_biet_id: book.id,
stateId: book.stateId,
});
});
return result;
};
const onSubmit = async (data) => {
var _a, _b, _c;
setSubmitLoading(true);
try {
const bookBorrowInsert = handleBookBorrow();
const bookWithPreState = getPreStateBook();
const inWareHouseBookId = [];
const inBookshelfBookId = [];
bookWithPreState === null || bookWithPreState === void 0 ? void 0 : bookWithPreState.forEach((item) => {
var _a, _b;
const { dang_ki_ca_biet_id, stateId } = item;
if (stateId === ((_a = listBookState.find((state) => state.code === IN_BOOKSHELF_STATE_CODE)) === null || _a === void 0 ? void 0 : _a.id)) {
inBookshelfBookId.push(dang_ki_ca_biet_id);
}
else if (stateId === ((_b = listBookState.find((state) => state.code === IN_WAREHOUSE_STATE_CODE)) === null || _b === void 0 ? void 0 : _b.id)) {
inWareHouseBookId.push(dang_ki_ca_biet_id);
}
else {
inBookshelfBookId.push(dang_ki_ca_biet_id);
}
});
const dataSubmit = {
action_code: ACTION_LIBRARY_CREATE_TICKET,
submitTicket: {
...data,
total_book: [...inWareHouseBookId, ...inBookshelfBookId].length,
warehouse_id: warehouseId,
actual_borrow_date: 'now',
expect_return_date: formatDateMMDDYY(data.expect_return_date),
user_id: userId,
school_id: Number(userInfo === null || userInfo === void 0 ? void 0 : userInfo.school_id),
created_at: 'now',
ticket_state_id: (_a = dataSelect.ticketStates.find((item) => item.code === BORROWED_TICKET_CODE)) === null || _a === void 0 ? void 0 : _a.id,
...(bookBorrowInsert && {
library_borrow_books: {
data: bookBorrowInsert,
},
}),
},
dataUpdateSateBookBorrow: {
inBookshelfBookId,
inWareHouseBookId,
},
};
const resData = await PHXAxiosInstance.post(`/library/borrow-ticket/create-ticket-borrow`, dataSubmit);
const isSuccess = (_b = resData.data) === null || _b === void 0 ? void 0 : _b.success;
const message = (_c = resData.data) === null || _c === void 0 ? void 0 : _c.message;
if (isSuccess) {
triggerMessage({
type: FORM_TYPE.ADD,
});
}
if (!isSuccess) {
triggerMessage({
type: FORM_TYPE.CUSTOM,
message,
isFailure: true,
});
}
onHideModal();
}
catch (e) {
console.error(e);
setSubmitLoading(false);
}
};
function onHideModal() {
onHide === null || onHide === void 0 ? void 0 : onHide();
setBannerDescription('');
reset({
borrow_note: '',
borrow_reason: '',
expect_return_date: '',
book_borrower_id: defaultBookBorrower,
});
setSubmitLoading(false);
setListBook([]);
setDefaultExpectReturnDate(null);
}
useEffect(() => {
if (bookBorrowerCode) {
const dataFilterProfile = handleProfile(bookBorrowerCode);
if (dataFilterProfile) {
setFilterProfile(dataFilterProfile);
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [bookBorrowerCode, setValue, warehouseId]);
useEffect(() => {
// fill giá trị mặc định cho lý do mượn sách
if (show) {
setValue('borrow_note', 'Bạn đọc đã mượn sách thành công.');
}
}, [show]);
useEffect(() => {
var _a, _b;
const book_borrower_id = watch('book_borrower_id');
const nextBorrowerCode = (_b = (_a = dataSelect.bookBorrower) === null || _a === void 0 ? void 0 : _a.find((item) => item.id === Number(book_borrower_id))) === null || _b === void 0 ? void 0 : _b.code;
if (nextBorrowerCode && nextBorrowerCode !== bookBorrowerCode) {
setBookBorrowerCode(nextBorrowerCode);
}
}, [watch('book_borrower_id')]);
useEffect(() => {
if (currentSchoolYearId && show) {
getData();
}
}, [currentSchoolYearId, show]);
return (React.createElement(PHXModal, { className: 'mt-[-4rem]', disableOutsideClick: true, disableSubmit: disabledSubmit, headerClassName: 'bg-white', inCard: false, onHide: onHideModal, onSubmit: handleSubmit(onSubmit), primaryActionText: 'Th\u00EAm m\u1EDBi', primaryLoading: submitLoading, show: show, size: 'large', title: 'Th\u00EAm m\u1EDBi phi\u1EBFu m\u01B0\u1EE3n', type: 'no-padding' }, loading ? (React.createElement("div", { className: 'h-[calc(100vh-12rem)] space-y-4 bg-[#F1F1F1] p-4' },
React.createElement(PHXSkeleton, { type: 'content-modal' }),
React.createElement(PHXSkeleton, { type: 'content-modal' }),
React.createElement(PHXSkeleton, { type: 'content-modal' }))) : (React.createElement("div", { className: 'h-[calc(100vh-12rem)] space-y-4 overflow-y-auto bg-[#F1F1F1] p-4' },
React.createElement(PHXCard, { border: false, primaryHeader: true, title: 'Th\u00F4ng tin chung' },
React.createElement("div", { className: 'space-y-4' },
React.createElement(PHXBanner, { className: 'mb-4', description: bannerDescription, hideCloseButton: true, show: !!bannerDescription, title: 'C\u1EA3nh b\u00E1o', type: 'warning' }),
React.createElement(PHXSelect, { className: 'col-span-2', defaultValue: defaultBookBorrower, label: '\u0110\u1ED1i t\u01B0\u1EE3ng m\u01B0\u1EE3n s\u00E1ch', register: register('book_borrower_id', {
required: true,
}) },
React.createElement("option", { value: '' }, "L\u1EF1a ch\u1ECDn"), (_b = dataSelect.bookBorrower) === null || _b === void 0 ? void 0 :
_b.map((item) => {
const { id, name } = item;
return (React.createElement("option", { key: id, value: id }, name));
})),
React.createElement(PHXSearchResultListV3, { key: bookBorrowerCode, disabled: !bookBorrowerCode, error: !!errors.user_id, errorType: 'required-field', filterArray: [
{ keyChild: 'full_name' },
{ keyParent: 'profile_student', keyChild: 'user_code' },
{ keyParent: 'profile_teacher', keyChild: 'user_code' },
{ keyParent: 'profile_staff', keyChild: 'user_code' },
], getSearchResult: (value) => {
handleChangeBookBorrower(value);
setUserId(value.id);
}, handleCustomRender: handleRenderSelectSearchResultList, isFillInput: true, isUnaccentSearchValue: true, label: 'Ng\u01B0\u1EDDi m\u01B0\u1EE3n', name: 'user_id', placeholder: 'Nh\u1EADp t\u00EAn ho\u1EB7c m\u00E3', register: register('user_id'), search: searchUserBorrow(userInfo === null || userInfo === void 0 ? void 0 : userInfo.school_id, currentSchoolYearId, filterProfile), setValue: setValue }),
React.createElement("div", { className: ' col-span-2' },
React.createElement(PHXSelectBox, { data: [{ id: null, value: 'Lựa chọn' }, ...dataSelect.classrooms],
// disabled={!userId}
label: 'Nh\u00F3m \u0111\u1ECDc gi\u1EA3', onChange: (value) => setValue('classroom_id', value.id), placeholder: 'L\u1EF1a ch\u1ECDn' })),
defaultExpectReturnDate ? (React.createElement(PHXDatePicker, { key: `visible_select_date_${defaultExpectReturnDate}`, defaultValue: defaultExpectReturnDate, error: !watch('expect_return_date'), errorType: 'required-field', id: 'expect_return_date', label: 'Ng\u00E0y tr\u1EA3 (d\u1EF1 ki\u1EBFn)', onChangeDate: ({ format }) => {
setValue('expect_return_date', format);
setDefaultExpectReturnDate(format);
}, placeholder: 'DD-MM-YYYY' })) : (React.createElement(PHXDatePicker, { key: 'invisible_select_date', errorType: 'required-field', id: 'expect_return_date', label: 'Ng\u00E0y tr\u1EA3 (d\u1EF1 ki\u1EBFn)', placeholder: 'DD-MM-YYYY' })),
React.createElement(PHXTextarea, { className: ' col-span-2', label: 'L\u00FD do m\u01B0\u1EE3n s\u00E1ch', placeholder: 'Nh\u1EADp l\u00FD do', register: register('borrow_reason'), rows: 4 }),
React.createElement(PHXTextarea, { className: ' col-span-2', label: 'Ghi ch\u00FA l\u00FAc m\u01B0\u1EE3n', placeholder: 'Nh\u1EADp ghi ch\u00FA', register: register('borrow_note'), rows: 4 }))),
warehouseId && (React.createElement(BookBorrowInfo, { bookBorrowerId: Number(watch('book_borrower_id') || defaultBookBorrower), listBookBorrower: dataSelect.bookBorrower, onChange: (data) => setListBook(data), prefixQrCode: '', warehouseId: warehouseId }))))));
}
//# sourceMappingURL=index.js.map