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 { getAdvancedSearchPaged, getBasicSearchPaged } from "../../actions/services/searchService"; import transLookup from "../../data/lookuptranslations.json"; import { setCurrentPage, 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, getSearchDetailsPaged } from "../utils"; import PaginationControl from "./pagination"; import { signIn, useSession } from "next-auth/react"; import { createWatchedCases, deleteWatchedCases, getWatchedCasesProxy } from "../../actions/services/portalService"; import { sendGAEvent } from "@next/third-parties/google"; import RepsOnResults from "./repsonresults"; import LiveLink from "./liveLink"; import { query } from "jsonpath"; 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, setCurrentPage, showLoginCheck } = props; let { t } = useTranslation(); const router = useRouter(); const { locale } = router; const { data: session } = useSession(); var resultsArr = searchResultsObj.value || []; const hasCount = searchResultsObj && typeof searchResultsObj["@odata.count"] === "number"; const [searchLoaded, setSearchLoaded] = useState(false); // const [showSpinnerState, setShowSpinnerState] = 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("desc"); 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 isEmailNotifications = (whichIncident) => { let isWatched = jsonpath({ path: "$..value[?(@ && @._pinswg_watchedcase_value=='" + whichIncident + "')]", json: watchedCases, eval: true }); return isWatched; }; 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); } )); }); }); }; function hasValidKey(obj, key) { return ( obj.hasOwnProperty(key) && obj[key] !== null && obj[key] !== undefined && obj[key] !== "" ); } const highlightQuery = advancedSearch ? searchString.map(([key, val]) => val).filter(Boolean) : searchString; const ResultsView = (resultsArr, currPage) => { return ( <>
{t("search:searchresults-site-address-label")}
{/* {t("search:searchresults-status-label")} */}
{showSpinnerState == true ? (
{t("common:spinner-fetching-data")} {
) : ( resultsArr.map((item, key) => { let detailsObj = jsonpath({ path: '$..[?(@ && @.ticketnumber=="' + item.ticketnumber + '")]', json: searchDetailsObj, eval: true }); Object.assign(item, item.pinswg_sipscase); detailsObj = detailsObj[0] || {}; return (
{ (sendGAEvent( "event", "CaseViewed", { caseReference: item.ticketnumber } ), setCurrentReference({ "statuscode": item.statuscode, "ticketnumber": item.ticketnumber, "currentReference": item.title, "currentType": "searchResultsObj", "incidentid": item.incidentid, "appealType": item.pinswg_appealcasetype, "showLoginCheck": props.showLoginCheck, "specialistProcess": detailsObj.hasOwnProperty( "pinswg_speacialistcaseprocess" ) ? detailsObj.pinswg_speacialistcaseprocess : detailsObj.hasOwnProperty( "pinswg_specialistcaseprocess" ) ? detailsObj.pinswg_specialistcaseprocess : "" })); }} > {t( "search:searchresults-case-reference-label" )} : {highlightText( item.title, highlightQuery )} {item.hasOwnProperty( "pinswg_sipscase" ) && item.hasOwnProperty( "_pinswg_projecttype_value@OData.Community.Display.V1.FormattedValue" ) && (
{ item[ "_pinswg_projecttype_value@OData.Community.Display.V1.FormattedValue" ] }
)}
{t( "search:searchresults-site-address-label" )} : {_.has( detailsObj, "pinswg_projectlocation" ) ? 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] : "" : // : hasValidKey( // item, // "pinswg_caseaddress" // ) // ? item.pinswg_caseaddress != null // ? item.pinswg_caseaddress.indexOf( // ";" // ) < 0 // ? item.pinswg_caseaddress // : router.locale == "cy" // ? item.pinswg_caseaddress.split( // ";" // )[1] // : item.pinswg_caseaddress.split( // ";" // )[0] // : "" ""} {_.has( detailsObj, "pinswg_siteaddressline1" ) ? detailsObj.pinswg_siteaddressline1 : ""} {/* {detailsObj.pinswg_siteaddressline1 != null &&
} */} {_.has( detailsObj, "pinswg_siteaddressline1" ) && detailsObj.pinswg_siteaddressline1 != null &&
} {_.has( detailsObj, "pinswg_siteaddressline1" ) ? detailsObj.pinswg_siteaddressline2 : ""} {_.has( detailsObj, "pinswg_siteaddressline2" ) && detailsObj.pinswg_siteaddressline2 != null &&
} {_.has( detailsObj, "pinswg_siteaddresstown" ) ? detailsObj.pinswg_siteaddresstown : ""} {_.has( detailsObj, "pinswg_siteaddresstown" ) && detailsObj.pinswg_siteaddresstown != null &&
} {_.has( detailsObj, "pinswg_siteaddresscounty" ) ? detailsObj.pinswg_siteaddresscounty : ""} {_.has( detailsObj, "pinswg_siteaddresscounty" ) && detailsObj.pinswg_siteaddresscounty != null &&
} {_.has( detailsObj, "pinswg_siteaddresspostcode" ) ? detailsObj.pinswg_siteaddresspostcode : ""}
{t( "search:searchresults-applicant-label" )} : {item.pinswg_appellantagent == 846040001 ? item.pinswg_appellantfirstname + " " + item.pinswg_appellantlastname : _.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_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_appealcasetype@OData.Community.Display.V1.FormattedValue" ] + '")].value_cy', json: transLookup, eval: true }) : item[ "pinswg_appealcasetype@OData.Community.Display.V1.FormattedValue" ] || "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); let currentPage = 0; currentPage = decodeURI(searchResultsObj["@odata.nextLink"]).split( "skiptoken=" )[1]; currentPage = typeof currentPage != "undefined" ? parseInt( decodeURI(currentPage) .split('pagenumber="')[1] .slice( 0, decodeURI(currentPage) .split('pagenumber="')[1] .indexOf('"') ) - 1 ) : pagesCount; const getSearchPageResults = useCallback( (pageNumber, orderBy, fieldSort) => { //console.log(advancedSearch, searchString, pageNumber); if (advancedSearch) { var searchoObj = Object.assign( ...searchString.map(([key, val]) => ({ [key]: val })) ); getAdvancedSearchPaged( searchoObj, pageNumber, orderBy, fieldSort, selectedOption ) .then((data) => data) .then((data) => { //console.log("getting details", data); setSearchResults(data); return getSearchDetailsPaged(data).then((data) => { setSearchDetails(data); setShowSpinnerState(false); }); }); } else { getBasicSearchPaged( searchString, pageNumber, orderBy, fieldSort, selectedOption ) .then((data) => data) .then((data) => { //console.log("getting details", data); setSearchResults(data); return getSearchDetailsPaged(data).then((data) => { setSearchDetails(data); setShowSpinnerState(false); }); }); } }, [ advancedSearch, searchString, selectedOption, setSearchDetails, setSearchResults ] ); const sortDataBy = (whichField) => { setOrderbyState(whichField); setfieldSortState("asc"); getSearchPageResults(1, whichField, fieldSortState); whichField == orderByState ? fieldSortState == "desc" ? setfieldSortState("asc") : setfieldSortState("desc") : setfieldSortState("asc"); setCurrentPage(1); setShowSpinnerState(true); }; 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 ]); //console.log( // "page is here ", // currentPage, // orderByState + " " + fieldSortState // ); return ( <>

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

{!isLinkedCase && (hasCount ? (

{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}" ) : ( "" )}

) : (

{t("common:spinner-fetching-data")} {

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

{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);