Skip to content

Commit

Permalink
Merge pull request #449 from ertush/hotfix
Browse files Browse the repository at this point in the history
Updated approveCHUUpdates function
  • Loading branch information
ertush authored Aug 12, 2024
2 parents 6efbe2c + 9710125 commit 4f9aa50
Show file tree
Hide file tree
Showing 4 changed files with 68 additions and 129 deletions.
74 changes: 5 additions & 69 deletions pages/_app.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,10 @@ import Backdrop from '@mui/material/Backdrop';
import CircularProgress from '@mui/material/CircularProgress';
import { useEffect, useState } from 'react';
// import { getUserDetails } from "../controllers/auth/public_auth";
import { SWRConfig } from 'swr'
import { IsUserLoggedInCtx } from '.';

function LoadAnimation({open}) {
function LoadAnimation({open}) {
return (
<Backdrop
sx={{ color: '#fff', zIndex: (theme) => theme.zIndex.drawer + 1 }}
Expand Down Expand Up @@ -52,76 +53,9 @@ export default function App(props) {
router.events.on('routeChangeError', () => {setIsNavigating(false)});


// if(Number(userID) !== 6) {
// // window.localStorage.removeItem('user')
// // window.localStorage.clear()
// router.push('/logout')

// }

let mtd = true;


// function initializePage() {

// const API_URL = process.env.NEXT_PUBLIC_API_URL;

// console.log(router.asPath)

if (mtd) {

// console.log(' Checking if user is logged in ..')

// if (typeof window !== "undefined") {


// }

// (typeof window !== "undefined" && window.document.cookie.indexOf("access_token=") > -1) || false;


// let session_token = null;

// if (is_user_logged_in) {
// session_token = JSON.parse(
// window.document.cookie.split("access_token=")[1].split(";")[0]
// );
// }

// if (
// // !is_user_logged_in
// typeof window == "undefined" &&
// session_token == null

// ) {
// console.log('Fetching User....')
// getUserDetails(session_token.token, `${API_URL}/rest-auth/user/`).then(
// (usr) => {

// if (usr.error || usr.detail) {
// setIsLoggedIn(false);
// setUser(null);
// } else {

// if(usr.type !== undefined) {
// console.log({usr})
// usr.type == 6 ? setIsLoggedIn(false) : setIsLoggedIn(true);
// }

// setUser(usr);

// }
// }
// );
// } else {

// console.log("no session. Refreshing...");
// // router.push('/auth/login')
// }
}
// }

// initializePage()

// Logout after 30 mins of inactivity
const time = 60 * 1000 * 30
Expand Down Expand Up @@ -189,7 +123,9 @@ export default function App(props) {
{
isNavigating && <LoadAnimation open={true} />
}
<Component {...pageProps} />
<SWRConfig value={{ provider: () => new Map() }}></SWRConfig>
<Component {...pageProps} />
<SWRConfig />

</PermissionContext.Provider>

Expand Down
90 changes: 49 additions & 41 deletions pages/community-units/approve/[id].js
Original file line number Diff line number Diff line change
Expand Up @@ -36,31 +36,31 @@ function ApproveCommunityUnit(props) {


const columns = [
{ label: 'Field', minWidth: 100 },
{ label: 'Old Value', minWidth: 100 },
{ label: 'New Value', minWidth: 100, }
{ label: 'Field', minWidth: 100, id: uuid()},
{ label: 'Old Value', minWidth: 100, id: uuid() },
{ label: 'New Value', minWidth: 100, id: uuid()}
];

const CHULDetails = [
{ value: `${cu.facility_subcounty}`, label: 'Sub County ' },
{ value: `${cu.facility_constituency}`, label: 'Constituency' },
{ value: `${cu.facility_ward}`, label: 'Ward' },
{ value: `${cu.households_monitored}`, label: 'Households Monitored' },
{ value: `${cu.facility_subcounty}`, label: 'Sub County ', id: uuid()},
{ value: `${cu.facility_constituency}`, label: 'Constituency', id: uuid() },
{ value: `${cu.facility_ward}`, label: 'Ward', id: uuid() },
{ value: `${cu.households_monitored}`, label: 'Households Monitored', id: uuid() },
];

const CHU_MainDetails = [
{ value: `${cu.status_name}`, label: 'Functional Status' },
{ value: `${cu.code}`, label: 'CHU Code' },
{ value: `${cu.number_of_chvs}`, label: 'Number of CHVs' },
{ value: `${cu.facility_name}`, label: 'Linked Facility' },
{ value: `${cu.facility_county}`, label: 'County' },
{ value: `${cu.status_name}`, label: 'Functional Status', id: uuid()},
{ value: `${cu.code}`, label: 'CHU Code', id: uuid()},
{ value: `${cu.number_of_chvs}`, label: 'Number of CHVs', id: uuid() },
{ value: `${cu.facility_name}`, label: 'Linked Facility', id: uuid() },
{ value: `${cu.facility_county}`, label: 'County', id: uuid() },
]



function approveCHU (e, token) {

e.preventDefault();



if (e.target.name == 'btn_approve_chu') setIsSubmittingApproval(true);
Expand Down Expand Up @@ -118,16 +118,19 @@ function ApproveCommunityUnit(props) {
alert.error(`Unable to approve CHU`)

const detail = await res.json()

const error = Object.entries(detail)?.map(([k, v]) => ([k, v]))?.join(":")

if(error) throw new Error(error.replace(',', ':'))

const error = Array.isArray(Object.values(detail)) && Object.values(detail).length == 1 ? detail[Object.keys(detail)[0]][0] : ''
setFormError(error)
// const error = Array.isArray(Object.values(detail)) && Object.values(detail).length == 1 ? detail[Object.keys(detail)[0]][0] : ''

}


})
.catch(e => {

setFormError(e.message)
console.error(e.message)
})
.finally(() => {
Expand All @@ -144,6 +147,10 @@ async function approveCHUUpdates (e, token) {
e.preventDefault();

// console.log({status})

console.log(formError)


let payload = ''
if (e.target.name == 'btn_approve_chu_updates') {
setIsSubmittingApproval(true)
Expand All @@ -166,10 +173,12 @@ async function approveCHUUpdates (e, token) {
method: 'PATCH',
body: JSON.stringify(payload)
})
.then(resp => resp.json())
.then(async (res) => {
.then(resp => ({resp, data: resp.json()}))
.then(async ({resp, data}) => {


if(resp.ok) {

if(res.ok) {
alert.success(`${payload.is_rejected ? 'Rejected' : 'Approved'} CHU Updates successfully`)

router.push({
Expand All @@ -180,17 +189,17 @@ async function approveCHUUpdates (e, token) {
} else {
alert.error(`Unable to approve CHU Updates`)

const detail = await res.json()
const error = Array.isArray(Object.values(detail)) && Object.values(detail).length == 1 ? detail[Object.keys(detail)[0]][0] : ''
setFormError(error)
const detail = await data

const error = Object.entries(detail)?.map(([k, v]) => ([k, v]))?.join(":")

if(error) throw new Error(error.replace(',', ':'))

}

})
.catch(e => {
console.log(e.message)
setFormError(e.message)
})
} catch (e) {

Expand Down Expand Up @@ -317,17 +326,16 @@ async function approveCHUUpdates (e, token) {

{/* CHU details */}
<div className="bg-gray-50 shadow-lg border border-gray-300/70 w-full p-3 flex flex-col gap-3 mt-4">
{CHU_MainDetails.map((dt) => {

const id = uuid()
{CHU_MainDetails.map(({label, value, id}) => {

return (

<div key={id} className="grid grid-cols-3 w-full md:w-11/12 leading-none items-center">
<label className="col-span-1 text-gray-600">
{dt.label}
{label}
</label>
<p className="col-span-2 text-black font-medium text-base">
{dt.value || " - "}
{value || " - "}
</p>
</div>
)})}
Expand Down Expand Up @@ -370,14 +378,13 @@ async function approveCHUUpdates (e, token) {

{!isCHULDetails && (
<div className="bg-gray-50 shadow-lg border border-gray-300/70 w-full p-3 flex flex-col gap-3 mt-6">
{CHULDetails.map((dt) => {
const id = uuid()

{CHULDetails.map(({label, value, id}) => {

return (
<div key={id} className="grid grid-cols-3 w-full md:w-11/12 leading-none items-center">
<label className="col-span-1 text-gray-600">{dt.label}</label>
<label className="col-span-1 text-gray-600">{label}</label>
<p className="col-span-2 text-black font-medium text-base">
{dt.value || " - "}
{value || " - "}
</p>
</div>
)})}
Expand All @@ -397,6 +404,9 @@ async function approveCHUUpdates (e, token) {
<h3 className="text-gray-900 font-semibold leading-16 text-medium">
Pending Updates
</h3>

{formError && <Alert severity="error" sx={{ width: '100%', marginY: '15px' }}>{formError}</Alert>}

<form
className="space-y-3"
name="chu_approve_reject_updates"
Expand All @@ -418,11 +428,9 @@ async function approveCHUUpdates (e, token) {
<TableRow >
{columns.map((column) => {

const id = uuid()

return (
<TableCell
key={id}
key={column.id}
align={column.align}
style={{ minWidth: column.minWidth, fontWeight: 600 }}
>
Expand Down Expand Up @@ -558,9 +566,9 @@ async function approveCHUUpdates (e, token) {
}
if (key == 'workers') {
const workers = cu.pending_updates['workers'].map((item) => {
const id = uuid()
// const id = uuid()

return <div className='col-span-4 w-full h-auto ml-7 mt-2' key={id}>
return <div className='col-span-4 w-full h-auto ml-7 mt-2' key={item.id}>
<div className='grid grid-cols-2 w-full'>
<p className='col-span-2 text-gray-600 font-medium text-base'>{item.first_name} {' '} {item.last_name} {'(In Charge)'}</p>
</div>
Expand Down Expand Up @@ -625,7 +633,7 @@ async function approveCHUUpdates (e, token) {
<div className="bg-gray-50 shadow-lg border border-gray-300/70 w-full p-3 flex flex-col gap-3 mt-6">
<h3 className="text-gray-900 font-semibold leading-16 text-medium">Approval comment: </h3>
{/* {cu.is_approved} */}
{formError && <Alert severity="error" sx={{ width: '100%', marginY: '15px' }}>{formError}</Alert>}
{formError !== null && <Alert severity="error" sx={{ width: '100%', marginY: '15px' }}>{formError}</Alert>}
<form
className="space-y-3"
name="chu_approve_reject_form"
Expand Down
2 changes: 1 addition & 1 deletion pages/dashboard/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -1455,7 +1455,7 @@ export async function getServerSideProps(ctx) {

const dashboard = await fetchDashboardData(token)

console.log({dashboard: dashboard?.data})
// console.log({dashboard: dashboard?.data})

if (dashboard?.data) { // console.log({ft, query})
return {
Expand Down
31 changes: 13 additions & 18 deletions pages/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ function Home() {

const router = useRouter()

// const [_, setUser] = useState(null);

const [isClient, setIsClient] = useState(null);
const [searchOption, setSearchOption] = useState('Facilities');
const [isContacts, setIsContacts] = useState(false)
Expand All @@ -62,27 +62,22 @@ function Home() {

setIsClient(true)

// if(userID !== 6){
// router.push('/dashboard')
// }


}, []);



function animateValue(event, start, end, duration) {
let startTimestamp = null;
const step = (timestamp) => {
if (!startTimestamp) startTimestamp = timestamp;
const progress = Math.min((timestamp - startTimestamp) / duration, 1);
event.target.innerHTML = Math.floor(progress * (end - start) + start);
if (progress < 1) {
window.requestAnimationFrame(step);
}
};
window.requestAnimationFrame(step);
}
// function animateValue(event, start, end, duration) {
// let startTimestamp = null;
// const step = (timestamp) => {
// if (!startTimestamp) startTimestamp = timestamp;
// const progress = Math.min((timestamp - startTimestamp) / duration, 1);
// event.target.innerHTML = Math.floor(progress * (end - start) + start);
// if (progress < 1) {
// window.requestAnimationFrame(step);
// }
// };
// window.requestAnimationFrame(step);
// }



Expand Down

0 comments on commit 4f9aa50

Please sign in to comment.