import React, { useContext, useEffect, useState, useImperativeHandle, forwardRef, } from "react"; import axios from "axios"; import moment from "moment"; import { useDispatch, useSelector } from "react-redux"; import { Button, TextField, Typography } from "@mui/material"; import { DatePicker } from "@mui/x-date-pickers"; import { RiSearchLine } from "react-icons/ri"; import { AppContext } from "../../../../contexts/AppContext"; import { CLOSE_MODAL, LOADING_END, LOADING_START, OPEN_MODAL, } from "../../../../lib/redux/slices/appSlice"; import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl"; import { formatJustDate, formatTime } from "../../../../utils/formatTime"; import { SPACING } from "../../../../data/spacing"; import { Grid } from "../../../../components/grid/Grid"; import { slaughterInventoryFinalSubmitService } from "../../../slaughter-house/services/slaughter-inventory-final-submit"; import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable"; import { StewardShowAllocationsOperations } from "../steward-show-allocations-operations/StewardShowAllocationsOperations"; import { getAllocationType } from "../../../../utils/getAllocationType"; import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith"; // import { format } from "date-fns-jalali"; export const StewardShowAllocations = forwardRef( ({ type, handleUpdate, priceInfo, remainWeight }, ref) => { const dispatch = useDispatch(); const [ , , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2, ] = useContext(AppContext); const selectedSubUser = useSelector( (state) => state.userSlice.selectedSubUser ); useEffect(() => { const currentDate = moment(new Date()).format("YYYY-MM-DD"); setSelectedDate1(currentDate); setSelectedDate2(currentDate); }, []); const handleTextChange = (event) => { setTextValue(event.target.value); 8; }; const [data, setData] = useState([]); const [totalRows, setTotalRows] = useState(0); const [perPage, setPerPage] = useState(10); const [textValue, setTextValue] = useState(""); const [page, setPage] = useState(1); const [tableData, setTableData] = useState([]); const [openNotif] = useContext(AppContext); const fetchApiData = async (pageParam = 1) => { try { dispatch(LOADING_START()); const response = await axios.get( `steward-allocation/?role=${getRoleFromUrl()}${ checkPathStartsWith("steward") ? `&role_key=${selectedSubUser?.key}` : "" }&search=filter&value=${textValue}${ type !== "not_entered" ? `&date1=${selectedDate1}&date2=${selectedDate2}` : "" }&page=${pageParam}&page_size=${perPage}${ type ? "&type=" + type : "" }` ); dispatch(LOADING_END()); setData(response.data.results || []); setTotalRows(response.data.count || 0); } catch (err) { dispatch(LOADING_END()); console.error("Error fetching allocations:", err); } }; const updateTable = () => { fetchApiData(1); // Do not call handleUpdate() here - parent's handleUpdate already calls // updateTable() on both instances; calling handleUpdate would cause // infinite recursion (handleUpdate → updateTable → handleUpdate → …). // Callers that need the parent bars summary refreshed call handleUpdate explicitly. }; useImperativeHandle(ref, () => ({ updateTable, })); const handlePageChange = (newPage) => { fetchApiData(newPage); setPage(newPage); }; const getAllocationData = (item) => { let typeText = `${item?.toKillHouse?.name} - ${item?.toKillHouse?.killHouseOperator?.user?.fullname} (${item?.toKillHouse?.killHouseOperator?.user?.mobile})`; switch (item?.allocationType) { case "steward_killhouse": typeText = `${item?.toKillHouse?.name} - ${item?.toKillHouse?.killHouseOperator?.user?.fullname} (${item?.toKillHouse?.killHouseOperator?.user?.mobile})`; break; case "steward_steward": typeText = `${item?.toStewards?.name} - ${item?.toStewards?.user?.fullname} (${item?.toStewards?.user?.mobile})`; break; case "steward_guild": typeText = `${item?.toGuilds?.guildsName} - ${item?.toGuilds?.user?.fullname} (${item?.toGuilds?.user?.mobile})`; break; case "ColdHouse": typeText = `${item?.toColdHouse?.name}`; break; case "killhouse_steward": typeText = `${item?.toStewards?.name || "-"} - ${ item?.toStewards?.user?.fullname || "-" } (${item?.toStewards?.user?.mobile || "-"})`; break; case "killhouse_guild": typeText = `${item?.toGuilds?.guildsName || "-"} - ${ item?.toGuilds?.user?.fullname || "-" } (${item?.toGuilds?.user?.mobile || "-"})`; break; default: typeText = `${item?.toKillHouse?.name} - ${item?.toKillHouse?.killHouseOperator?.user?.fullname} (${item?.toKillHouse?.killHouseOperator?.user?.mobile})`; break; } return typeText; }; const getSellerName = (item) => { let type = ""; switch (item?.allocationType) { case "steward_guild": case "steward_steward": type = `${!item?.stewards ? "-" : item?.stewards?.user?.fullname} (${ item?.stewards?.user?.mobile })`; break; case "killhouse_steward": type = `${!item?.killHouse ? "-" : item?.killHouse?.name} (${ item?.killHouse?.killHouseOperator?.user?.fullname } - ${item?.killHouse?.killHouseOperator?.user?.mobile})`; break; case "killhouse_guild": type = `${!item?.killHouse ? "-" : item?.killHouse?.name} (${ item?.killHouse?.killHouseOperator?.user?.fullname } - ${item?.killHouse?.killHouseOperator?.user?.mobile})`; break; default: type = `${!item?.steward ? "-" : item?.steward?.user?.fullname} (${ item?.steward?.user?.mobile })`; break; } return type; }; const handlePerRowsChange = (perRows) => { setPerPage(perRows); setPage(1); }; const getLastItem = () => { if (!type || type === "not_entered") { return ["عملیات"]; } else { return []; } }; const getRegCodeItemData = (item) => { if (type === "not_entered") { return []; } else { return [ item?.loggedRegistrationCode ? item.loggedRegistrationCode : "-", item?.registrationCode ? "ارسال شده" : "ارسال نشده", ]; } }; const getRegCodeItemColumns = () => { if (type === "not_entered") { return []; } else { return ["کداحراز", "وضعیت کد احراز"]; } }; const getAprovedItemData = (item) => { if (!type) { return [item?.receiverRealWeightOfCarcasses?.toLocaleString()]; } else if (type === "not_entered") { return []; } else { return [ item?.receiverRealNumberOfCarcasses?.toLocaleString(), item?.receiverRealWeightOfCarcasses?.toLocaleString(), ]; } }; const getAprovedItemColumns = () => { if (!type) { return ["وزن تایید شده"]; } else if (type === "not_entered") { return []; } else { return ["حجم تایید شده", "وزن تایید شده"]; } }; useEffect(() => { const d = data?.map((item, i) => { return [ page === 1 ? i + 1 : i + perPage * (page - 1) + 1, item?.date ? formatTime(item?.date) : "-", item?.productionDate ? formatJustDate(item?.productionDate) : "-", item?.distributionType === "web" ? "سایت" : item?.distributionType === "app" ? "موبایل" : item?.distributionType === "pos" ? "پوز" : item?.distributionType || "-", getAllocationType(item), getAllocationData(item), getSellerName(item), item?.sellType === "exclusive" ? "اختصاصی" : "آزاد", item?.amount?.toLocaleString() + " ریال", item?.totalAmount?.toLocaleString() + " ریال", item?.realWeightOfCarcasses?.toLocaleString(), ...getAprovedItemData(item), ...getRegCodeItemData(item), item?.weightLossOfCarcasses?.toLocaleString(), item?.quota === "governmental" ? "دولتی" : item?.quota === "free" ? "آزاد" : "-", item?.approvedPriceStatus ? "دولتی" : "آزاد", item?.receiverState === "accepted" ? "تایید شده" : item?.receiverState === "rejected" ? "رد شده" : "در انتظار تایید", , ]; }); setTableData(d); }, [data]); useEffect(() => { fetchApiData(1); }, [selectedDate1, selectedDate2, perPage]); const handleSubmit = async (event) => { event.preventDefault(); dispatch(LOADING_START()); try { const response = await axios.get( `steward-allocation/?role=${getRoleFromUrl()}${ checkPathStartsWith("steward") ? `&role_key=${selectedSubUser?.key}` : "" }&search=filter&value=${textValue}${ type !== "not_entered" ? `&date1=${selectedDate1}&date2=${selectedDate2}` : "" }&page=${page}&page_size=${perPage}${type ? "&type=" + type : ""}` ); setData(response.data.results); setTotalRows(response.data.count); dispatch(LOADING_END()); } catch (error) { console.error("Error fetching data:", error); dispatch(LOADING_END()); } }; return ( {type !== "not_entered" && ( <> ( )} value={selectedDate1} onChange={(e) => { setSelectedDate1(moment(e).format("YYYY-MM-DD")); }} /> ( )} value={selectedDate2} onChange={(e) => { setSelectedDate2(moment(e).format("YYYY-MM-DD")); }} /> )}
{!(type === "entered" || type === "not_entered") && (
), }) ); }} > تایید نهایی (یکجا) )}
); } ); StewardShowAllocations.displayName = "StewardShowAllocations";