import { JSONPath as jsonpath } from "jsonpath-plus"; import _ from "lodash"; import useTranslation from "next-translate/useTranslation"; import Link from "next/link"; import { useRouter } from "next/router"; import { useCallback, useState } from "react"; import { connect } from "react-redux"; import transLookup from "../../data/lookuptranslations.json"; import { setCurrentReference } from "../../store/currentView/action"; import { parseCookies, setCookie } from "nookies"; import { useEffect } from "react"; import { setLoggedInUserId } from "../../store/accountDetails/action"; import { setSearchDetails, setSearchResults } from "../../store/searchOutput/action"; import { setWatchedCases, setWatchedCasesDetails } from "../../store/watchedCases/action"; import { getDetailsProxy } from "../utils"; import PaginationControl from "./pagination"; import { signIn, useSession } from "next-auth/react"; import { createWatchedCases, deleteWatchedCases, getWatchedCasesProxy } from "../../actions/services/portalService"; import RepsOnResults from "./repsonresults"; import LiveLink from "./liveLink"; const escapeRegExp = (string) => string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); const highlightText = (text, query) => { if (!text || !query) return text; const terms = Array.isArray(query) ? query : String(query).trim().split(/\s+/).filter(Boolean); if (!terms.length) return text; const regex = new RegExp(`(${terms.map(escapeRegExp).join("|")})`, "gi"); return String(text) .split(regex) .map((part, i) => regex.test(part) ? ( {part} ) : ( part ) ); }; const SearchResults = (props) => { const { searchString, searchResultsObj, searchDetailsObj, setCurrentReference, setSearchResults, setSearchDetails, advancedSearch, myportal, watchedCases, setWatchedCases, setWatchedCasesDetails, isLinkedCase, showLoginCheck } = props; let { t } = useTranslation(); const router = useRouter(); const { locale } = router; const { data: session } = useSession(); let [resultsArr, setResultsArr] = useState(searchResultsObj.value || []); const hasCount = searchResultsObj && typeof searchResultsObj["@odata.count"] === "number"; const [currentPage, setCurrentPage] = useState(1); const [searchLoaded, setSearchLoaded] = useState(false); const [showSpinnerState, setShowSpinnerState] = useState( !(searchResultsObj && searchResultsObj["@odata.count"] != null) ); const [selectedOption, setSelectedOption] = useState(10); const [orderByState, setOrderbyState] = useState("createdon"); const [fieldSortState, setfieldSortState] = useState("asc"); const [loginToWatch, setLoginToWatch] = useState("true"); let spinnerState = () => { showSpinnerState == true ? setShowSpinnerState(false) : setShowSpinnerState(true); }; const cookies = parseCookies(); const selectWatchedCase = (loggedInUser, incidentID, appealType) => { let updateBody = { "pinswg_WatchedCase@odata.bind": "/incidents(" + incidentID + ")", "pinswg_Contact@odata.bind": "/contacts(" + loggedInUser + ")", "pinswg_appealcasetype": +appealType }; createWatchedCases(updateBody) .then((data) => data) .then(() => { getWatchedCasesProxy(props.accountDetails.loggedinUserId).then( (data) => { (setWatchedCases(data), getDetailsProxy(data, "myWatchedCases").then( (data) => { setWatchedCasesDetails(data); } )); } ); }); }; const selectEmailNotifications = ( emailaddress, loggedInUser, incidentID, appealType ) => { let updateBody = { "pinswg_WatchedCase@odata.bind": "/incidents(" + incidentID + ")", "pinswg_Contact@odata.bind": "/contacts(" + loggedInUser + ")", "pinswg_appealcasetype": +appealType, "pinswg_emailnotifications": true }; console.log("Email signed up"); createWatchedCases(updateBody) .then((data) => data) .then(() => { getWatchedCasesProxy(props.accountDetails.loggedinUserId).then( (data) => { (setWatchedCases(data), getDetailsProxy(data, "myWatchedCases").then( (data) => { setWatchedCasesDetails(data); } )); } ); }); }; const isWatchedCase = (whichIncident) => { let isWatched = jsonpath({ path: "$..value[?(@ && @._pinswg_watchedcase_value=='" + whichIncident + "')]", json: watchedCases, eval: true }); return isWatched; }; const isEmailSignUp = (whichIncident) => { let isEmail = jsonpath({ path: "$..value[?(@ && @._pinswg_watchedcase_value=='" + whichIncident + "' && @.pinswg_emailnotifications==true)]", json: watchedCases, eval: true }); return isEmail; }; const deleteItem = (caseID, topThreeType) => { let cookies = parseCookies(); topThreeType == "watchedCases" && deleteWatchedCases(caseID) .then((data) => data) .then(() => { getWatchedCasesProxy( props.accountDetails.loggedinUserId ).then((data) => { let showWatchedCases = (submittedArr) => { const required = submittedArr.value.filter((el) => { return ( el.pinswg_representationsubmitted == null ); }); let newObj = {}; return Object.assign(newObj, { "@odata.count": required.length, "value": required }); }; data = showWatchedCases(data); data.value.sort(function compare(a, b) { var dateA = new Date(a.createdon); var dateB = new Date(b.createdon); return dateB - dateA; }); (setWatchedCases(data), getDetailsProxy(data, "myWatchedCases").then( (data) => { setWatchedCasesDetails(data); } )); }); }); }; const indexOfLastRecord = currentPage * selectedOption; const indexOfFirstRecord = indexOfLastRecord - selectedOption; const highlightQuery = advancedSearch ? searchString.map(([key, val]) => val).filter(Boolean) : searchString; const ResultsView = (resultsArr) => { var resultsArrPaged = resultsArr.slice( indexOfFirstRecord, indexOfLastRecord ); return ( <>
{t("search:searchresults-site-address-label")}
{/* {t("search:searchresults-status-label")} */}
{showSpinnerState == true ? (
{t("common:spinner-fetching-data")} {
) : ( resultsArrPaged.map((item, key) => { let detailsObj = jsonpath({ path: '$..[?(@ && @.ticketnumber=="' + item.ticketnumber + '")]', json: searchDetailsObj, eval: true }); detailsObj = detailsObj[0]; return (
{t( "search:searchresults-case-reference-label" )} : {item.pinswg_name}
{t( "search:searchresults-site-address-label" )} : {_.has( detailsObj, "pinswg_projectlocation" ) ? highlightText( detailsObj.pinswg_projectlocation != null ? detailsObj.pinswg_projectlocation.indexOf( ";" ) < 0 ? detailsObj.pinswg_projectlocation : router.locale == "cy" ? detailsObj.pinswg_projectlocation.split( ";" )[1] : detailsObj.pinswg_projectlocation.split( ";" )[0] : "", highlightQuery ) : ""} {_.has( detailsObj, "pinswg_siteaddressline1" ) ? highlightText( detailsObj.pinswg_siteaddressline1, highlightQuery ) : ""} {_.has( detailsObj, "pinswg_addressline1" ) ? highlightText( detailsObj.pinswg_addressline1, highlightQuery ) : ""} {/* {detailsObj.pinswg_siteaddressline1 != null &&
} */} {_.has( detailsObj, "pinswg_siteaddressline1" ) && detailsObj.pinswg_siteaddressline1 != null &&
} {_.has( detailsObj, "pinswg_addressline1" ) && detailsObj.pinswg_addressline1 != null &&
} {_.has( detailsObj, "pinswg_siteaddressline1" ) ? highlightText( detailsObj.pinswg_siteaddressline2, highlightQuery ) : ""} {_.has( detailsObj, "pinswg_addressline1" ) ? highlightText( detailsObj.pinswg_addressline2, highlightQuery ) : ""} {_.has( detailsObj, "pinswg_siteaddressline2" ) && detailsObj.pinswg_siteaddressline2 != null &&
} {_.has( detailsObj, "pinswg_addressline2" ) && detailsObj.pinswg_addressline2 != null &&
} {_.has( detailsObj, "pinswg_siteaddresstown" ) ? highlightText( detailsObj.pinswg_siteaddresstown, highlightQuery ) : ""} {_.has(detailsObj, "pinswg_addresstown") ? highlightText( detailsObj.pinswg_addresstown, highlightQuery ) : ""} {_.has( detailsObj, "pinswg_siteaddresstown" ) && detailsObj.pinswg_siteaddresstown != null &&
} {_.has( detailsObj, "pinswg_addresstown" ) && detailsObj.pinswg_addresstown != null &&
} {_.has( detailsObj, "pinswg_siteaddresscounty" ) ? highlightText( detailsObj.pinswg_siteaddresscounty, highlightQuery ) : ""} {_.has( detailsObj, "pinswg_addresscounty" ) ? highlightText( detailsObj.pinswg_addresscounty, highlightQuery ) : ""} {_.has( detailsObj, "pinswg_siteaddresscounty" ) && detailsObj.pinswg_siteaddresscounty != null &&
} {_.has( detailsObj, "pinswg_addresscounty" ) && detailsObj.pinswg_addresscounty != null &&
} {_.has( detailsObj, "pinswg_siteaddresspostcode" ) ? highlightText( detailsObj.pinswg_siteaddresspostcode, highlightQuery ) : ""} {_.has(detailsObj, "pinswg_postcode") ? highlightText( detailsObj.pinswg_postcode, highlightQuery ) : ""}
{t( "search:searchresults-applicant-label" )} : {_.has(detailsObj, [ "_pinswg_appellant_value@OData.Community.Display.V1.FormattedValue" ]) ? detailsObj[ "_pinswg_appellant_value@OData.Community.Display.V1.FormattedValue" ] : ""}
{t( "search:searchresults-authority-label" )} : {_.has(item, [ "_pinswg_localplanningauthority_value@OData.Community.Display.V1.FormattedValue" ]) ? router.locale == "cy" ? jsonpath({ path: '$..[?(@ && @.value=="' + item[ "_pinswg_localplanningauthority_value@OData.Community.Display.V1.FormattedValue" ] + '")].value_cy', json: transLookup, eval: true }) : item[ "_pinswg_localplanningauthority_value@OData.Community.Display.V1.FormattedValue" ] || "N/A" : ""} {_.has(item, [ "_pinswg_associatedlpa_value@OData.Community.Display.V1.FormattedValue" ]) ? router.locale == "cy" ? jsonpath({ path: '$..[?(@ && @.value=="' + item[ "_pinswg_associatedlpa_value@OData.Community.Display.V1.FormattedValue" ] + '")].value_cy', json: transLookup, eval: true }) : item[ "_pinswg_associatedlpa_value@OData.Community.Display.V1.FormattedValue" ] || "N/A" : ""} {item?.pinswg_lpareference && ( <> Ref: {" "} {highlightText( item.pinswg_lpareference, highlightQuery )} )}
{t( "search:searchresults-case-type-label" )} : {router.locale == "cy" ? jsonpath({ path: '$..[?(@ && @.value=="' + item[ "pinswg_appealType" ] + '")].value_cy', json: transLookup, eval: true }) : item["pinswg_appealType"] || "N/A"}
{t( "search:searchresults-status-label" )} : {router.locale == "cy" ? jsonpath({ path: '$..[?(@ && @.value=="' + item[ "statuscode@OData.Community.Display.V1.FormattedValue" ] + '")].value_cy', json: transLookup, eval: true }) : item[ "statuscode@OData.Community.Display.V1.FormattedValue" ] || "N/A"}
{myportal == true && (
{isWatchedCase(item.incidentid) .length > 0 == true ? ( ) : ( )} {isEmailSignUp(item.incidentid) .length > 0 == true ? ( ) : ( )}
)} {(showLoginCheck == "true" || showLoginCheck == true) && !session && (
{t( "case:watch-this-case-link" )}
)}
); }) )}
); }; const pagesCount = Math.ceil(searchResultsObj["@odata.count"] / 10); const getSearchPageResults = useCallback( (pageNumber, orderBy, fieldSort) => { // setSearchDetails(data); setCurrentPage(pageNumber); let sortedResults = []; setResultsArr((previousResults) => { sortedResults = _.sortBy(previousResults, [ function (o) { return o[orderBy]; } ]); fieldSort == "desc" && sortedResults.reverse(); return sortedResults; }); setShowSpinnerState(false); console.log( "================================\n", sortedResults, "sort done", "\n=================================\n" ); }, [] ); const sortDataBy = (whichField) => { setOrderbyState(whichField); setfieldSortState("asc"); setShowSpinnerState(true); console.log( "================================\n", "sort start", "\n=================================\n" ); getSearchPageResults(1, whichField, fieldSortState); whichField == orderByState ? fieldSortState == "desc" ? setfieldSortState("asc") : setfieldSortState("desc") : setfieldSortState("asc"); setCurrentPage(1); }; useEffect(() => { const selectWatchedCase = (loggedInUser, incidentID, appealType) => { let updateBody = { "pinswg_WatchedCase@odata.bind": "/incidents(" + incidentID + ")", "pinswg_Contact@odata.bind": "/contacts(" + loggedInUser + ")", "pinswg_appealcasetype": +appealType }; createWatchedCases(updateBody) .then((data) => data) .then(() => { getWatchedCasesProxy( props.accountDetails.loggedinUserId ).then((data) => { (setWatchedCases(data), getDetailsProxy(data, "myWatchedCases").then( (data) => { setWatchedCasesDetails(data); } )); }); }); }; // if (searchLoaded) { // if (selectedOption) { // setShowSpinnerState(true); // getSearchPageResults(1, orderByState, fieldSortState); // } // } else { // setSearchLoaded(true); // } if (loginToWatch && router.query.hasOwnProperty("toWatch")) { console.log("am in here"); let now = new Date(); let expDate = new Date(now); expDate.setDate(now.getDate() + 1); setLoggedInUserId(props.accountDetails.loggedinUserId); setCookie(null, "pinsUser", props.accountDetails.loggedinUserId, { path: "/", expires: expDate }); selectWatchedCase( props.accountDetails.loggedinUserId, router.query.toWatch.split("_")[0], router.query.toWatch.split("_")[1] ); getSearchPageResults(1, orderByState, fieldSortState); setLoginToWatch(false); } else { //console.log("or am in here"); setLoginToWatch(false); } }, [ selectedOption, fieldSortState, orderByState, searchLoaded, loginToWatch, setWatchedCases, getSearchPageResults, setWatchedCasesDetails, props.accountDetails.loggedinUserId, router.query ]); return ( <>

{isLinkedCase ? t("search:searchresults-title-label-linked-case") : t("search:searchresults-title-label")}

{!isLinkedCase && (

{resultsArr.length > 200 ? t("search:searchresults-max-count-label") : t("search:searchresults-count-label", { count: searchResultsObj["@odata.count"] })} . {advancedSearch != true ? ( <> {t( "search:searchresults-case-count-label" )}{" "} {" "} "{searchString}" ) : ( "" )}

)} {searchResultsObj["@odata.count"] > 5 && (
)} {resultsArr.length > 0 ? ( ResultsView(resultsArr) ) : (

{t("search:searchresults-no-records-label")}

)}
); }; const mapDispatchToProps = (dispatch) => { return { setCurrentReference: (currentReference) => { dispatch(setCurrentReference(currentReference)); }, setSearchResults: (searchResultsObj) => { dispatch(setSearchResults(searchResultsObj)); }, setSearchDetails: (searchDetailsObj) => { dispatch(setSearchDetails(searchDetailsObj)); }, setWatchedCases: (watchedCases) => { dispatch(setWatchedCases(watchedCases)); }, setWatchedCasesDetails: (watchedCasesDetails) => { dispatch(setWatchedCasesDetails(watchedCasesDetails)); } // setCurrentPage: (currentPage) => { // dispatch(setCurrentPage(currentPage)); // }, }; }; const mapStateToProps = (state) => { return { // currentView: state.currentView, accountDetails: state.accountDetails // search: state.search, // searchResultsObj: state.searchResultsObj, }; }; export default connect(mapStateToProps, mapDispatchToProps)(SearchResults);