Skip to content

Commit

Permalink
Merge pull request #286 from ertush/hotfix-dev
Browse files Browse the repository at this point in the history
Hotfix dev
ertush authored Jan 11, 2024
2 parents 0cefc53 + 839c38d commit 246f8f0
Showing 6 changed files with 811 additions and 133 deletions.
64 changes: 31 additions & 33 deletions components/Forms/CommunityUnitsForms.js
Original file line number Diff line number Diff line change
@@ -974,10 +974,9 @@ function EditCommunityUnitsServicesForm(props) {
})(options?.services ?? [])


function handleSubmit (token, selectedServices, chulId) {
function handleSubmit (selectedServices, chulId) {
// console.log({stateSetters, chulId})


const _payload = selectedServices.map(({value}) => ({ service: value }))

_payload.forEach(obj => obj['health_unit'] = chulId)
@@ -996,38 +995,39 @@ function EditCommunityUnitsServicesForm(props) {
body: JSON.stringify({services: _payload})
})

// .then(async resp => {
// if (resp.status == 200 || resp.status == 204) {

// setSubmitting(false)

// alert.success(`${props?.name} services have been updated successfully`, {
// containerStyle: {
// backgroundColor: "green",
// color: "#fff"
// },
// timeout: 10000
// })

// } else {
// // const detail = await resp.json()

// setSubmitting(false)
// // setFormError(Array.isArray(Object.values(detail)) && Object.values(detail).length == 1 && typeof Object.values(detail)[0] == 'string' && detail[0][0])
// alert.error(`Unable to update ${props?.name} services`, {
// timeout: 10000
// })
// }
// })




}
catch (e) {
console.error(e.message)
}
}

};
};


function handleCHUServiceUpdate (selectedServices, chulId) {

const _payload = selectedServices.map(({value}) => ({ service: value }))

_payload.forEach(obj => obj['health_unit'] = chulId)

try {
return fetch(`${process.env.NEXT_PUBLIC_API_URL}/chul/units/${chulId}/`, {
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json;charset=utf-8',
'Authorization': `Bearer ${props?.token}`
},
method: 'PATCH',
body: JSON.stringify({services: _payload})
})

}
catch (e) {
console.error(e.message)
}
}



