From f4517a93eb0a9075d99098c6e0f3d7aef24ba2b9 Mon Sep 17 00:00:00 2001 From: suzalflueck Date: Mon, 29 Apr 2024 13:39:41 -0700 Subject: [PATCH 1/5] add check --- frontend/src/utils/common.ts | 5 + frontend/src/views/DistrictView.vue | 182 ++++++++++++++-------------- 2 files changed, 98 insertions(+), 89 deletions(-) diff --git a/frontend/src/utils/common.ts b/frontend/src/utils/common.ts index a3459726..f00bbbfd 100644 --- a/frontend/src/utils/common.ts +++ b/frontend/src/utils/common.ts @@ -13,3 +13,8 @@ export function useSanitizeURL(input: string | String): String { input = input.toLowerCase().replace(/^a-zA-Z0-9 ]/g, '') return input } + +/** VALIDATION FUNCTIONS */ +export function isValidDistrictNumber(input: string | String | number): boolean { + return !!input && input.toString().length === 3 && /^\d+$/.test(input.toString()); +} diff --git a/frontend/src/views/DistrictView.vue b/frontend/src/views/DistrictView.vue index 88203020..833ce3da 100644 --- a/frontend/src/views/DistrictView.vue +++ b/frontend/src/views/DistrictView.vue @@ -4,7 +4,7 @@ import { ref, reactive, onMounted, computed, toValue } from 'vue' import { useAppStore } from '@/stores/app' import { useRoute } from 'vue-router' import router from '@/router' -import { formatPhoneNumber } from '@/utils/common' +import { formatPhoneNumber, isValidDistrictNumber } from '@/utils/common' import type { District, School, Grade, Address, Contact } from '@/types/types.d.ts' import jsonexport from 'jsonexport/dist' import { useSanitizeURL } from '@/composables/string' @@ -78,97 +78,101 @@ function downloadDistrictSchools() { onMounted(async () => { const route = useRoute() // Set the districtId inside the onMounted hook; null if districtId not found - districtId.value = - appStore.getDistrictByDistrictNumber(String(route.params.districtNumber))?.districtId ?? null + if (isValidDistrictNumber(String(route.params.districtNumber))) { + districtId.value = + appStore.getDistrictByDistrictNumber(String(route.params.districtNumber))?.districtId ?? null + } // get district data - try { - const response = await InstituteService.getDistrictView(districtId.value as string) - if (response.data?.districtData?.contacts) { - district.value = response.data - contacts.value = response.data?.districtData?.contacts - schools.value = district.value?.districtSchools + if (!!districtId.value) { + try { + const response = await InstituteService.getDistrictView(districtId.value as string) + if (response.data?.districtData?.contacts) { + district.value = response.data + contacts.value = response.data?.districtData?.contacts + schools.value = district.value?.districtSchools - //Change School date for DL - const transformedSchoolData = schools.value.map((school: School) => { - const { contacts, addresses, ...rest } = school - const transformedContacts = contacts.map(({ schoolContactTypeCode, ...contactRest }) => ({ - schoolContactTypeCode, - ...contactRest - })) - const physicalAddress = addresses.find( - (address: Address) => address?.addressTypeCode === 'PHYSICAL' - ) - const mailingAddress = addresses.find( - (address: Address) => address?.addressTypeCode === 'MAILING' - ) - return { - ...rest, - contacts: transformedContacts.reduce((acc, contact) => ({ ...acc, ...contact }), {}), - physicalAddress: physicalAddress, - mailingAddress: mailingAddress, - grades: [], - neighborhoodLearning: [], - schoolMove: [] - } - }) - //Change School data for DL - filteredSchools.value = transformedSchoolData.map((item: any) => { - return { - 'District Number': response.data.districtData.districtNumber, - Mincode: item.mincode, - 'Display Name': item.displayName, - 'Mailing Address': item.mailingAddress?.addressLine1, - 'Mailing Address Line2': item.mailingAddress?.addressLine2, - 'Mailing Address City': item.mailingAddress?.city, - 'Mailing Address Province': item.mailingAddress?.provinceCode, - 'Mailing Address PostalCode': item.mailingAddress?.postal, - 'Physical Address': item.physicalAddress?.addressLine1, - 'Physical Address Line2': item.physicalAddress?.addressLine2, - 'Physical Address City': item.physicalAddress?.city, - 'Physical Address Province': item.physicalAddress?.provinceCode, - 'Physical Address Postal Code': item.physicalAddress?.postal, - Role: item.contacts?.jobTitle, - 'Contact First Name': item.contacts?.firstName, - 'Contact Last Name': item.contacts?.lastName, - 'Contact Phone Extension': item.contacts?.phoneExtension, - 'Contact Phone Number': item.contacts?.phoneNumber, - 'Facility Type Code': appStore.getFacilityCodeLabel(item.facilityTypeCode), - 'School Category Code': appStore.getCategoryCodeLabel(item.schoolCategoryCode), - 'Phone Number': item.phoneNumber, - Fax: item.faxNumber, - Email: item.email, - Website: item.website, - 'Group Classification Primary K-3': item.primaryK3, - 'Group Classification Elementary 4-7 EU': item.elementary47, - 'Group Classification Junior Secondary 8-10 SU': item.juniorSecondary810, - 'Group Classification Senior Secondary 11-12': item.seniorSecondary1112 - } - }) - filteredContacts.value = contacts.value.map((item: any) => { - return { - 'District Number': response.data.districtData?.districtNumber, - 'District Name': response.data.districtData?.displayName, - 'Contact Type': item.label, - 'Job Title': item.jobTitle, - 'First Name': item.firstName, - 'Last Name': item.lastName, - 'Phone Number': item.phoneNumber, - 'Phone Extension': item.phoneExtension, - 'Alternate Phone Number': item.alternatePhoneNumber, - 'Alternate Phone Extension': item.alternatePhoneExtension, - Email: item.email, - 'Mailing Address': response.data.districtData?.addresses[0].addressLine1, - 'Mailing City': response.data.districtData?.addresses[0].city, - 'Mailing Province': response.data.districtData?.addresses[0].provinceCode, - 'Mailing Postal Code': response.data.districtData?.addresses[0].postal, - 'District Phone': response.data.districtData?.phoneNumber, - 'District Fax': response.data.districtData?.faxNumber, - Website: response.data.districtData?.website - } - }) + //Change School date for DL + const transformedSchoolData = schools.value.map((school: School) => { + const { contacts, addresses, ...rest } = school + const transformedContacts = contacts.map(({ schoolContactTypeCode, ...contactRest }) => ({ + schoolContactTypeCode, + ...contactRest + })) + const physicalAddress = addresses.find( + (address: Address) => address?.addressTypeCode === 'PHYSICAL' + ) + const mailingAddress = addresses.find( + (address: Address) => address?.addressTypeCode === 'MAILING' + ) + return { + ...rest, + contacts: transformedContacts.reduce((acc, contact) => ({ ...acc, ...contact }), {}), + physicalAddress: physicalAddress, + mailingAddress: mailingAddress, + grades: [], + neighborhoodLearning: [], + schoolMove: [] + } + }) + //Change School data for DL + filteredSchools.value = transformedSchoolData.map((item: any) => { + return { + 'District Number': response.data.districtData.districtNumber, + Mincode: item.mincode, + 'Display Name': item.displayName, + 'Mailing Address': item.mailingAddress?.addressLine1, + 'Mailing Address Line2': item.mailingAddress?.addressLine2, + 'Mailing Address City': item.mailingAddress?.city, + 'Mailing Address Province': item.mailingAddress?.provinceCode, + 'Mailing Address PostalCode': item.mailingAddress?.postal, + 'Physical Address': item.physicalAddress?.addressLine1, + 'Physical Address Line2': item.physicalAddress?.addressLine2, + 'Physical Address City': item.physicalAddress?.city, + 'Physical Address Province': item.physicalAddress?.provinceCode, + 'Physical Address Postal Code': item.physicalAddress?.postal, + Role: item.contacts?.jobTitle, + 'Contact First Name': item.contacts?.firstName, + 'Contact Last Name': item.contacts?.lastName, + 'Contact Phone Extension': item.contacts?.phoneExtension, + 'Contact Phone Number': item.contacts?.phoneNumber, + 'Facility Type Code': appStore.getFacilityCodeLabel(item.facilityTypeCode), + 'School Category Code': appStore.getCategoryCodeLabel(item.schoolCategoryCode), + 'Phone Number': item.phoneNumber, + Fax: item.faxNumber, + Email: item.email, + Website: item.website, + 'Group Classification Primary K-3': item.primaryK3, + 'Group Classification Elementary 4-7 EU': item.elementary47, + 'Group Classification Junior Secondary 8-10 SU': item.juniorSecondary810, + 'Group Classification Senior Secondary 11-12': item.seniorSecondary1112 + } + }) + filteredContacts.value = contacts.value.map((item: any) => { + return { + 'District Number': response.data.districtData?.districtNumber, + 'District Name': response.data.districtData?.displayName, + 'Contact Type': item.label, + 'Job Title': item.jobTitle, + 'First Name': item.firstName, + 'Last Name': item.lastName, + 'Phone Number': item.phoneNumber, + 'Phone Extension': item.phoneExtension, + 'Alternate Phone Number': item.alternatePhoneNumber, + 'Alternate Phone Extension': item.alternatePhoneExtension, + Email: item.email, + 'Mailing Address': response.data.districtData?.addresses[0].addressLine1, + 'Mailing City': response.data.districtData?.addresses[0].city, + 'Mailing Province': response.data.districtData?.addresses[0].provinceCode, + 'Mailing Postal Code': response.data.districtData?.addresses[0].postal, + 'District Phone': response.data.districtData?.phoneNumber, + 'District Fax': response.data.districtData?.faxNumber, + Website: response.data.districtData?.website + } + }) + } + } catch (error) { + console.error(error) } - } catch (error) { - console.error(error) } // get district contact type codes // try { From 045ba8c66cbf384f8097858156acbef2b2de154e Mon Sep 17 00:00:00 2001 From: suzalflueck Date: Fri, 3 May 2024 12:03:13 -0700 Subject: [PATCH 2/5] backend fixes for async issues --- backend/src/routes/district-router.js | 71 ++-- backend/src/routes/institute-router.js | 494 +++++++++++++++---------- frontend/src/stores/app.ts | 28 +- frontend/src/views/DistrictView.vue | 9 +- 4 files changed, 355 insertions(+), 247 deletions(-) diff --git a/backend/src/routes/district-router.js b/backend/src/routes/district-router.js index a2d9c392..944d32e3 100644 --- a/backend/src/routes/district-router.js +++ b/backend/src/routes/district-router.js @@ -244,13 +244,14 @@ async function getAllDistrictContacts(req, res) { let sortedData = sortJSONByDistrictNumber(filteredData); res.json(sortedData); } catch (e) { + log.error(e); log.error("getData Error", e.response ? e.response.status : e.message); } } async function getAllDistrictMailing(req, res) { const districtList = await listCache.get("districtlist"); - const contactTypeCodes = await listCache.get("codesList"); + //const contactTypeCodes = await listCache.get("codesList"); const propertyOrder = [ { property: "districtId_districtNumber", label: "District Number" }, @@ -325,6 +326,7 @@ async function getAllDistrictMailing(req, res) { res.json(contentByDistrict); //res.json(districtContactsReorderedAndRelabeled ); } catch (e) { + log.error(e); log.error("getData Error", e.response ? e.response.status : e.message); } } @@ -399,8 +401,9 @@ async function getDistrict(req, res) { const facilityCodes = await listCache.get("facilityCodes"); const fundingGroups = await listCache.get("fundingGroups"); const districtContactCodeTypes = await listCache.get("codesList"); - const nonPublicContactTypeCodes = - getNonPublicContactTypeCodes(contactTypeCodes); + const nonPublicContactTypeCodes = await getNonPublicContactTypeCodes( + contactTypeCodes + ); const districtDataPublic = removeContacts( districtDataResponse.data, @@ -410,36 +413,37 @@ async function getDistrict(req, res) { districtDataPublic, contactTypeCodes ); - districtDataPublicWithLabels.contacts = filterByPubliclyAvailableCodes( - districtDataPublicWithLabels.contacts, - "districtContactTypeCode", - getArrayofPubliclyAvailableCodes( - districtContactCodeTypes.codesList.districtContactTypeCodes, - "districtContactTypeCode" - ) - ); - districtDataPublicWithLabels.contacts = filterByExpiryDate( - districtDataPublicWithLabels.contacts - ); - - districtSchoolsResponse.data.content = normalizeJsonObject( - districtSchoolsResponse.data.content, - schoolCategoryCodes, - "schoolCategoryCode", - null, - ["label", "description"] - ); - districtSchoolsResponse.data.content = normalizeJsonObject( - districtSchoolsResponse.data.content, - facilityCodes, - "faciltyTypeCode", - null, - ["label", "description"] - ); - districtSchoolsResponse.data.content = addFundingGroups( - districtSchoolsResponse.data.content, - fundingGroups - ); + if (!!districtContactCodeTypes) { + districtDataPublicWithLabels.contacts = filterByPubliclyAvailableCodes( + districtDataPublicWithLabels.contacts, + "districtContactTypeCode", + getArrayofPubliclyAvailableCodes( + districtContactCodeTypes.codesList.districtContactTypeCodes, + "districtContactTypeCode" + ) + ); + districtDataPublicWithLabels.contacts = filterByExpiryDate( + districtDataPublicWithLabels.contacts + ); + districtSchoolsResponse.data.content = normalizeJsonObject( + districtSchoolsResponse.data.content, + schoolCategoryCodes, + "schoolCategoryCode", + null, + ["label", "description"] + ); + districtSchoolsResponse.data.content = normalizeJsonObject( + districtSchoolsResponse.data.content, + facilityCodes, + "faciltyTypeCode", + null, + ["label", "description"] + ); + districtSchoolsResponse.data.content = addFundingGroups( + districtSchoolsResponse.data.content, + fundingGroups + ); + } const today = new Date(); const filteredSchoolsResponse = districtSchoolsResponse.data.content.filter( @@ -467,6 +471,7 @@ async function getDistrict(req, res) { res.json(districtJSON); log.info(req.url); } catch (e) { + log.error(e); log.error("getData Error", e.response ? e.response.status : e.message); } } diff --git a/backend/src/routes/institute-router.js b/backend/src/routes/institute-router.js index 2b0ebf95..a87404e4 100644 --- a/backend/src/routes/institute-router.js +++ b/backend/src/routes/institute-router.js @@ -5,28 +5,69 @@ const config = require("../config/index"); const axios = require("axios"); const { checkToken } = require("../components/auth"); -const {filterByOpenedAndClosedDate, formatGrades, removeFieldsByCriteria, createList, addDistrictLabels, districtNumberSort, isAllowedSchoolCategory, filterRemoveByField, filterByField } = require("../components/utils"); +const { + filterByOpenedAndClosedDate, + formatGrades, + removeFieldsByCriteria, + createList, + addDistrictLabels, + districtNumberSort, + isAllowedSchoolCategory, + filterRemoveByField, + filterByField, +} = require("../components/utils"); const { listCache, codeCache } = require("../components/cache"); -const schoolListOptions = { fields: ["mincode", "displayName", "schoolId", "closedDate", "openedDate","schoolCategoryCode"], fieldToInclude: null, valueToInclude: null, sortField: "mincode" }; -const districtListOptions = { fields: ["displayName", "districtId","districtNumber", "closedDate"] ,fieldToInclude: "districtStatusCode", valueToInclude: "ACTIVE", sortField: "districtNumber"}; -const authorityListOptions = { fields: ["displayName", "authorityNumber","independentAuthorityId", "closedDate", "opendDate"], sortField: "authorityNumber" }; -const openSchoolListOptions = { fields: [ - "schoolId", - "districtId", - "mincode", - "schoolNumber", - "faxNumber", - "phoneNumber", - "email", - "website", - "displayName", - "schoolCategoryCode", - "facilityTypeCode", - "openedDate", - "closedDate", - "districtNumber" -],fieldToInclude: "closedDate", valueToInclude: null, sortField: "mincode" }; +const schoolListOptions = { + fields: [ + "mincode", + "displayName", + "schoolId", + "closedDate", + "openedDate", + "schoolCategoryCode", + ], + fieldToInclude: null, + valueToInclude: null, + sortField: "mincode", +}; +const districtListOptions = { + fields: ["displayName", "districtId", "districtNumber", "closedDate"], + fieldToInclude: "districtStatusCode", + valueToInclude: "ACTIVE", + sortField: "districtNumber", +}; +const authorityListOptions = { + fields: [ + "displayName", + "authorityNumber", + "independentAuthorityId", + "closedDate", + "opendDate", + ], + sortField: "authorityNumber", +}; +const openSchoolListOptions = { + fields: [ + "schoolId", + "districtId", + "mincode", + "schoolNumber", + "faxNumber", + "phoneNumber", + "email", + "website", + "displayName", + "schoolCategoryCode", + "facilityTypeCode", + "openedDate", + "closedDate", + "districtNumber", + ], + fieldToInclude: "closedDate", + valueToInclude: null, + sortField: "mincode", +}; //Batch Routes router.get("/contact-type-codes", checkToken, getContactTypeCodes); @@ -37,7 +78,7 @@ router.get("/authority/list", checkToken, getAuthorityList); router.get("/district/list", checkToken, getDistrictList); router.get("/district/contact/*", checkToken, getDistrictContactsAPI); router.get("/create-cache", checkToken, createCache); -router.get("/category-codes", checkToken, getCategoryCodes); +router.get("/category-codes", checkToken); router.get("/*", checkToken, getInstituteAPI); @@ -47,9 +88,7 @@ async function createCache(req, res) { try { const fundingGroupsResponse = await axios.get( - `${config.get( - "server:schoolsAPIURL" - )}/schools/fundingGroups`, + `${config.get("server:schoolsAPIURL")}/schools/fundingGroups`, { headers: { Authorization: `Bearer ${req.accessToken}` }, } @@ -70,10 +109,20 @@ async function createCache(req, res) { axios .get(url, { headers: { Authorization: `Bearer ${req.accessToken}` } }) .then((response) => { - const filteredNonbBCDistrictList = response.data.filter(district => ["098","102", "103"].includes(district.districtNumber)); - const filteredDistrictList = response.data.filter(district => !["098","102", "103"].includes(district.districtNumber)); - const districtList = createList(filteredDistrictList, districtListOptions); - const nonBCdistrictList = createList(filteredNonbBCDistrictList, districtListOptions); + const filteredNonbBCDistrictList = response.data.filter((district) => + ["098", "102", "103"].includes(district.districtNumber) + ); + const filteredDistrictList = response.data.filter( + (district) => !["098", "102", "103"].includes(district.districtNumber) + ); + const districtList = createList( + filteredDistrictList, + districtListOptions + ); + const nonBCdistrictList = createList( + filteredNonbBCDistrictList, + districtListOptions + ); listCache.set("nonbcdistrictlist", nonBCdistrictList); listCache.set("districtlist", districtList); @@ -86,31 +135,32 @@ async function createCache(req, res) { e.response ? e.response.status : e.message ); }); - } + } if (!listCache.has("categoryCodes")) { //const codes = []; - + try { const categoryCodesResponse = await axios.get( - `${config.get( - "server:instituteAPIURL" - )}/institute/category-codes`, + `${config.get("server:instituteAPIURL")}/institute/category-codes`, { headers: { Authorization: `Bearer ${req.accessToken}` }, } ); - - categoryCodesResponse.data = filterRemoveByField(categoryCodesResponse.data,"schoolCategoryCode", ["FED_BAND","POST_SEC","YUKON"]) + + categoryCodesResponse.data = filterRemoveByField( + categoryCodesResponse.data, + "schoolCategoryCode", + ["FED_BAND", "POST_SEC", "YUKON"] + ); listCache.set("categoryCodes", categoryCodesResponse.data); - } catch (error) { const statusCode = error.response ? error.response.status : 500; log.error("Category Code Caching Error", statusCode, error.message); res.status(statusCode).send(error.message); } - } else{ + } else { const categoryCodes = await listCache.get("categoryCodes"); - res.json(categoryCodes) + res.json(categoryCodes); } if (await !codeCache.has("gradelist")) { const url = `${config.get("server:instituteAPIURL")}/institute/grade-codes`; // Update the URL according to your API endpoint @@ -118,7 +168,7 @@ async function createCache(req, res) { .get(url, { headers: { Authorization: `Bearer ${req.accessToken}` } }) .then((response) => { const gradeCodes = response.data; - + codeCache.set("gradelist", gradeCodes); log.info(req.url); }) @@ -133,37 +183,34 @@ async function createCache(req, res) { res.json(gradeCodes); } - if (!listCache.has("categoryCodes")) { - //const codes = []; - - try { - const categoryCodesResponse = await axios.get( - `${config.get( - "server:instituteAPIURL" - )}/institute/category-codes`, - { - headers: { Authorization: `Bearer ${req.accessToken}` }, - } - ); - - categoryCodesResponse.data = filterRemoveByField(categoryCodesResponse.data,"schoolCategoryCode", ["FED_BAND","POST_SEC","YUKON"]) - listCache.set("categoryCodes", categoryCodesResponse.data); - - } catch (error) { - const statusCode = error.response ? error.response.status : 500; - log.error("Category Code Caching Error", statusCode, error.message); - res.status(statusCode).send(error.message); - } - } - + // if (!listCache.has("categoryCodes")) { + + // try { + // const categoryCodesResponse = await axios.get( + // `${config.get( + // "server:instituteAPIURL" + // )}/institute/category-codes`, + // { + // headers: { Authorization: `Bearer ${req.accessToken}` }, + // } + // ); + + // categoryCodesResponse.data = filterRemoveByField(categoryCodesResponse.data,"schoolCategoryCode", ["FED_BAND","POST_SEC","YUKON"]) + // listCache.set("categoryCodes", categoryCodesResponse.data); + + // } catch (error) { + // const statusCode = error.response ? error.response.status : 500; + // log.error("Category Code Caching Error", statusCode, error.message); + // res.status(statusCode).send(error.message); + // } + // } + if (!listCache.has("facilityCodes")) { //const codes = []; try { const facilityCodesResponse = await axios.get( - `${config.get( - "server:instituteAPIURL" - )}/institute/facility-codes`, + `${config.get("server:instituteAPIURL")}/institute/facility-codes`, { headers: { Authorization: `Bearer ${req.accessToken}` }, } @@ -174,47 +221,52 @@ async function createCache(req, res) { log.error("Faility Code Caching Error", statusCode, error.message); res.status(statusCode).send(error.message); } - } + } if (!listCache.has("districtAddresses")) { //const codes = []; try { const districtsResponse = await axios.get( - `${config.get("server:instituteAPIURL")}/institute/district/paginated?pageSize=200`, + `${config.get( + "server:instituteAPIURL" + )}/institute/district/paginated?pageSize=200`, { headers: { Authorization: `Bearer ${req.accessToken}` }, } ); - + districtsResponse.data.content.forEach((district) => { district.addresses.forEach((address) => { - if (address.addressTypeCode === "MAILING") { Object.keys(address).forEach((field) => { // Exclude the specified fields - if (![ - "createUser", - "updateUser", - "createDate", - "updateDate", - "schoolAddressId", - "schoolId", - "addressTypeCode" - ].includes(field)) { + if ( + ![ + "createUser", + "updateUser", + "createDate", + "updateDate", + "schoolAddressId", + "schoolId", + "addressTypeCode", + ].includes(field) + ) { district[`mailing_${field}`] = address[field]; } }); } else if (address.addressTypeCode === "PHYSICAL") { Object.keys(address).forEach((field) => { - if (![ - "createUser", - "updateUser", - "createDate", - "updateDate", - "schoolAddressId", - "schoolId", - "addressTypeCode" - ].includes(field)) { + if ( + ![ + "createUser", + "updateUser", + "createDate", + "updateDate", + "schoolAddressId", + "schoolId", + "addressTypeCode", + ].includes(field) + ) { district[`physical_${field}`] = address[field]; } }); @@ -227,8 +279,7 @@ async function createCache(req, res) { log.error("District Code Caching Error", statusCode, error.message); res.status(statusCode).send(error.message); } - } - + } if (await !listCache.has("codesList")) { try { @@ -260,9 +311,18 @@ async function createCache(req, res) { ); const codes = { - authorityContactTypeCodes: removeFieldsByCriteria(authorityContactTypeCodesResponse.data, [{ fieldToRemove: "publiclyAvailable", value: false }]), - districtContactTypeCodes: removeFieldsByCriteria(districtContactTypeCodesResponse.data,[{ fieldToRemove: "publiclyAvailable", value: false }]), - schoolContactTypeCodes: removeFieldsByCriteria(schoolContactTypeCodesResponse.data,[{ fieldToRemove: "publiclyAvailable", value: false }]), + authorityContactTypeCodes: removeFieldsByCriteria( + authorityContactTypeCodesResponse.data, + [{ fieldToRemove: "publiclyAvailable", value: false }] + ), + districtContactTypeCodes: removeFieldsByCriteria( + districtContactTypeCodesResponse.data, + [{ fieldToRemove: "publiclyAvailable", value: false }] + ), + schoolContactTypeCodes: removeFieldsByCriteria( + schoolContactTypeCodesResponse.data, + [{ fieldToRemove: "publiclyAvailable", value: false }] + ), }; res.json(codes); listCache.set("codesList", { codesList: codes }); @@ -273,10 +333,8 @@ async function createCache(req, res) { } } res.status(200).json({ success: true }); - } - async function getContactTypeCodes(req, res) { if (await !listCache.has("codesList")) { //const codes = []; @@ -310,9 +368,18 @@ async function getContactTypeCodes(req, res) { ); const codes = { - authorityContactTypeCodes: removeFieldsByCriteria(authorityContactTypeCodesResponse.data, [{ fieldToRemove: "publiclyAvailable", value: false }]), - districtContactTypeCodes: removeFieldsByCriteria(districtContactTypeCodesResponse.data,[{ fieldToRemove: "publiclyAvailable", value: false }]), - schoolContactTypeCodes: removeFieldsByCriteria(schoolContactTypeCodesResponse.data,[{ fieldToRemove: "publiclyAvailable", value: false }]), + authorityContactTypeCodes: removeFieldsByCriteria( + authorityContactTypeCodesResponse.data, + [{ fieldToRemove: "publiclyAvailable", value: false }] + ), + districtContactTypeCodes: removeFieldsByCriteria( + districtContactTypeCodesResponse.data, + [{ fieldToRemove: "publiclyAvailable", value: false }] + ), + schoolContactTypeCodes: removeFieldsByCriteria( + schoolContactTypeCodesResponse.data, + [{ fieldToRemove: "publiclyAvailable", value: false }] + ), }; listCache.set("codesList", { codesList: codes }); res.json(codes); @@ -327,67 +394,72 @@ async function getContactTypeCodes(req, res) { } } async function getOffshoreSchoolList(req, res) { - - let currentDate = new Date().toISOString().substring(0, 19) + let currentDate = new Date().toISOString().substring(0, 19); const params = [ { - condition: 'AND', + condition: "AND", searchCriteriaList: [ { - key: 'schoolCategoryCode', - operation: 'eq', + key: "schoolCategoryCode", + operation: "eq", value: "OFFSHORE", - valueType: 'STRING', - condition: 'AND' + valueType: "STRING", + condition: "AND", }, { - key: 'openedDate', - operation: 'lte', + key: "openedDate", + operation: "lte", value: currentDate, - valueType: 'DATE_TIME', - condition: 'AND' - } - ] + valueType: "DATE_TIME", + condition: "AND", + }, + ], }, { - condition: 'AND', + condition: "AND", searchCriteriaList: [ { - key: 'closedDate', - operation: 'eq', + key: "closedDate", + operation: "eq", value: null, - valueType: 'STRING', - condition: 'OR' + valueType: "STRING", + condition: "OR", }, { - key: 'closedDate', - operation: 'gte', + key: "closedDate", + operation: "gte", value: currentDate, - valueType: 'DATE_TIME', - condition: 'OR' - } - ] - } + valueType: "DATE_TIME", + condition: "OR", + }, + ], + }, ]; - const jsonString = JSON.stringify(params) - const encodedParams = encodeURIComponent(jsonString) - - + const jsonString = JSON.stringify(params); + const encodedParams = encodeURIComponent(jsonString); if (await !listCache.has("offshoreschoollist")) { - const url = `${config.get('server:instituteAPIURL')}/institute/school/paginated?pageSize=1000&pageNumber=0&searchCriteriaList=${encodedParams}`; + const url = `${config.get( + "server:instituteAPIURL" + )}/institute/school/paginated?pageSize=1000&pageNumber=0&searchCriteriaList=${encodedParams}`; axios .get(url, { headers: { Authorization: `Bearer ${req.accessToken}` } }) .then((response) => { const offshoreSchoolList = response.data.content; - const schoolGrades = codeCache.get("gradelist"); - + const schoolGrades = codeCache.get("gradelist"); + for (let i = 0; i < offshoreSchoolList.length; i++) { - const formattedGrades = formatGrades(offshoreSchoolList[i].grades, schoolGrades); - offshoreSchoolList[i] = { ...offshoreSchoolList[i], ...formattedGrades }; + const formattedGrades = formatGrades( + offshoreSchoolList[i].grades, + schoolGrades + ); + offshoreSchoolList[i] = { + ...offshoreSchoolList[i], + ...formattedGrades, + }; // Now you can use the updated offshoreSchoolList[i] object as needed - } + } res.json(offshoreSchoolList); listCache.set("offshoreschoollist", offshoreSchoolList); log.info(req.url); @@ -404,41 +476,44 @@ async function getOffshoreSchoolList(req, res) { } } async function getAuthorityList(req, res) { - if (await !listCache.has("authoritylist")) { - - let currentDate = new Date().toISOString().substring(0, 19) + let currentDate = new Date().toISOString().substring(0, 19); const params = [ { condition: null, searchCriteriaList: [ { - key: 'closedDate', - operation: 'eq', + key: "closedDate", + operation: "eq", value: null, - valueType: 'STRING', - condition: 'OR' + valueType: "STRING", + condition: "OR", }, { - key: 'closedDate', - operation: 'gte', + key: "closedDate", + operation: "gte", value: currentDate, - valueType: 'DATE_TIME', - condition: 'OR' - } - ] - } + valueType: "DATE_TIME", + condition: "OR", + }, + ], + }, ]; - - const jsonString = JSON.stringify(params) - const encodedParams = encodeURIComponent(jsonString) - - const url = `${config.get('server:instituteAPIURL')}/institute/authority/paginated?pageSize=1000&searchCriteriaList=${encodedParams}`; + + const jsonString = JSON.stringify(params); + const encodedParams = encodeURIComponent(jsonString); + + const url = `${config.get( + "server:instituteAPIURL" + )}/institute/authority/paginated?pageSize=1000&searchCriteriaList=${encodedParams}`; axios .get(url, { headers: { Authorization: `Bearer ${req.accessToken}` } }) .then((response) => { - const authorityList = createList(response.data.content, authorityListOptions); - + const authorityList = createList( + response.data.content, + authorityListOptions + ); + res.json(authorityList); listCache.set("authoritylist", authorityList); log.info(req.url); @@ -454,43 +529,58 @@ async function getAuthorityList(req, res) { res.json(authorityList); } } -async function getCategoryCodes(req, res) { - - if (!listCache.has("categoryCodes")) { - //const codes = []; - - try { - const categoryCodesResponse = await axios.get( - `${config.get( - "server:instituteAPIURL" - )}/institute/category-codes`, - { - headers: { Authorization: `Bearer ${req.accessToken}` }, - } - ); - - categoryCodesResponse.data = filterRemoveByField(categoryCodesResponse.data,"schoolCategoryCode", ["FED_BAND","POST_SEC","YUKON"]) - listCache.set("categoryCodes", categoryCodesResponse.data); - - } catch (error) { - const statusCode = error.response ? error.response.status : 500; - log.error("Category Code Caching Error", statusCode, error.message); - res.status(statusCode).send(error.message); - } - } else{ - const categoryCodes = await listCache.get("categoryCodes"); - res.json(categoryCodes) - } -} +// async function getCategoryCodes(req, res) { +// if (!listCache.has("categoryCodes")) { +// //const codes = []; + +// try { +// const categoryCodesResponse = await axios.get( +// `${config.get("server:instituteAPIURL")}/institute/category-codes`, +// { +// headers: { Authorization: `Bearer ${req.accessToken}` }, +// } +// ); + +// categoryCodesResponse.data = filterRemoveByField( +// categoryCodesResponse.data, +// "schoolCategoryCode", +// ["FED_BAND", "POST_SEC", "YUKON"] +// ); +// listCache.set("categoryCodes", categoryCodesResponse.data); +// } catch (error) { +// const statusCode = error.response ? error.response.status : 500; +// log.error("Category Code Caching Error", statusCode, error.message); +// res.status(statusCode).send(error.message); +// } +// } else { +// const categoryCodes = await listCache.get("categoryCodes"); +// res.json(categoryCodes); +// } +// } async function getSchoolList(req, res) { if (await !listCache.has("schoollist")) { const url = `${config.get("server:instituteAPIURL")}/institute/school`; // Update the URL according to your API endpoint axios .get(url, { headers: { Authorization: `Bearer ${req.accessToken}` } }) .then((response) => { - const openSchools = filterByOpenedAndClosedDate(response.data) - const validSchoolCategories = filterByField(openSchools, "schoolCategoryCode", ["POST_SEC", "YUKON", "SUMMER", "FED_BAND"]) - const validSchoolFacilities = filterByField(validSchoolCategories, "facilityTypeCode", ['PROVINCIAL','DIST_CONT','ELEC_DELIV','POST_SEC','JUSTB4PRO','SUMMER']) + const openSchools = filterByOpenedAndClosedDate(response.data); + const validSchoolCategories = filterByField( + openSchools, + "schoolCategoryCode", + ["POST_SEC", "YUKON", "SUMMER", "FED_BAND"] + ); + const validSchoolFacilities = filterByField( + validSchoolCategories, + "facilityTypeCode", + [ + "PROVINCIAL", + "DIST_CONT", + "ELEC_DELIV", + "POST_SEC", + "JUSTB4PRO", + "SUMMER", + ] + ); const schoolList = createList(validSchoolFacilities, schoolListOptions); res.json(schoolList); listCache.set("schoollist", schoolList); @@ -514,10 +604,20 @@ async function getDistrictList(req, res) { .get(url, { headers: { Authorization: `Bearer ${req.accessToken}` } }) .then((response) => { //const districtList = response.data; - const filteredNonbBCDistrictList = response.data.filter(district => ["098","102", "103"].includes(district.districtNumber)); - const filteredDistrictList = response.data.filter(district => !["098","102", "103"].includes(district.districtNumber)); - const districtList = createList(filteredDistrictList, districtListOptions); - const nonBCdistrictList = createList(filteredNonbBCDistrictList, districtListOptions); + const filteredNonbBCDistrictList = response.data.filter((district) => + ["098", "102", "103"].includes(district.districtNumber) + ); + const filteredDistrictList = response.data.filter( + (district) => !["098", "102", "103"].includes(district.districtNumber) + ); + const districtList = createList( + filteredDistrictList, + districtListOptions + ); + const nonBCdistrictList = createList( + filteredNonbBCDistrictList, + districtListOptions + ); listCache.set("nonbcdistrictlist", nonBCdistrictList); listCache.set("districtlist", districtList); res.json(districtList); @@ -552,19 +652,21 @@ async function getDistrictContactsAPI(req, res) { const url = `${config.get("server:instituteAPIURL")}/institute` + req.url; const districtList = await listCache.get("districtlist"); - const nonBCDistrictList = await listCache.get("nonbcdistrictlist"); + const nonBCDistrictList = await listCache.get("nonbcdistrictlist"); axios .get(url, { headers: { Authorization: `Bearer ${req.accessToken}` } }) .then((response) => { if (req.url.includes("/district/contact/paginated")) { const jsonData = addDistrictLabels(response.data, districtList); - - jsonData.content = jsonData.content.filter(contact => { + + jsonData.content = jsonData.content.filter((contact) => { // Check if districtId is not undefined, empty, or null - return contact.districtNumber !== undefined - && contact.districtNumber !== "" - && contact.districtNumber !== null; - }); + return ( + contact.districtNumber !== undefined && + contact.districtNumber !== "" && + contact.districtNumber !== null + ); + }); res.json(jsonData); } else { res.json(response.data); @@ -582,7 +684,7 @@ async function getGradeCodes(req, res) { .get(url, { headers: { Authorization: `Bearer ${req.accessToken}` } }) .then((response) => { const gradeCodes = response.data; - + codeCache.set("gradelist", gradeCodes); res.json(gradeCodes); log.info(req.url); diff --git a/frontend/src/stores/app.ts b/frontend/src/stores/app.ts index 08dad99f..4d950961 100644 --- a/frontend/src/stores/app.ts +++ b/frontend/src/stores/app.ts @@ -111,20 +111,20 @@ export const useAppStore = defineStore('app', { console.error("ERRPR LOADING CACHE" + error) }) // set category codes - InstituteService.getCategoryCodes().then((response) => { - const currentDate: Date = new Date() - this.categoryCodes = response.data?.filter((item: any) => { - const effectiveDate: Date = new Date(item.effectiveDate); - const expiryDate: Date = new Date(item.expiryDate); - return expiryDate >= currentDate && effectiveDate <= currentDate; - }) - //sort by display order - this.categoryCodes?.sort((a: any, b: any) => { - return a.displayOrder - b.displayOrder - }) - }).catch((error) => { - console.error(error) - }) + // InstituteService.getCategoryCodes().then((response) => { + // const currentDate: Date = new Date() + // this.categoryCodes = response.data?.filter((item: any) => { + // const effectiveDate: Date = new Date(item.effectiveDate); + // const expiryDate: Date = new Date(item.expiryDate); + // return expiryDate >= currentDate && effectiveDate <= currentDate; + // }) + // //sort by display order + // this.categoryCodes?.sort((a: any, b: any) => { + // return a.displayOrder - b.displayOrder + // }) + // }).catch((error) => { + // console.error(error) + // }) // set facility type codes InstituteService.getFacilityCodes().then((response) => { diff --git a/frontend/src/views/DistrictView.vue b/frontend/src/views/DistrictView.vue index 833ce3da..aaa7f9b8 100644 --- a/frontend/src/views/DistrictView.vue +++ b/frontend/src/views/DistrictView.vue @@ -78,10 +78,11 @@ function downloadDistrictSchools() { onMounted(async () => { const route = useRoute() // Set the districtId inside the onMounted hook; null if districtId not found - if (isValidDistrictNumber(String(route.params.districtNumber))) { - districtId.value = - appStore.getDistrictByDistrictNumber(String(route.params.districtNumber))?.districtId ?? null - } + // if (isValidDistrictNumber(String(route.params.districtNumber))) { + // districtId.value = + // appStore.getDistrictByDistrictNumber(String(route.params.districtNumber))?.districtId ?? null + // } + districtId.value = '349664f8-47e3-a226-075c-081d56d93d39' // get district data if (!!districtId.value) { try { From e2343ab7ab896a2e27177924b0a09042febcdd1b Mon Sep 17 00:00:00 2001 From: suzalflueck Date: Mon, 6 May 2024 13:41:06 -0700 Subject: [PATCH 3/5] added async to app store --- frontend/src/services/InstituteService.ts | 2 +- frontend/src/stores/app.ts | 14 ++++++------ frontend/src/views/DistrictView.vue | 28 ++++++++++------------- 3 files changed, 20 insertions(+), 24 deletions(-) diff --git a/frontend/src/services/InstituteService.ts b/frontend/src/services/InstituteService.ts index e7cbbf7d..75d823c1 100644 --- a/frontend/src/services/InstituteService.ts +++ b/frontend/src/services/InstituteService.ts @@ -68,7 +68,7 @@ export default { } return ApiService.apiAxios.get(url); }, - getDistrictView(id: string): Promise { + getDistrictView(id: string | undefined): Promise { return ApiService.apiAxios.get(`/api/v1/district/${id}`) }, getDistrictContactTypeCodes(): Promise { diff --git a/frontend/src/stores/app.ts b/frontend/src/stores/app.ts index 4d950961..e211ea4c 100644 --- a/frontend/src/stores/app.ts +++ b/frontend/src/stores/app.ts @@ -57,8 +57,8 @@ export const useAppStore = defineStore('app', { isIndependentSchool(schoolCategoryCode: String){ return schoolCategoryCode == 'INDEPEND' }, - setDistricts(): void { - InstituteService.getDistricts() + async setDistricts(): Promise { + await InstituteService.getDistricts() .then((response) => { // Handle the response data this.districts = response.data @@ -68,8 +68,8 @@ export const useAppStore = defineStore('app', { console.error(error) }) }, - setAuthorityList(): void { - InstituteService.getAuthorityList().then((response) => { + async setAuthorityList(): Promise { + await InstituteService.getAuthorityList().then((response) => { //handle the response this.authorities = response.data }) @@ -78,7 +78,7 @@ export const useAppStore = defineStore('app', { console.error(error) }) }, - setSchoolList(): void { + async setSchoolList(): Promise { InstituteService.getSchoolList() .then((response) => { @@ -91,7 +91,7 @@ export const useAppStore = defineStore('app', { }) }, - setOffshoreSchoolList(): void { + async setOffshoreSchoolList(): Promise { InstituteService.getOffshoreSchoolList() .then((response) => { @@ -104,7 +104,7 @@ export const useAppStore = defineStore('app', { }) }, - async setCodes() { + async setCodes(): Promise { await InstituteService.loadCache().then((response) => { //console.log(response) }).catch((error) => { diff --git a/frontend/src/views/DistrictView.vue b/frontend/src/views/DistrictView.vue index aaa7f9b8..96289cf9 100644 --- a/frontend/src/views/DistrictView.vue +++ b/frontend/src/views/DistrictView.vue @@ -13,7 +13,7 @@ import DisplayAddress from '@/components/common/DisplayAddress.vue' import DisplayAlert from '@/components/common/DisplayAlert.vue' const appStore = useAppStore() -const districtId = ref(null) // Initialize with null initially +const districtId = ref(undefined) // Initialize with null initially const district = reactive({ value: {} as District }) const schools = ref([]) const contacts = ref([]) @@ -74,19 +74,18 @@ function downloadDistrictSchools() { appStore.exportCSV(csv) }) } - -onMounted(async () => { +async function getDistrictId(): Promise { const route = useRoute() + return appStore.getDistrictByDistrictNumber(String(route.params.districtNumber))?.districtId ?? '' +} +async function getDistrictData(): Promise { // Set the districtId inside the onMounted hook; null if districtId not found - // if (isValidDistrictNumber(String(route.params.districtNumber))) { - // districtId.value = - // appStore.getDistrictByDistrictNumber(String(route.params.districtNumber))?.districtId ?? null - // } - districtId.value = '349664f8-47e3-a226-075c-081d56d93d39' + districtId.value = await getDistrictId() //move this getter to the backend? QUESTION + //districtId.value = '349664f8-47e3-a226-075c-081d56d93d39' // get district data if (!!districtId.value) { try { - const response = await InstituteService.getDistrictView(districtId.value as string) + const response = await InstituteService.getDistrictView(districtId.value) if (response.data?.districtData?.contacts) { district.value = response.data contacts.value = response.data?.districtData?.contacts @@ -175,13 +174,10 @@ onMounted(async () => { console.error(error) } } - // get district contact type codes - // try { - // const response = await InstituteService.getDistrictContactTypeCodes() - // districtContactTypeCodes.value = response.data - // } catch (error) { - // console.error(error) - // } +} + +onMounted(async () => { + await getDistrictData() }) From e157674afc02f5db3f995a54c1f4dc4e0196fdc6 Mon Sep 17 00:00:00 2001 From: suzalflueck Date: Thu, 9 May 2024 13:26:03 -0700 Subject: [PATCH 4/5] Fixed missing responses in backend and cleaning up routing since we were calling some endpoints multiple times --- backend/src/routes/district-router.js | 8 +- backend/src/routes/institute-router.js | 172 ++++++++++------------ frontend/src/App.vue | 2 +- frontend/src/services/InstituteService.ts | 26 ++-- frontend/src/stores/app.ts | 36 ++--- frontend/src/views/AuthorityView.vue | 20 ++- frontend/src/views/DistrictView.vue | 31 ++-- frontend/src/views/SchoolView.vue | 2 +- 8 files changed, 144 insertions(+), 153 deletions(-) diff --git a/backend/src/routes/district-router.js b/backend/src/routes/district-router.js index 944d32e3..9f6751fa 100644 --- a/backend/src/routes/district-router.js +++ b/backend/src/routes/district-router.js @@ -93,7 +93,7 @@ async function getDistrictCodes(req) { return districtCodeList; } catch (e) { log.error( - "getDistrictList Error", + "getDistrictCodesList Error", e.response ? e.response.status : e.message ); } @@ -244,14 +244,12 @@ async function getAllDistrictContacts(req, res) { let sortedData = sortJSONByDistrictNumber(filteredData); res.json(sortedData); } catch (e) { - log.error(e); log.error("getData Error", e.response ? e.response.status : e.message); } } async function getAllDistrictMailing(req, res) { const districtList = await listCache.get("districtlist"); - //const contactTypeCodes = await listCache.get("codesList"); const propertyOrder = [ { property: "districtId_districtNumber", label: "District Number" }, @@ -324,14 +322,11 @@ async function getAllDistrictMailing(req, res) { const contentByDistrict = sortJSONByDistrictNumber(content); res.json(contentByDistrict); - //res.json(districtContactsReorderedAndRelabeled ); } catch (e) { - log.error(e); log.error("getData Error", e.response ? e.response.status : e.message); } } -//api/v1/institute/district/12342525 async function getDistrict(req, res) { const { id } = req.params; @@ -471,7 +466,6 @@ async function getDistrict(req, res) { res.json(districtJSON); log.info(req.url); } catch (e) { - log.error(e); log.error("getData Error", e.response ? e.response.status : e.message); } } diff --git a/backend/src/routes/institute-router.js b/backend/src/routes/institute-router.js index a87404e4..4fb888eb 100644 --- a/backend/src/routes/institute-router.js +++ b/backend/src/routes/institute-router.js @@ -78,14 +78,12 @@ router.get("/authority/list", checkToken, getAuthorityList); router.get("/district/list", checkToken, getDistrictList); router.get("/district/contact/*", checkToken, getDistrictContactsAPI); router.get("/create-cache", checkToken, createCache); -router.get("/category-codes", checkToken); +router.get("/category-codes", checkToken, getCategoryCodes); router.get("/*", checkToken, getInstituteAPI); async function createCache(req, res) { if (await !listCache.has("fundingGroups")) { - //const codes = []; - try { const fundingGroupsResponse = await axios.get( `${config.get("server:schoolsAPIURL")}/schools/fundingGroups`, @@ -95,6 +93,7 @@ async function createCache(req, res) { ); listCache.set("fundingGroups", fundingGroupsResponse.data); res.json(fundingGroupsResponse.data); + log.info("cached funding groups - ", req.url); } catch (error) { const statusCode = error.response ? error.response.status : 500; log.error("getFunding Groups Error", statusCode, error.message); @@ -104,41 +103,40 @@ async function createCache(req, res) { const cachedFundingGroupList = await listCache.get("fundingGroups"); res.json(cachedFundingGroupList); } - if (await !listCache.has("districtlist")) { - const url = `${config.get("server:instituteAPIURL")}/institute/district`; // Update the URL according to your API endpoint - axios - .get(url, { headers: { Authorization: `Bearer ${req.accessToken}` } }) - .then((response) => { - const filteredNonbBCDistrictList = response.data.filter((district) => - ["098", "102", "103"].includes(district.districtNumber) - ); - const filteredDistrictList = response.data.filter( - (district) => !["098", "102", "103"].includes(district.districtNumber) - ); - const districtList = createList( - filteredDistrictList, - districtListOptions - ); - const nonBCdistrictList = createList( - filteredNonbBCDistrictList, - districtListOptions - ); - - listCache.set("nonbcdistrictlist", nonBCdistrictList); - listCache.set("districtlist", districtList); - res.json(districtList); - log.info(req.url); - }) - .catch((e) => { - log.error( - "getDistrictList Error", - e.response ? e.response.status : e.message - ); - }); - } - if (!listCache.has("categoryCodes")) { - //const codes = []; - + // if (await !listCache.has("districtlist")) { + // const url = `${config.get("server:instituteAPIURL")}/institute/district`; // Update the URL according to your API endpoint + // axios + // .get(url, { headers: { Authorization: `Bearer ${req.accessToken}` } }) + // .then((response) => { + // const filteredNonbBCDistrictList = response.data.filter((district) => + // ["098", "102", "103"].includes(district.districtNumber) + // ); + // const filteredDistrictList = response.data.filter( + // (district) => !["098", "102", "103"].includes(district.districtNumber) + // ); + // const districtList = createList( + // filteredDistrictList, + // districtListOptions + // ); + // const nonBCdistrictList = createList( + // filteredNonbBCDistrictList, + // districtListOptions + // ); + + // listCache.set("nonbcdistrictlist", nonBCdistrictList); + // listCache.set("districtlist", districtList); + // res.json(districtList); + // log.info("cached district list - ", req.url); + // }) + // .catch((e) => { + // log.error( + // "getDistrictList Error (createCache)", + // e.response ? e.response.status : e.message + // ); + // }); + // } + //TODO: Move to common function since this is same as getCategoryCodes() + if (await !listCache.has("categoryCodes")) { try { const categoryCodesResponse = await axios.get( `${config.get("server:instituteAPIURL")}/institute/category-codes`, @@ -153,6 +151,7 @@ async function createCache(req, res) { ["FED_BAND", "POST_SEC", "YUKON"] ); listCache.set("categoryCodes", categoryCodesResponse.data); + log.info("cached category codes - ", req.url); } catch (error) { const statusCode = error.response ? error.response.status : 500; log.error("Category Code Caching Error", statusCode, error.message); @@ -161,6 +160,7 @@ async function createCache(req, res) { } else { const categoryCodes = await listCache.get("categoryCodes"); res.json(categoryCodes); + log.info("fetched category codes - ", req.url); } if (await !codeCache.has("gradelist")) { const url = `${config.get("server:instituteAPIURL")}/institute/grade-codes`; // Update the URL according to your API endpoint @@ -170,44 +170,21 @@ async function createCache(req, res) { const gradeCodes = response.data; codeCache.set("gradelist", gradeCodes); - log.info(req.url); + log.info("cached grade list - ", req.url); }) .catch((e) => { log.error( - "getDistrictList Error", + "getGradeList Error", e.response ? e.response.status : e.message ); }); } else { const gradeCodes = await codeCache.get("gradelist"); res.json(gradeCodes); + log.info("fetched grade list - ", req.url); } - // if (!listCache.has("categoryCodes")) { - - // try { - // const categoryCodesResponse = await axios.get( - // `${config.get( - // "server:instituteAPIURL" - // )}/institute/category-codes`, - // { - // headers: { Authorization: `Bearer ${req.accessToken}` }, - // } - // ); - - // categoryCodesResponse.data = filterRemoveByField(categoryCodesResponse.data,"schoolCategoryCode", ["FED_BAND","POST_SEC","YUKON"]) - // listCache.set("categoryCodes", categoryCodesResponse.data); - - // } catch (error) { - // const statusCode = error.response ? error.response.status : 500; - // log.error("Category Code Caching Error", statusCode, error.message); - // res.status(statusCode).send(error.message); - // } - // } - if (!listCache.has("facilityCodes")) { - //const codes = []; - try { const facilityCodesResponse = await axios.get( `${config.get("server:instituteAPIURL")}/institute/facility-codes`, @@ -216,6 +193,7 @@ async function createCache(req, res) { } ); listCache.set("facilityCodes", facilityCodesResponse.data); + log.info("cached facility codes - ", req.url); } catch (error) { const statusCode = error.response ? error.response.status : 500; log.error("Faility Code Caching Error", statusCode, error.message); @@ -223,8 +201,6 @@ async function createCache(req, res) { } } if (!listCache.has("districtAddresses")) { - //const codes = []; - try { const districtsResponse = await axios.get( `${config.get( @@ -274,6 +250,7 @@ async function createCache(req, res) { }); }); listCache.set("districtAddresses", districtsResponse.data.content); + log.info("cached district addresses - ", req.url); } catch (error) { const statusCode = error.response ? error.response.status : 500; log.error("District Code Caching Error", statusCode, error.message); @@ -283,6 +260,7 @@ async function createCache(req, res) { if (await !listCache.has("codesList")) { try { + log.info("Starting to get codes list"); //MOVE UNTIL I SEE IT const authorityContactTypeCodesResponse = await axios.get( `${config.get( "server:instituteAPIURL" @@ -324,21 +302,22 @@ async function createCache(req, res) { [{ fieldToRemove: "publiclyAvailable", value: false }] ), }; - res.json(codes); + // res.json(codes); listCache.set("codesList", { codesList: codes }); + log.info("cached codes list - ", req.url); } catch (error) { const statusCode = error.response ? error.response.status : 500; + log.error(e); log.error("getCodesList Error", statusCode, error.message); res.status(statusCode).send(error.message); } } + // res acts like a return res.status(200).json({ success: true }); } async function getContactTypeCodes(req, res) { if (await !listCache.has("codesList")) { - //const codes = []; - try { const authorityContactTypeCodesResponse = await axios.get( `${config.get( @@ -529,34 +508,33 @@ async function getAuthorityList(req, res) { res.json(authorityList); } } -// async function getCategoryCodes(req, res) { -// if (!listCache.has("categoryCodes")) { -// //const codes = []; - -// try { -// const categoryCodesResponse = await axios.get( -// `${config.get("server:instituteAPIURL")}/institute/category-codes`, -// { -// headers: { Authorization: `Bearer ${req.accessToken}` }, -// } -// ); +async function getCategoryCodes(req, res) { + if (!listCache.has("categoryCodes")) { + try { + const categoryCodesResponse = await axios.get( + `${config.get("server:instituteAPIURL")}/institute/category-codes`, + { + headers: { Authorization: `Bearer ${req.accessToken}` }, + } + ); -// categoryCodesResponse.data = filterRemoveByField( -// categoryCodesResponse.data, -// "schoolCategoryCode", -// ["FED_BAND", "POST_SEC", "YUKON"] -// ); -// listCache.set("categoryCodes", categoryCodesResponse.data); -// } catch (error) { -// const statusCode = error.response ? error.response.status : 500; -// log.error("Category Code Caching Error", statusCode, error.message); -// res.status(statusCode).send(error.message); -// } -// } else { -// const categoryCodes = await listCache.get("categoryCodes"); -// res.json(categoryCodes); -// } -// } + categoryCodesResponse.data = filterRemoveByField( + categoryCodesResponse.data, + "schoolCategoryCode", + ["FED_BAND", "POST_SEC", "YUKON"] + ); + listCache.set("categoryCodes", categoryCodesResponse.data); + res.json(categoryCodesResponse.data); + } catch (error) { + const statusCode = error.response ? error.response.status : 500; + log.error("Category Code Caching Error", statusCode, error.message); + res.status(statusCode).send(error.message); + } + } else { + const categoryCodes = await listCache.get("categoryCodes"); + res.json(categoryCodes); + } +} async function getSchoolList(req, res) { if (await !listCache.has("schoollist")) { const url = `${config.get("server:instituteAPIURL")}/institute/school`; // Update the URL according to your API endpoint @@ -625,7 +603,7 @@ async function getDistrictList(req, res) { }) .catch((e) => { log.error( - "getDistrictList Error", + "getDistrictList Error (getDistrictList)", e.response ? e.response.status : e.message ); }); diff --git a/frontend/src/App.vue b/frontend/src/App.vue index 64419e25..7cc84069 100644 --- a/frontend/src/App.vue +++ b/frontend/src/App.vue @@ -9,7 +9,7 @@ const data = ref([]) // Placeholder for the received data const appStore = useAppStore() onBeforeMount(async () => { - await appStore.setCodes() + await appStore.setCodes() //calls /create-cache await appStore.setDistricts() await appStore.setAuthorityList() await appStore.setSchoolList() diff --git a/frontend/src/services/InstituteService.ts b/frontend/src/services/InstituteService.ts index 75d823c1..fedcf26d 100644 --- a/frontend/src/services/InstituteService.ts +++ b/frontend/src/services/InstituteService.ts @@ -3,44 +3,44 @@ import { type AxiosResponse } from 'axios'; export default { // Districts - getDistricts(): Promise { + async getDistricts(): Promise { return ApiService.apiAxios.get('/api/v1/institute/district/list'); }, //DO NOT USE; TODO: Factor this out and use getDistrictView instead getDistrict(districtId: string): Promise { - return ApiService.apiAxios.get('/api/v1/institute/district/'+districtId); + return ApiService.apiAxios.get('/api/v1/institute/district/'+ districtId); }, // Independent Authorities - getAuthorityList(): Promise { + async getAuthorityList(): Promise { return ApiService.apiAxios.get('/api/v1/institute/authority/list'); }, - getAuthority(authorityId: string): Promise { + async getAuthority(authorityId: string): Promise { return ApiService.apiAxios.get('/api/v1/authority/'+ authorityId) }, // Schools - getSchoolList(): Promise { + async getSchoolList(): Promise { return ApiService.apiAxios.get('/api/v1/institute/school/list'); }, - getOffshoreSchoolList(): Promise { + async getOffshoreSchoolList(): Promise { return ApiService.apiAxios.get('/api/v1/institute/offshore-school/list'); }, - getSchool(schoolId: string): Promise { + async getSchool(schoolId: string): Promise { return ApiService.apiAxios.get('/api/v1/school/'+schoolId); }, // Codes - getFacilityCodes(): Promise { + async getFacilityCodes(): Promise { return ApiService.apiAxios.get('/api/v1/institute/facility-codes'); }, - getCategoryCodes(): Promise { + async getCategoryCodes(): Promise { return ApiService.apiAxios.get('/api/v1/institute/category-codes'); }, - getContactTypeCodes(): Promise { + async getContactTypeCodes(): Promise { return ApiService.apiAxios.get('/api/v1/institute/contact-type-codes'); }, - getGradeCodes(): Promise { + async getGradeCodes(): Promise { return ApiService.apiAxios.get('/api/v1/institute/grade-codes'); }, - getAddressTypeCodes(): Promise { + async getAddressTypeCodes(): Promise { return ApiService.apiAxios.get('/api/v1/institute/address-type-codes'); }, @@ -74,7 +74,7 @@ export default { getDistrictContactTypeCodes(): Promise { return ApiService.apiAxios.get('/api/v1/institute/district-contact-type-codes'); }, - loadCache(): Promise { + async loadCache(): Promise { return ApiService.apiAxios.get('/api/v1/institute/create-cache'); }, diff --git a/frontend/src/stores/app.ts b/frontend/src/stores/app.ts index e211ea4c..04165462 100644 --- a/frontend/src/stores/app.ts +++ b/frontend/src/stores/app.ts @@ -111,30 +111,30 @@ export const useAppStore = defineStore('app', { console.error("ERRPR LOADING CACHE" + error) }) // set category codes - // InstituteService.getCategoryCodes().then((response) => { - // const currentDate: Date = new Date() - // this.categoryCodes = response.data?.filter((item: any) => { - // const effectiveDate: Date = new Date(item.effectiveDate); - // const expiryDate: Date = new Date(item.expiryDate); - // return expiryDate >= currentDate && effectiveDate <= currentDate; - // }) - // //sort by display order - // this.categoryCodes?.sort((a: any, b: any) => { - // return a.displayOrder - b.displayOrder - // }) - // }).catch((error) => { - // console.error(error) - // }) + await InstituteService.getCategoryCodes().then((response) => { + const currentDate: Date = new Date() + this.categoryCodes = response.data?.filter((item: any) => { + const effectiveDate: Date = new Date(item.effectiveDate); + const expiryDate: Date = new Date(item.expiryDate); + return expiryDate >= currentDate && effectiveDate <= currentDate; + }) + //sort by display order + this.categoryCodes?.sort((a: any, b: any) => { + return a.displayOrder - b.displayOrder + }) + }).catch((error) => { + console.error(error) + }) // set facility type codes - InstituteService.getFacilityCodes().then((response) => { + await InstituteService.getFacilityCodes().then((response) => { this.facilityCodes = response.data }).catch((error) => { console.error(error) }) // set contact type codes for Districts, Authorities, and Schools - InstituteService.getContactTypeCodes().then((response) => { + await InstituteService.getContactTypeCodes().then((response) => { const currentDate: Date = new Date() @@ -178,13 +178,13 @@ export const useAppStore = defineStore('app', { }) // set address type codes for institute addresses - InstituteService.getAddressTypeCodes().then((response) => { + await InstituteService.getAddressTypeCodes().then((response) => { this.addressTypeCodes = response.data }).catch((error) => { console.error(error) }) - InstituteService.getGradeCodes().then((response) => { + await InstituteService.getGradeCodes().then((response) => { this.gradeCodes = response.data }).catch((error) => { console.error(error) diff --git a/frontend/src/views/AuthorityView.vue b/frontend/src/views/AuthorityView.vue index 34c20369..0c3cbb23 100644 --- a/frontend/src/views/AuthorityView.vue +++ b/frontend/src/views/AuthorityView.vue @@ -207,9 +207,11 @@ onMounted(async () => { :items="[ { title: 'Home', href: '/' }, 'Authority', - authority.value.authorityData?.authorityNumber + - ' ' + - authority.value.authorityData?.displayName + authority.value.authorityData + ? authority.value.authorityData.authorityNumber + + ' ' + + authority.value.authorityData.displayName + : '' ]" > @@ -313,7 +315,9 @@ onMounted(async () => { - - - - + + + + diff --git a/frontend/src/views/SchoolView.vue b/frontend/src/views/SchoolView.vue index 883df15c..c71a1edb 100644 --- a/frontend/src/views/SchoolView.vue +++ b/frontend/src/views/SchoolView.vue @@ -229,7 +229,7 @@ function goToDistrict() { :items="[ { title: 'Home', href: '/' }, 'School', - { title: schoolData?.value?.displayName, href: '' } + !!schoolData.value ? { title: schoolData.value.displayName, href: '' } : '' ]" > From 98cfe3027c00aca69d7f8edebc3b5893988bf121 Mon Sep 17 00:00:00 2001 From: suzalflueck Date: Thu, 23 May 2024 12:49:42 -0700 Subject: [PATCH 5/5] Remove comment block --- backend/src/routes/institute-router.js | 32 -------------------------- 1 file changed, 32 deletions(-) diff --git a/backend/src/routes/institute-router.js b/backend/src/routes/institute-router.js index 4fb888eb..fb7b4c2f 100644 --- a/backend/src/routes/institute-router.js +++ b/backend/src/routes/institute-router.js @@ -103,39 +103,7 @@ async function createCache(req, res) { const cachedFundingGroupList = await listCache.get("fundingGroups"); res.json(cachedFundingGroupList); } - // if (await !listCache.has("districtlist")) { - // const url = `${config.get("server:instituteAPIURL")}/institute/district`; // Update the URL according to your API endpoint - // axios - // .get(url, { headers: { Authorization: `Bearer ${req.accessToken}` } }) - // .then((response) => { - // const filteredNonbBCDistrictList = response.data.filter((district) => - // ["098", "102", "103"].includes(district.districtNumber) - // ); - // const filteredDistrictList = response.data.filter( - // (district) => !["098", "102", "103"].includes(district.districtNumber) - // ); - // const districtList = createList( - // filteredDistrictList, - // districtListOptions - // ); - // const nonBCdistrictList = createList( - // filteredNonbBCDistrictList, - // districtListOptions - // ); - // listCache.set("nonbcdistrictlist", nonBCdistrictList); - // listCache.set("districtlist", districtList); - // res.json(districtList); - // log.info("cached district list - ", req.url); - // }) - // .catch((e) => { - // log.error( - // "getDistrictList Error (createCache)", - // e.response ? e.response.status : e.message - // ); - // }); - // } - //TODO: Move to common function since this is same as getCategoryCodes() if (await !listCache.has("categoryCodes")) { try { const categoryCodesResponse = await axios.get(