diff --git a/components/Forms/BasicDetailsForm.js b/components/Forms/BasicDetailsForm.js index b509c506..5849a5eb 100644 --- a/components/Forms/BasicDetailsForm.js +++ b/components/Forms/BasicDetailsForm.js @@ -74,7 +74,7 @@ export function BasicDeatilsForm({ useGeoJSON, useGeoData }) { for (let item of Object.keys(formFields)) { facilityBasicDetails[item] = (item.includes('nhif_accreditation') || item.includes('reporting_in_dhis') || item.includes('accredited_lab_iso_15189')) - ? `${options['19']?.data[item]}` : options['19']?.data[item]; + ? `${options?.data[item]}` : options?.data[item]; } // State @@ -86,17 +86,17 @@ export function BasicDeatilsForm({ useGeoJSON, useGeoData }) { // const [subCountyOptions, setSubCountyOptions] = useState([]); const [isCountyOption, setIsCountyOption] = useState(false); - const { updatedSavedChanges, updateFacilityUpdateData } = options['19']?.data ? useContext(FacilityUpdatesContext) : {updatedSavedChanges: null, updateFacilityUpdateData: null } + const { updatedSavedChanges, updateFacilityUpdateData } = options?.data ? useContext(FacilityUpdatesContext) : {updatedSavedChanges: null, updateFacilityUpdateData: null } // Facility update data const [initialValues, handleFormUpdate] = useLocalStorageState({ - key: options['19']?.data ? 'basic_details_edit_form' : 'basic_details_form', - value: options['19']?.data ? facilityBasicDetails : formFields + key: options?.data ? 'basic_details_edit_form' : 'basic_details_form', + value: options?.data ? facilityBasicDetails : formFields }).actions.use(); - const formValues = options['19']?.data ? facilityBasicDetails : initialValues && initialValues.length > 1 ? JSON.parse(initialValues) : formFields + const formValues = options?.data ? facilityBasicDetails : initialValues && initialValues.length > 1 ? JSON.parse(initialValues) : formFields // Modify form values const [filteredOptions, setFilteredOptions] = useState({ @@ -124,7 +124,7 @@ export function BasicDeatilsForm({ useGeoJSON, useGeoData }) { const all_ftypes = [] - for (let type in f_types) all_ftypes.push(options['0']?.facility_types?.filter(({ sub_division }) => sub_division === f_types[type])) + for (let type in f_types) all_ftypes.push(options?.facility_types?.filter(({ sub_division }) => sub_division === f_types[type])) return all_ftypes.map(arr => { @@ -177,7 +177,7 @@ export function BasicDeatilsForm({ useGeoJSON, useGeoData }) { let i = 0; for (i = 0; i < f_types.length; i++) { - all_ftypes.push(options['0']?.facility_types.filter(({ sub_division }) => sub_division === f_types[i])) + all_ftypes.push(options?.facility_types.filter(({ sub_division }) => sub_division === f_types[i])) } @@ -261,21 +261,21 @@ export function BasicDeatilsForm({ useGeoJSON, useGeoData }) { setFilteredOptions((prev) => ({ ...prev, ownerTypeOptions: [ - options['2']?.owners.filter(({ label }) => label == "Private Practice- Pharmacist")[0] || {}, - options['2']?.owners.filter(({ label }) => label == "Private Practice - Private Company")[0] || {}, - options['2']?.owners.filter(({ label }) => label == "Private Practice Lab Technician/Technologist")[0] || {}, - options['2']?.owners.filter(({ label }) => label == "Private Practice - Nurse / Midwifery")[0] || {}, - options['2']?.owners.filter(({ label }) => label == "Private Practice - Medical Specialist")[0] || {}, - options['2']?.owners.filter(({ label }) => label == "Private Practice - General Practitioner")[0] || {}, - options['2']?.owners.filter(({ label }) => label == "Private Practice - Clinical Officer")[0] || {}, - options['2']?.owners.filter(({ label }) => label == "Private Practice - Private Institution Academic")[0] || {} + options || {}, + options || {}, + options || {}, + options || {}, + options || {}, + options || {}, + options || {}, + options || {} ] })) break; case own_types[1]: setFilteredOptions((prev) => ({ ...prev, - ownerTypeOptions: options['2']?.owners.filter(({ label }) => label == 'Non-Governmental Organizations') + ownerTypeOptions: options?.owners.filter(({ label }) => label == 'Non-Governmental Organizations') })) break; @@ -283,12 +283,12 @@ export function BasicDeatilsForm({ useGeoJSON, useGeoData }) { setFilteredOptions((prev) => ({ ...prev, ownerTypeOptions: [ - options['2']?.owners.filter(({ label }) => label == "Public Institution - Parastatal")[0] || {}, - options['2']?.owners.filter(({ label }) => label == 'Ministry of Health')[0] || {}, - options['2']?.owners.filter(({ label }) => label == 'Armed Forces')[0] || {}, - options['2']?.owners.filter(({ label }) => label == 'Kenya Police Service')[0] || {}, - options['2']?.owners.filter(({ label }) => label == 'National Youth Service')[0] || {}, - options['2']?.owners.filter(({ label }) => label == 'Prisons')[0] || {} + options || {}, + options || {}, + options || {}, + options || {}, + options || {}, + options || {} ] })) @@ -297,12 +297,12 @@ export function BasicDeatilsForm({ useGeoJSON, useGeoData }) { setFilteredOptions((prev) => ({ ...prev, ownerTypeOptions: [ - options['2']?.owners.filter(({ label }) => label == 'Seventh Day Adventist')[0] || {}, - options['2']?.owners.filter(({ label }) => label == 'Supreme Council for Kenya Muslims')[0] || {}, - options['2']?.owners.filter(({ label }) => label == 'Other Faith Based')[0] || {}, - options['2']?.owners.filter(({ label }) => label == 'Seventh Day Adventist')[0] || {}, - options['2']?.owners.filter(({ label }) => label == 'Kenya Episcopal Conference-Catholic Secretariat')[0] || {}, - options['2']?.owners.filter(({ label }) => label == 'Christian Health Association of Kenya')[0] || {}, + options || {}, + options || {}, + options || {}, + options || {}, + options || {}, + options || {}, ] })) break; @@ -322,8 +322,8 @@ export function BasicDeatilsForm({ useGeoJSON, useGeoData }) { official_name: string({ required_error: "Facility Official Name is required" }), name: string({ required_error: "Facility Unique Name is required" }), - facility_type: string({ required_error: "Facility Type is required" }).min(1), - facility_type_details: string({ required_error: "Facility Type Details is required" }).min(1), + facility_type: string({ required_error: "Facility Type is required" }), + facility_type_details: string({ required_error: "Facility Type Details is required" }), operation_status: string({ required_error: "Operation Status is required" }), date_established: string({ required_error: "Date established is required", @@ -358,39 +358,22 @@ export function BasicDeatilsForm({ useGeoJSON, useGeoData }) { const facilityTypeDetailsRef = useRef(null); const checkListFileRef = useRef(null); - if(options['19']?.data){ - formValues['facility_type'] = facilityTypeOptions.find(({label}) => label == options['19']?.data?.facility_type_parent)?.value - formValues['facility_type_details'] = filteredOptions.facilityTypeDetailOptions.find(({label}) => label == options['19']?.data?.facility_type_name)?.value + if(options?.data){ + formValues['facility_type'] = facilityTypeOptions.find(({label}) => label == options?.data?.facility_type_parent)?.value + formValues['facility_type_details'] = filteredOptions.facilityTypeDetailOptions.find(({label}) => label == options?.data?.facility_type_name)?.value // delete formValues['facility_checklist_document']; // formValues['facility_checklist_document'] = new File([],'Checklist File',undefined) } - - // console.log({formValues}) - -// const fetcher = url => { - -// fetch(url, { -// headers: { -// 'Authorization': `Bearer ${options['18']?.token ?? options['22']?.token }`, -// 'Accept': 'application/json', -// 'Content-Type': 'application/json, **/**' - -// } -// }) - -// } - - -// const {data:sub_counties, error} = useSWR(updateSubCountyOptions ? `${process.env.NEXT_PUBLIC_API_URL}/common/sub_counties/${formikState?.values.county_id}` : null, fetcher) + return ( options['19']?.data ? + onSubmit={(values) => options?.data ? // Update existing facility - handleBasicDetailsUpdates(options['22']?.token, values, facilityId, updatedSavedChanges) + handleBasicDetailsUpdates(options?.token, values, facilityId, updatedSavedChanges) .then((resp) => { defer(() => updatedSavedChanges(true)); @@ -403,7 +386,7 @@ export function BasicDeatilsForm({ useGeoJSON, useGeoData }) { `${process.env.NEXT_PUBLIC_API_URL}/facilities/facilities/${facilityId}/`, { headers: { - 'Authorization': 'Bearer ' + options['22']?.token, + 'Authorization': 'Bearer ' + options?.token, 'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/json;charset=utf-8' } @@ -420,7 +403,7 @@ export function BasicDeatilsForm({ useGeoJSON, useGeoData }) { `${process.env.NEXT_PUBLIC_API_URL}/facilities/facility_updates/${results?.latest_update}/`, { headers: { - 'Authorization': 'Bearer ' + options['22']?.token, + 'Authorization': 'Bearer ' + options?.token, 'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/json;charset=utf-8' } @@ -461,7 +444,7 @@ export function BasicDeatilsForm({ useGeoJSON, useGeoData }) { ) : // Post new facility - handleBasicDetailsSubmit(options['18']?.token, values, formId, setFormId, checkListFileRef.current, alert, setGeoJSON, setWardName, setGeoCenter, setFacilityId)} + handleBasicDetailsSubmit(options?.token, values, formId, setFormId, checkListFileRef.current, alert, setGeoJSON, setWardName, setGeoCenter, setFacilityId)} validationSchema={toFormikValidationSchema(formSchema)} enableReinitialize > @@ -471,29 +454,25 @@ export function BasicDeatilsForm({ useGeoJSON, useGeoData }) { const errors = formikState.errors; - const fetcher = (url, token) => { + // const fetcher = (url, token) => { - fetch(url, { - mode:'no-cors', - headers: { - 'Authorization': `Bearer ${token}`, - 'Accept': 'application/json, text/plain, */*', - 'Content-Type': 'application/json;charset=utf-8' - - } - }) + // fetch(url, { + // mode:'no-cors', + // headers: { + // 'Authorization': `Bearer ${token}`, + // 'Accept': 'application/json, text/plain, */*', + // 'Content-Type': 'application/json;charset=utf-8' - } - - - // const {data:sub_counties, error} = useSWR(isCountyOption ? [`${process.env.NEXT_PUBLIC_API_URL}/common/sub_counties/${formikState?.values.county_id}`, options['18']?.token ?? options['22']?.token ] : null, fetcher) + // } + // }) + // } //Effects useEffect(() => { - if(!options['19']?.data){ + if(!options?.data){ handleFormUpdate(JSON.stringify(formikState?.values)) } @@ -512,17 +491,6 @@ export function BasicDeatilsForm({ useGeoJSON, useGeoData }) { // Form Validations - // if(formikState?.values?.facility_type !== ""){ - - - // const facilityTypeDetails = options['1']?.facility_type_details?.find( - // ({ value }) => value.includes(formikState?.values?.facility_type) - // )?.value ?? " "; - - - // // console.log({facilityTypeDetails}) - // } - // Hours/Days duration form rules if (formikState?.values?.open_whole_day) { formikState?.values?.open_late_night = true; @@ -551,8 +519,8 @@ export function BasicDeatilsForm({ useGeoJSON, useGeoData }) { if (formikState?.values?.facility_type !== "") setFacilityTypeValue(formikState?.values?.facility_type) - if (formikState?.values?.owner_type !== "" && options['3']?.owner_types ) setOwnerTypeLabel(() => { - return options['3']?.owner_types?.filter(({ value }) => value === formikState?.values?.owner_type)[0]?.label + if (formikState?.values?.owner_type !== "" && options?.owner_types ) setOwnerTypeLabel(() => { + return options?.label }) // if owner == 'armed forces' then check the facility classified field @@ -566,58 +534,58 @@ export function BasicDeatilsForm({ useGeoJSON, useGeoData }) { switch (formikState?.values?.facility_type) { // STAND ALONE case '85f2099b-a2f8-49f4-9798-0cb48c0875ff': - formikState?.values?.keph_level = options['4']?.keph.find(({ label }) => label === 'Level 2')?.value; + formikState?.values?.keph_level = options?.keph.find(({ label }) => label === 'Level 2')?.value; break; // DISPENSARY case '87626d3d-fd19-49d9-98da-daca4afe85bf': - formikState?.values?.keph_level = options['4']?.keph.find(({ label }) => label === 'Level 2')?.value + formikState?.values?.keph_level = options?.keph.find(({ label }) => label === 'Level 2')?.value break; // MEDICAL CLINIC case '8949eeb0-40b1-43d4-a38d-5d4933dc209f': - formikState?.values?.keph_level = options['4']?.keph.find(({ label }) => label === 'Level 2')?.value + formikState?.values?.keph_level = options?.keph.find(({ label }) => label === 'Level 2')?.value break; // NURSING HOME case '0b7f9699-6024-4813-8801-38f188c834f5': - formikState?.values?.keph_level = options['4']?.keph.find(({ label }) => label === 'Level 3')?.value + formikState?.values?.keph_level = options?.keph.find(({ label }) => label === 'Level 3')?.value break; // HEALTH CENTER case '9ad22615-48f2-47b3-8241-4355bb7db835': - formikState?.values?.keph_level = options['4']?.keph.find(({ label }) => label === 'Level 3')?.value + formikState?.values?.keph_level = options?.keph.find(({ label }) => label === 'Level 3')?.value break; // MEDICAL CENTER case 'df69577d-b90f-4b66-920a-d0f3ecd95191': - formikState?.values?.keph_level = options['4']?.keph.find(({ label }) => label === 'Level 3')?.value + formikState?.values?.keph_level = options?.keph.find(({ label }) => label === 'Level 3')?.value break; // HOSIPTALS case '1f1e3389-f13f-44b5-a48e-c1d2b822e5b5': // Comprehensive Teaching & Tertiary Referral Hospital if (formikState?.values?.facility_type_details === 'b9a51572-c931-4cc5-8e21-f17b22b0fd20') { - formikState?.values?.keph_level = options['4']?.keph.find(({ label }) => label === 'Level 6')?.value + formikState?.values?.keph_level = options?.keph.find(({ label }) => label === 'Level 6')?.value break; } // Specialized & Tertiary Referral hospitals if (formikState?.values?.facility_type_details === '52ccbc58-2a71-4a66-be40-3cd72e67f798') { - formikState?.values?.keph_level = options['4']?.keph.find(({ label }) => label === 'Level 6')?.value + formikState?.values?.keph_level = options?.keph.find(({ label }) => label === 'Level 6')?.value break; } // Secondary care hospitals if (formikState?.values?.facility_type_details === 'f222bab7-589c-4ba8-bd9a-fe6c96fcd085') { - formikState?.values?.keph_level = options['4']?.keph.find(({ label }) => label === 'Level 5')?.value + formikState?.values?.keph_level = options?.keph.find(({ label }) => label === 'Level 5')?.value break; } // Primary care hospitals if (formikState?.values?.facility_type_details === '0fa47f39-d58e-4a16-845c-82818719188d') { - formikState?.values?.keph_level = options['4']?.keph.find(({ label }) => label === 'Level 4')?.value + formikState?.values?.keph_level = options?.keph.find(({ label }) => label === 'Level 4')?.value break; } @@ -670,7 +638,7 @@ export function BasicDeatilsForm({ useGeoJSON, useGeoData }) { {/* Facility Type */} -
+
{/* Facility Type Details */} -
+
@@ -157,7 +162,7 @@ export default function EditFacility(props) {
@@ -187,7 +192,7 @@ export default function EditFacility(props) { EditFacility.getInitialProps = async (ctx) => { - const allOptions = [] + // const allOptions = [] const options = [ 'facility_types', @@ -212,7 +217,7 @@ EditFacility.getInitialProps = async (ctx) => { 'facility_data' ] - + const allOptions = {}; return checkToken(ctx.req, ctx.res) .then(async (t) => { @@ -231,26 +236,26 @@ EditFacility.getInitialProps = async (ctx) => { try { - const _data = await fetch(url, { + const _facilityTypeData = await fetch(url, { headers: { Authorization: 'Bearer ' + token, Accept: 'application/json', }, }) - // let results = (await _data.json()).results.map(({id, sub_division, name }) => sub_division ? {value:id, label:sub_division} : {value:id, label:name}) + if(!_facilityTypeData) throw Error('Unable facility type data') + + const facilityTypeData = (await _facilityTypeData.json())?.results - allOptions.push({ facility_types: (await _data.json()).results }) + + allOptions['facility_types'] = facilityTypeData; + } catch (err) { - console.log(`Error fetching ${option}: `, err); - allOptions.push({ - error: true, - err: err, - facility_types: [], - }); + console.error(`Error fetching ${option}: `, err); + } break; @@ -259,26 +264,26 @@ EditFacility.getInitialProps = async (ctx) => { try { - const _data = await fetch(url, { + const _facilityTypeDetails = await fetch(url, { headers: { Authorization: 'Bearer ' + token, Accept: 'application/json', }, }) + + if (!_facilityTypeDetails) throw Error("Unable to fetch facility type details") - let _results = (await _data.json()).results.map(({ id, name }) => ({ value: id, label: name })) - allOptions.push({ facility_type_details: _results }) + const facilityTypeDetails = (await _facilityTypeDetails.json()).results.map(({ id, name }) => ({ value: id, label: name })) + + + allOptions['facility_type_details'] = facilityTypeDetails; } catch (err) { - console.log(`Error fetching ${option}: `, err); - allOptions.push({ - error: true, - err: err, - facility_types: [], - }); + console.error(`Error fetching ${option}: `, err); + } break; case 'owners': @@ -287,23 +292,23 @@ EditFacility.getInitialProps = async (ctx) => { try { - const _data = await fetch(url, { + const _owners = await fetch(url, { headers: { Authorization: 'Bearer ' + token, Accept: 'application/json', }, }) - allOptions.push({ owners: (await _data.json()).results.map(({ id, name }) => ({ value: id, label: name })) }) + if(!_owners) throw new Error('Unable to fetch owners') + + const owners = (await _owners.json())?.results + + allOptions['owners'] = owners } catch (err) { - console.log(`Error fetching ${option}: `, err); - allOptions.push({ - error: true, - err: err, - owners: [], - }); + console.error(`Error fetching ${option}: `, err); + } break; @@ -313,23 +318,25 @@ EditFacility.getInitialProps = async (ctx) => { try { - const _data = await fetch(url, { + const _owner_types = await fetch(url, { headers: { Authorization: 'Bearer ' + token, Accept: 'application/json', }, }) - allOptions.push({ owner_types: (await _data.json()).results.map(({ id, name }) => ({ value: id, label: name })) }) + if(!_owner_types) throw Error('Unable to fetch owner types') + + const owner_types = await _owner_types.json() + + + allOptions["owner_types"] = (await owner_types).results.map(({ id, name }) => ({ value: id, label: name })) + } catch (err) { - console.log(`Error fetching ${option}: `, err); - allOptions.push({ - error: true, - err: err, - owner_types: [], - }) + console.error(`Error fetching ${option}: `, err); + } break; @@ -338,24 +345,24 @@ EditFacility.getInitialProps = async (ctx) => { try { - - const _data = await fetch(url, { + const _keph = await fetch(url, { headers: { Authorization: 'Bearer ' + token, Accept: 'application/json', }, }) - allOptions.push({ keph: (await _data.json()).results.map(({ id, name }) => ({ value: id, label: name })) }) + if(!_keph) throw Error('Unable to fetch keph') + + const keph = (await _keph.json()).results.map(({ id, name }) => ({ value: id, label: name })) + + + allOptions["keph"] = keph } catch (err) { - console.log(`Error fetching ${option}: `, err); - allOptions.push({ - error: true, - err: err, - keph: [], - }) + console.error(`Error fetching ${option}: `, err); + } break; @@ -365,23 +372,24 @@ EditFacility.getInitialProps = async (ctx) => { try { - const _data = await fetch(url, { + const _facility_admission_status = await fetch(url, { headers: { Authorization: 'Bearer ' + token, Accept: 'application/json', }, }) - allOptions.push({ facility_admission_status: (await _data.json()).results.map(({ id, name }) => ({ value: id, label: name })) }) + if(!_facility_admission_status) throw Error('Unabe to fetch Faility type details') + + const facility_admission_status = (await _facility_admission_status.json()).results.map(({ id, name }) => ({ value: id, label: name })) + + + allOptions["facility_admission_status"] = facility_admission_status } catch (err) { - console.log(`Error fetching ${option}: `, err); - allOptions.push({ - error: true, - err: err, - facility_admission_status: [], - }) + console.error(`Error fetching ${option}: `, err); + } break; case 'job_titles': @@ -390,23 +398,24 @@ EditFacility.getInitialProps = async (ctx) => { try { - const _data = await fetch(url, { + const _job_titles = await fetch(url, { headers: { Authorization: 'Bearer ' + token, Accept: 'application/json', }, }) - allOptions.push({ job_titles: (await _data.json()).results.map(({ id, name }) => ({ value: id, label: name })) }) + if(!_job_titles) throw Error('Unable to fetch job titles') + + const job_titles = (await _job_titles.json()).results.map(({ id, name }) => ({ value: id, label: name })) + + + allOptions["job_titles"] = job_titles } catch (err) { - console.log(`Error fetching ${option}: `, err); - allOptions.push({ - error: true, - err: err, - facility_admission_status: [], - }) + console.error(`Error fetching ${option}: `, err); + } break; case 'contact_types': @@ -415,23 +424,23 @@ EditFacility.getInitialProps = async (ctx) => { try { - const _data = await fetch(url, { + const _contact_types = await fetch(url, { headers: { Authorization: 'Bearer ' + token, Accept: 'application/json', }, }) - allOptions.push({ contact_types: (await _data.json()).results.map(({ id, name }) => ({ value: id, label: name })) }) + if(!_contact_types) Error("Unable to Contact Types") + + const contact_types = (await _contact_types.json()).results.map(({ id, name }) => ({ value: id, label: name })) + + allOptions["contact_types"] = contact_types } catch (err) { - console.log(`Error fetching ${option}: `, err); - allOptions.push({ - error: true, - err: err, - facility_admission_status: [], - }) + console.error(`Error fetching ${option}: `, err); + } break; case 'facility_depts': @@ -440,23 +449,23 @@ EditFacility.getInitialProps = async (ctx) => { try { - const _data = await fetch(url, { + const _faciilty_depts = await fetch(url, { headers: { Authorization: 'Bearer ' + token, Accept: 'application/json', }, }) - allOptions.push({ facility_depts: (await _data.json()).results.map(({ id, name, regulatory_body_name }) => ({ value: id, label: name, reg_body_name: regulatory_body_name })) }) + if(!_faciilty_depts) throw Error("Unable to fetch facility Departments") + + const facility_depts = (await _faciilty_depts.json()).results.map(({ id, name, regulatory_body_name }) => ({ value: id, label: name, reg_body_name: regulatory_body_name })) + + allOptions["facility_depts"] = facility_depts } catch (err) { - console.log(`Error fetching ${option}: `, err); - allOptions.push({ - error: true, - err: err, - facility_depts: [], - }) + console.error(`Error fetching ${option}: `, err); + } break; case 'regulating_bodies': @@ -465,23 +474,24 @@ EditFacility.getInitialProps = async (ctx) => { try { - const _data = await fetch(url, { + const _regulating_bodies = await fetch(url, { + headers: { Authorization: 'Bearer ' + token, Accept: 'application/json', }, }) - allOptions.push({ regulating_bodies: (await _data.json()).results.map(({ id, name }) => ({ value: id, label: name })) }) + if(!_regulating_bodies) throw Error("Unable to fetch reguating bodies") + + const regulating_bodies = (await _regulating_bodies.json()).results.map(({ id, name }) => ({ value: id, label: name })) + + allOptions["regulating_bodies"] = regulating_bodies } catch (err) { console.log(`Error fetching ${option}: `, err); - allOptions.push({ - error: true, - err: err, - regulating_bodies: [], - }) + } break; case 'regulation_status': @@ -490,23 +500,23 @@ EditFacility.getInitialProps = async (ctx) => { try { - const _data = await fetch(url, { + const _regulation_status = await fetch(url, { headers: { Authorization: 'Bearer ' + token, Accept: 'application/json', }, }) - allOptions.push({ regulation_status: (await _data.json()).results.map(({ id, name }) => ({ value: id, label: name })) }) + if(!_regulation_status) throw Error("Unable to fetch Regulation Status") + + const regulation_status = (await _regulation_status.json()).results.map(({ id, name }) => ({ value: id, label: name })) + + allOptions["regulation_status"] = regulation_status } catch (err) { - console.log(`Error fetching ${option}: `, err); - allOptions.push({ - error: true, - err: err, - regulation_status: [], - }) + console.error(`Error fetching ${option}: `, err); + } break; case 'services': @@ -515,23 +525,23 @@ EditFacility.getInitialProps = async (ctx) => { try { - const _data = await fetch(url, { + const _services = await fetch(url, { headers: { Authorization: 'Bearer ' + token, Accept: 'application/json', } }) - allOptions.push({ service: (await _data.json()).results.map(({ id, name, category, category_name }) => ({ id, name, category, category_name })) }) + if(!_services) throw Error("Unable to fetch services") + + const services = (await _services.json()).results.map(({ id, name, category, category_name }) => ({ id, name, category, category_name })) + + allOptions["services"] = services } catch (err) { - console.log(`Error fetching ${option}: `, err); - allOptions.push({ - error: true, - err: err, - service: [], - }) + console.error(`Error fetching ${option}: `, err); + } break; @@ -541,23 +551,23 @@ EditFacility.getInitialProps = async (ctx) => { try { - const _data = await fetch(url, { + const _infrastructure = await fetch(url, { headers: { Authorization: 'Bearer ' + token, Accept: 'application/json', } }) - allOptions.push({ infrastructure: (await _data.json()).results.map(({ id, name, category_name, category }) => ({ id, name, category_name, category })) }) + if(!_infrastructure) throw Error("Unable to fetch infrstructure") + + const infrastructure = (await _infrastructure.json()).results.map(({ id, name, category_name, category }) => ({ id, name, category_name, category })) + + allOptions["infrastructure"] = infrastructure } catch (err) { console.log(`Error fetching ${option}: `, err); - allOptions.push({ - error: true, - err: err, - service: [], - }) + } break; @@ -566,29 +576,29 @@ EditFacility.getInitialProps = async (ctx) => { try { - const _data = await fetch(url, { + const _specialities = await fetch(url, { headers: { Authorization: 'Bearer ' + token, Accept: 'application/json', } }) - allOptions.push({ hr: (await _data.json()).results.map(({ id, name, category_name, category }) => ({ id, name, category_name, category })) }) + if(!_specialities) throw Error("Unable to fetch specialities") + + const specialities = (await _specialities.json()).results.map(({ id, name, category_name, category }) => ({ id, name, category_name, category })) + + allOptions["hr"] = specialities } catch (err) { console.log(`Error fetching ${option}: `, err); - allOptions.push({ - error: true, - err: err, - service: [], - }) + } break; case "collection_date": try { - const response = await fetch( + const _collection_date = await fetch( `${process.env.NEXT_PUBLIC_API_URL}/gis/facility_coordinates/?facility=${ctx.query.id}&format=json`, { headers: { @@ -599,24 +609,19 @@ EditFacility.getInitialProps = async (ctx) => { ); - const [_result] = (await response.json()).results; + const [_result] = (await _collection_date.json()).results; - allOptions.push({ - collection_date: _result["collection_date"], - }); + allOptions["collection_date"] = _result["collection_date"]; + } catch (err) { - console.log(`Error fetching ${option}: `, err); - allOptions.push({ - error: true, - err: err.message, - collection_date: null, - }); + console.error(`Error fetching ${option}: `, err); + } break; case "facility_data": try { - const _data = await fetch( + const _facility_data = await fetch( `${process.env.NEXT_PUBLIC_API_URL}/facilities/facilities/${ctx.query.id}/?format=json`, { headers: { @@ -626,13 +631,22 @@ EditFacility.getInitialProps = async (ctx) => { } ); + + const facilityData = await _facility_data.json() - allOptions.push({ data: await _data.json() }); + // console.log({facilityData: facilityData?.ward}) + + + if (facilityData) { + + allOptions['data'] = facilityData; - if (_data) { try { + + + const response = await fetch( - `${process.env.NEXT_PUBLIC_API_URL}/common/wards/${allOptions[19]?.data?.ward}/?format=json`, + `${process.env.NEXT_PUBLIC_API_URL}/common/wards/${facilityData?.ward}/?format=json`, { headers: { Authorization: 'Bearer ' + token, @@ -641,24 +655,27 @@ EditFacility.getInitialProps = async (ctx) => { } ); - const _data = await response.json(); + const wardData = await response.json(); + + if(wardData){ const [lng, lat] = - _data?.ward_boundary.properties.center.coordinates; + wardData?.ward_boundary.properties.center.coordinates; - allOptions.push({ - geolocation: { - geoJSON: JSON.parse(JSON.stringify(_data?.ward_boundary)), + allOptions["geolocation"] = { + geoJSON: JSON.parse(JSON.stringify(wardData?.ward_boundary)), centerCoordinates: JSON.parse( JSON.stringify([lat, lng]) ) - }, - }); + } + + + } - if (_data) { + try { const response = await fetch( - `${process.env.NEXT_PUBLIC_API_URL}/facilities/facility_regulation_status/?facility=${allOptions[19]?.data?.id}/?format=json`, + `${process.env.NEXT_PUBLIC_API_URL}/facilities/facility_regulation_status/?facility=${facilityData?.id}/?format=json`, { headers: { Authorization: 'Bearer ' + token, @@ -666,42 +683,30 @@ EditFacility.getInitialProps = async (ctx) => { } } ); - const _data = await response.json(); - - allOptions.push({ - facility_regulation_status: (await _data).results, - }); + const regulationData = await response.json(); + + if (regulationData) { + allOptions['facility_regulation_status'] = (await regulationData).results + + } } catch (err) { console.log(`Error fetching ${option}: `, err); - allOptions.push({ - error: true, - err: err.message, - facility_regulation_status: null, - }); + } - } + } catch (err) { console.log(`Error fetching ${option}: `, err); - allOptions.push({ - error: true, - err: err.message, - geolocation: null, - }); + } } } catch (err) { console.log(`Error fetching ${option}: `, err); - allOptions.push({ - error: true, - err: err.message, - data: null, - }); + } break; default: let fields = '' - let _obj = {} if (option === 'counties') fields = 'id,name&page_size=47' if (option === 'sub_counties') fields = 'id,name,county&page_size=312' @@ -721,20 +726,11 @@ EditFacility.getInitialProps = async (ctx) => { }, }) - _obj[option] = (await _data.json()).results.map(({ id, name }) => ({ value: id, label: name })) - - - allOptions.push(_obj) - - + allOptions[option] = (await _data.json())?.results.map(({ id, name }) => ({ value: id, label: name })) } catch (err) { console.log(`Error fetching ${option}: `, err); - allOptions.push({ - error: true, - err: err, - data: [] - }); + } break; @@ -742,11 +738,11 @@ EditFacility.getInitialProps = async (ctx) => { } - allOptions.push({ - token - }) + allOptions["token"] = token + - return allOptions + console.log("allOptions Log", allOptions) + return allOptions } diff --git a/public/USAID.png b/public/USAID.png new file mode 100644 index 00000000..2da8fa56 Binary files /dev/null and b/public/USAID.png differ diff --git a/public/healthit.png b/public/healthit.png new file mode 100644 index 00000000..8e7d65b2 Binary files /dev/null and b/public/healthit.png differ diff --git a/public/moh-logo.png b/public/moh-logo.png new file mode 100644 index 00000000..c227da96 Binary files /dev/null and b/public/moh-logo.png differ