@@ -1053,14 +1053,12 @@ function EditCommunityUnitsServicesForm(props) {


<EditListItem
initialSelectedItems={currentServices}
itemData={currentServices}
categoryItems={serviceOptions[0]?.options} //serviceOptions
itemId={props?.id} //chulId
item={null}
token={props?.token}
token={props?.token}
handleItemsSubmit={handleSubmit} //handleCHUServiceSubmit
handleItemsUpdate={() => null} //handleServiceUpdates
setNextItemCategory={null}
handleItemsUpdate={handleCHUServiceUpdate} //handleServiceUpdates
setSubmitting={setSubmitting}
submitting={submitting}
options={serviceOptions[0]?.options}
7 changes: 0 additions & 7 deletions components/Forms/InfrastructureForm.js
Original file line number Diff line number Diff line change
@@ -110,26 +110,19 @@ export function InfrastructureForm() {

{/* Edit List With Count*/}
<EditListWithCount
initialSelectedItems={options?.data? options?.data.facility_infrastructure:[]}
otherItemsCategory={null}
itemsCategoryName={'infrastructure'}
categoryItems={infrastructureOption.categories}
options={options.infrastructure}
token={options.token}
itemId={facilityId ?? options?.data?.id}
item={options?.data ?? null}
handleItemsSubmit={handleInfrastructureSubmit}
handleItemsUpdate={handleInfrastructureUpdates}
setSubmitting={setSubmitting}
submitting={submitting}
removeItemHandler={() => null}
handleItemPrevious={handleInfrastructurePrevious}
setNextItemCategory={setFormId}
setItemsUpdateData={updateFacilityUpdateData}
nextItemCategoryId={formId}
nextItemCategory={'human resource'}
previousItemCategory={'services'}
setIsSaveAndFinish={updatedSavedChanges}
itemData={options?.data ? options?.data?.facility_infrastructure : null}
title={tableheaders}

13 changes: 3 additions & 10 deletions components/Forms/ServicesForm.js
Original file line number Diff line number Diff line change
@@ -119,26 +119,19 @@ export function ServicesForm() {
<div className='flex items-center w-full h-auto min-h-[300px]'>

<EditListItem
initialSelectedItems={options?.data ? options?.data.facility_services:[]}
itemData={options?.data ? options?.data.facility_services : null}
categoryItems={serviceOptions.categories}
itemsCategoryName={'Services'}
itemId={facilityId ?? options?.data?.id}
setItems={setServices}
item={options?.data ?? null}
options={options?.services}
token={options?.token}
itemName={'facility_services'}
removeItemHandler={handleServiceDelete}
handleItemsSubmit={handleServiceSubmit}
handleItemsUpdate={handleServiceUpdates}
setSubmitting={setSubmitting}
submitting={submitting}
setItemsUpdateData={updateFacilityUpdateData}
handleItemPrevious={handleServicePrevious}
setIsSaveAndFinish={updatedSavedChanges}
servicesData={options?.data ? options?.data?.facility_services: null}

/>

/>

</div>
</div>
170 changes: 101 additions & 69 deletions components/Forms/formComponents/EditListItem.js
Original file line number Diff line number Diff line change
@@ -13,55 +13,32 @@ import { Alert } from '@mui/lab'


function EditListItem({
initialSelectedItems,
itemData,
categoryItems,
itemId,
item,
itemName,
handleItemsSubmit,
handleItemsUpdate,
setSubmitting,
submitting,
handleItemPrevious,
token,
options,
servicesData
options

}) {



const alert = useAlert()
const router = useRouter()


const [allServices, setallServices] = useState([])
const [selectedItems, setSelectedItems] = useState(Array.isArray(initialSelectedItems) && initialSelectedItems.length > 0 ? (() => {
const result = []

if(itemName == 'facility_services'){
console.log({initialSelectedItems})
initialSelectedItems?.map((service) => {

result.push({ sname: service.service_name, rowid: service.service_id, category_id: service.category_id, category_name: service.category_name })

return result

})

}
else {
return initialSelectedItems
}
const [selectedItems, setSelectedItems] = useState([])
const [showItemCategory, setShowItemCategory] = useState(false)


})() : [])



const editService = servicesData?.map(({ service_name: name, service_id, id }) => ({ id, service_id, name }));

const [savedItems, saveSelectedItems] = useState(servicesData ? editService : [])
const [formError, setFormError] = useState(null)
const [formError, setFormError] = useState(null)


// Refs
@@ -119,7 +96,8 @@ function EditListItem({

if (issearchcategory) {

subset = categoryItems.filter((e) => e.label.toLowerCase().includes(_query.toLowerCase()))

subset = categoryItems.filter((e) => e.label.toLowerCase().includes(_query.toLowerCase()))


setCategoryItems(subset);
@@ -138,47 +116,95 @@ function EditListItem({


useEffect(() => {
//store service when service is added
// if (selectedItems.length !== 0) {
// let x = selectedItems;

if(Array.isArray(itemData)) {
const result = []

setSelectedItems(() => {

if(itemName == 'facility_services'){

// saveSelectedItems(
// JSON.stringify(x)
// );
itemData?.map((service) => {
result.push({ sname: service.service_name, rowid: service.service_id, category_id: service.category_id, category_name: service.category_name })
})

// return () => {
// localStorage.setItem('services_edit_form', '[]')
// }
// }
return result

console.log(JSON.stringify(selectedItems, null, 2))
}
else {
return itemData
}
})
}

}, [])

function handleSearchItemFocus (e) {
e.preventDefault()

if(!showItemCategory) {
setShowItemCategory(true)
}
}

function handleSubmit(e) {

e.preventDefault()

setSubmitting(true)

if (item) {
if (itemData) {

const newSelectedItems = selectedItems.filter(({rowId}, i) => rowId == itemData[i]?.service_id)

if(itemName == 'facility_services') {
handleItemsUpdate(token, [newSelectedItems, itemId])
.then(resp => {
if (resp.status == 200 || resp.status == 204) {
setSubmitting(false)
alert.success('Updated facility services successfully');

router.push({
pathname: '/facilities/facility_changes/[facility_id]',
query: {
facility_id: itemId
}
})
} else {
setSubmitting(false)
resp.json()
.then(resp => {
const formResponse = []
setFormError(() => {
if(typeof resp == 'object') {
const respEntry = Object.entries(resp)

for (let [_, v] of respEntry) {
formResponse.push(v)
}

handleItemsUpdate(token, [selectedItems, itemId])
return `Error: ${formResponse.join("")}`
}
})
})
}
})
.catch(e => console.error('unable to update facility services. Error:', e.message))
} else {
handleItemsUpdate(newSelectedItems, itemId)
.then(resp => {
if (resp.status == 200 || resp.status == 204) {
setSubmitting(false)
alert.success('Updated facility services successfully');
alert.success('Updated Community Health Unit Services successfully');

router.push({
pathname: '/facilities/facility_changes/[facility_id]',
query: {
facility_id: itemId
}
})
// router.push({
// pathname: '/facilities/facility_changes/[facility_id]',
// query: {
// facility_id: itemId
// }
// })
} else {

setSubmitting(false)
resp.json()
.then(resp => {
const formResponse = []
@@ -196,7 +222,8 @@ function EditListItem({
})
}
})
.catch(e => console.error('unable to fetch facility update data. Error:', e.message))
.catch(e => console.error('unable to update CHU servics update. Error:', e.message))
}
}
else {
if (itemName == "facility_services") {
@@ -275,7 +302,7 @@ function EditListItem({
})
.catch(e => console.error('unable to submit item data. Error:', e.message))
} else {
handleItemsSubmit(token, selectedItems, itemId)
handleItemsSubmit(selectedItems, itemId)
.then(resp => {
if (resp.status == 204 || resp.status == 200) {
setSubmitting(false)
@@ -314,15 +341,16 @@ function EditListItem({
>

{formError && <Alert severity='error' className={'w-full'}>{formError}</Alert>}
<pre>{JSON.stringify(selectedItems, null, 2)}</pre>



<div className='w-full grid grid-cols-12 gap-4'>

<div className='w-full grid grid-cols-12 gap-4'>
<div className={`${itemName == "chul_services" ? 'col-span-12' : 'col-span-5'}`} >
<h4 className="text-lg uppercase mt-4 pb-2 border-b border-blue-600 w-full mb-4 font-semibold text-blue-900">{itemName == 'chul_services' ? 'Services' : 'Categories'}</h4>
<input type="text" onChange={(e) => onSearch(e, true, false)} className="col-span-12 border border-blue-600 p-2 placeholder-gray-500 focus:shadow-none focus:bg-white focus:border-black outline-none w-full" placeholder="Search" />
<input name="searchItem" type="text" onFocus={handleSearchItemFocus} onChange={(e) => onSearch(e, true, false)} className="col-span-12 border border-blue-600 p-2 placeholder-gray-500 focus:shadow-none focus:bg-white focus:border-black outline-none w-full" placeholder="Search" />
{!showItemCategory && <div className="text-center border-l border-blue-500 border-r border-b w-full">Search for services</div>}

<br />
{
showItemCategory &&
<ul className='max-h-96 overflow-auto border-r border-l border-b border-blue-500'>

{
@@ -345,6 +373,7 @@ function EditListItem({
}

</ul>
}
</div>
{
itemName == "facility_services" &&
@@ -374,12 +403,12 @@ function EditListItem({
<input
type="checkbox"
className="p-1 w-5 h-5"
checked={selectedItems?.some(item => item.rowid.includes(row.id))}
checked={selectedItems?.some(item => item?.rowid?.includes(row?.id))}
onChange={(e) => handleCheckboxChange(
row.id,
row.name,
row.category,
row.category_name,
row?.id,
row?.name,
row?.category,
row?.category_name,
)}
/> Yes
</td>
@@ -438,20 +467,23 @@ function EditListItem({
</tr>
</thead>
<tbody className='bg-blue-50 shadow-md'>


{Array.isArray(selectedItems) && selectedItems.length === 0 && <tr><td colSpan={3} className="text-center">No services found</td></tr>}


{
itemName == "facility_services" ?
selectedItems?.map((row, i) => (
itemName == "facility_services" ?
selectedItems?.map((row, i) => (
<tr key={i}>

<td className="border border-gray-300 px-1 py-1">{row.sname}</td>
<td className="border border-gray-300 px-1 py-1">
Yes
</td>
</tr>
))
:
:
selectedItems?.map(({ label, value}) => (
<tr key={value}>
<td className="border border-gray-300 px-1 py-1">{label}</td>
@@ -478,7 +510,7 @@ function EditListItem({
{/* Save btn */}

{
savedItems.length > 0 && item !== null &&
Array.isArray(itemData) &&

<div className=" w-full flex justify-end h-auto mr-3">
<button type='submit' className='p-2 text-white bg-blue-600 font-semibold'>
@@ -498,7 +530,7 @@ function EditListItem({
}

{
item === null &&
itemData === null &&

<div className={`flex ${itemName == "facility_services" ? 'justify-between' : 'justify-end'} items-center w-full mt-4`} >
{
56 changes: 42 additions & 14 deletions components/Forms/formComponents/EditListWithCount.js
Original file line number Diff line number Diff line change
@@ -13,11 +13,9 @@ import {Alert} from '@mui/lab'

function EditListWithCount(
{
initialSelectedItems,
otherItemsCategory,
itemsCategoryName,
itemId,
item,
handleItemsSubmit,
handleItemsUpdate,
handleItemPrevious,
@@ -68,12 +66,12 @@ function EditListWithCount(


//console.log(options)
const [selectedRows, setSelectedRows] = useState((initialSelectedItems ? (() => {
const [selectedRows, setSelectedRows] = useState((itemData ? (() => {

const result = []

if (initialSelectedItems.length > 0) {
initialSelectedItems.forEach((element) => {
if (itemData.length > 0) {
itemData.forEach((element) => {
if (itemsCategoryName.includes('human resource')) {
const cat = options.filter((e) => e.id == element.speciality)[0].category
result.push({
@@ -133,6 +131,7 @@ function EditListWithCount(

const [savedItems, saveSelectedItems] = useState(itemData ? editItem : [])

const [showItemCategory, setShowItemCategory] = useState(false)

const [items, setItems] = useState(typeof savedItems === 'string' && savedItems.length > 0 ? JSON.parse(savedItems) : savedItems)

@@ -188,7 +187,7 @@ function EditListWithCount(

}

if(item) selectedRows.pop()
if(itemData) selectedRows.pop()


}, [selectedRows]);
@@ -213,11 +212,27 @@ function EditListWithCount(
}, [isFormSubmit])

const filterSpecialities = (ctg) => {
// function getCheckedCheckBoxCount() {
// const checkboxes = document.querySelectorAll('input[name=itemCheckBox]')

// console.log(checkboxes)
// }

// getCheckedCheckBoxCount()

const filteredOptions = options.filter((option) => option.category === ctg);
setSpecialities(filteredOptions)
setIsActive(ctg)
}

function handleSearchItemFocus (e) {
e.preventDefault()

if(!showItemCategory) {
setShowItemCategory(true)
}
}

const handleCheckboxChange = (id, name, category, category_name) => {
setSelectedRows((prevSelectedRows) => {
if (prevSelectedRows?.filter((row) => row?.rowid == id).length > 0) {
@@ -252,9 +267,12 @@ function EditListWithCount(

setSubmitting(true)

if (item) {
if (itemData) {

const newSelectedRows = selectedRows.filter(({rowId}, i) => rowId == itemData[i]?.id)

handleItemsUpdate(token, [selectedRows, itemId])

handleItemsUpdate(token, [newSelectedRows, itemId])
.then(resp => {
if (resp.status == 200 || resp.status == 204) {
setSubmitting(false)
@@ -391,6 +409,7 @@ function EditListWithCount(

const onSearch = ((event, issearchcategory, issearchspeciality) => {


const _query = event.target.value;
setQuery(_query);
if (_query.length > 3) {
@@ -425,8 +444,12 @@ function EditListWithCount(
<div className='w-full grid grid-cols-12 gap-4'>
<div className="col-span-5" >
<h4 className="text-lg uppercase mt-4 pb-2 border-b border-blue-600 w-full mb-4 font-semibold text-blue-900">Categories</h4>
<input type="text" onChange={(e) => onSearch(e, true, false)} className="col-span-12 border border-blue-600 p-2 placeholder-gray-500 focus:shadow-none focus:bg-white focus:border-black outline-none w-full" placeholder="Search" />
<input type="text" onFocus={handleSearchItemFocus} onChange={(e) => onSearch(e, true, false)} className="col-span-12 border border-blue-600 p-2 placeholder-gray-500 focus:shadow-none focus:bg-white focus:border-black outline-none w-full" placeholder="Search" />
{!showItemCategory && <div className="text-center border-l border-blue-500 border-r border-b w-full">{`Search for ${itemsCategoryName.includes('infrastructure') ? 'infrastructure' : 'a speciality' }`}</div>}

<br />
{
showItemCategory &&
<ul className='max-h-96 overflow-auto border-r border-l border-b border-blue-500'>
{categoryOptions.map(({ label, value, catcount }) => (
<div key={value}
@@ -444,7 +467,9 @@ function EditListWithCount(

))}
</ul>
}
</div>

<div className="col-span-7" >
<h4 className="text-lg uppercase mt-4 pb-2 border-b border-blue-600 w-full mb-4 font-semibold text-blue-900">{itemsCategoryName.includes('human resource') ? 'Specialities' : itemsCategoryName.includes('infrastructure') ? 'Infrastructure' : null}</h4>
<input type="text" onChange={(e) => onSearch(e, false, true)} className="col-span-12 border border-blue-600 p-2 placeholder-gray-500 focus:shadow-none focus:bg-white focus:border-black outline-none w-full" placeholder="Search" />
@@ -458,17 +483,19 @@ function EditListWithCount(
</tr>
</thead>
<tbody className='bg-blue-50 shadow-md'>
{specialities.length === 0 && <tr><td colSpan={3} className="text-center">No specialities found</td></tr>}
{specialities.length === 0 && <tr><td colSpan={3} className="text-center">{`No ${itemsCategoryName.includes('infrastructure') ? 'infrastructure' : 'specialities'} found`}</td></tr>}

{specialities.map((row) => (

<tr key={row?.id}>
<tr key={row?.id} >
<td className="border px-1 py-1">
<label className="w-full p-2" >{row?.name}</label>
</td>
<td className="border px-1 py-1">
<input

type="checkbox"
name="itemCheckBox"
className="p-1 w-5 h-5"
checked={selectedRows.some(item => item?.rowid?.includes(row?.id))}
onChange={(e) => handleCheckboxChange(
@@ -519,12 +546,13 @@ function EditListWithCount(
{/* {selectedRows.pop()} */}
{selectedRows.map((row) => {
// if(row.name !== "Vaccine Carriers" || row.name !== "Public Health Technician"){
return <tr>
return ( <tr>
<td className="border border-gray-300 px-1 py-1">{row?.sname}</td>
{row?.iscategoryvisible ? <td className="border border-gray-300 px-1 py-1">{row?.category_name}</td> :null }
<td className="border border-gray-300 px-1 py-1">Yes</td>
<td className="border border-gray-300 px-1 py-1">{row?.count ? Number(row?.count) : null}</td>
</tr>
)
// }
})}

@@ -535,7 +563,7 @@ function EditListWithCount(
{/* Save btn */}

{
savedItems.length > 0 && item !== null &&
savedItems.length > 0 && itemData !== null &&

<div className="w-full flex justify-end h-auto mt-3">
<button type='submit' className='p-2 text-white bg-blue-600 font-semibold'>
@@ -555,7 +583,7 @@ function EditListWithCount(
}

{
item === null &&
itemData === null &&

<div className='flex justify-between items-center w-full mt-4'>
<button onClick={handleItemPrevious} className='flex items-center justify-start space-x-2 p-1 border border-blue-900 px-2'>
634 changes: 634 additions & 0 deletions pages/public/chu/index.js

Large diffs are not rendered by default.

1 comment on commit 246f8f0

@vercel
Copy link

@vercel vercel bot commented on 246f8f0 Jan 11, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

kmhfl-upgrade-alpha-ui – ./

kmhfl-upgrade-alpha-ui-git-main-ertush.vercel.app
kmhfl-upgrade-alpha-ui-ertush.vercel.app
kmhflv3.vercel.app

Please sign in to comment.