Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prevent Unnecessary Update Request in Facilities Section #8956

Open
wants to merge 19 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 18 commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion cypress.config.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { defineConfig } from "cypress";
import fs from "fs";
import cypressSplit from "cypress-split";
import fs from "fs";

export default defineConfig({
projectId: "wf7d2m",
Expand Down
212 changes: 108 additions & 104 deletions src/components/Facility/BedCapacity.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
import { useEffect, useReducer, useState } from "react";
import { useTranslation } from "react-i18next";

import { Cancel, Submit } from "@/components/Common/ButtonV2";
import { CapacityModal, OptionsType } from "@/components/Facility/models";
import { SelectFormField } from "@/components/Form/FormFields/SelectFormField";
import TextFormField from "@/components/Form/FormFields/TextFormField";
import { FieldChangeEvent } from "@/components/Form/FormFields/Utils";

import { BED_TYPES } from "@/common/constants";

import * as Notification from "@/Utils/Notifications";
import routes from "@/Utils/request/api";
import request from "@/Utils/request/request";

import Form from "../Form/Form";

interface BedCapacityProps extends CapacityModal {
facilityId: string;
handleClose: () => void;
Expand Down Expand Up @@ -61,11 +61,6 @@ export const BedCapacity = (props: BedCapacityProps) => {
);
const [isLoading, setIsLoading] = useState(false);

const headerText = !id ? "Add Bed Capacity" : "Edit Bed Capacity";
const buttonText = !id
? `Save ${!isLastOptionType ? "& Add More" : "Bed Capacity"}`
: "Update Bed Capacity";

async function fetchCapacityBed() {
setIsLoading(true);
if (!id) {
Expand All @@ -75,10 +70,6 @@ export const BedCapacity = (props: BedCapacityProps) => {
});
if (capacityQuery?.data) {
const existingData = capacityQuery.data?.results;
// if all options are diabled
if (existingData.length === BED_TYPES.length) {
return;
}
// disable existing bed types
const updatedBedTypes = BED_TYPES.map((type) => {
const isExisting = existingData.find(
Expand Down Expand Up @@ -115,64 +106,58 @@ export const BedCapacity = (props: BedCapacityProps) => {
fetchCapacityBed();
}, []);

useEffect(() => {
const lastBedType =
bedTypes.filter((i: OptionsType) => i.disabled).length ===
BED_TYPES.length - 1;
setIsLastOptionType(lastBedType);
}, [bedTypes]);

const handleChange = (e: FieldChangeEvent<unknown>) => {
const form = { ...state.form };
form[e.name] = e.value;
dispatch({ type: "set_form", form });
};

const validateData = () => {
//checking validation of the new form data comming from handle submit
const validateData = (form: typeof initForm) => {
const errors = { ...initForm };
let invalidForm = false;
Object.keys(state.form).forEach((field) => {
if (!state.form[field]) {
let validForm = true;
Object.keys(form).forEach((field) => {
if (!form[field]) {
errors[field] = t("field_required");
invalidForm = true;
} else if (
field === "currentOccupancy" &&
Number(state.form[field] < 0)
) {
validForm = false;
} else if (field === "currentOccupancy" && Number(form[field] < 0)) {
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix logical error in number conversion within conditional checks

There is a logical error in the way Number() is used within the conditional statements. The expression Number(form[field] < 0) converts the boolean result of form[field] < 0 into a number (0 or 1), which is not the intended comparison.

To fix this issue, you should convert form[field] to a number before performing the comparison.

Apply this diff to correct the conditionals:

- } else if (field === "currentOccupancy" && Number(form[field] < 0)) {
+ } else if (field === "currentOccupancy" && Number(form[field]) < 0) {
...
- } else if (field === "totalCapacity" && Number(form[field] < 0)) {
+ } else if (field === "totalCapacity" && Number(form[field]) < 0) {

Also applies to: 126-126

errors[field] = "Occupied cannot be negative";
invalidForm = true;
validForm = false;
} else if (
field === "currentOccupancy" &&
Number(state.form[field]) > Number(state.form.totalCapacity)
Number(form[field]) > Number(form.totalCapacity)
) {
errors[field] = "Occupied must be less than or equal to total capacity";
invalidForm = true;
validForm = false;
}
if (field === "totalCapacity" && Number(state.form[field]) === 0) {
if (field === "totalCapacity" && Number(form[field]) === 0) {
errors[field] = "Total capacity cannot be 0";
invalidForm = true;
} else if (field === "totalCapacity" && Number(state.form[field]) < 0) {
validForm = false;
} else if (field === "totalCapacity" && Number(form[field]) < 0) {
errors[field] = "Total capacity cannot be negative";
invalidForm = true;
validForm = false;
}
});
if (invalidForm) {
if (!validForm) {
dispatch({ type: "set_error", errors });
return false;
}
dispatch({ type: "set_error", errors });
return true;
};

const handleSubmit = async (e: any, btnType = "Save") => {
e.preventDefault();
const valid = validateData();
const headerText = !id ? "Add Bed Capacity" : "Edit Bed Capacity";
const buttonText = !id ? "Save Bed Capacity" : "Update Bed Capacity";

useEffect(() => {
const lastBedType =
bedTypes.filter((i: OptionsType) => i.disabled).length ===
BED_TYPES.length - 1;
setIsLastOptionType(lastBedType);
}, [bedTypes]);

const handleSubmit = async (form: typeof initForm, source?: string) => {
const valid = validateData(form);
if (valid) {
setIsLoading(true);
const bodyData = {
room_type: Number(state.form.bedType),
total_capacity: Number(state.form.totalCapacity),
current_capacity: Number(state.form.currentOccupancy),
room_type: Number(form.bedType),
total_capacity: Number(form.totalCapacity),
current_capacity: Number(form.currentOccupancy),
};
const { data } = await request(
id ? routes.updateCapacity : routes.createCapacity,
Expand All @@ -182,8 +167,9 @@ export const BedCapacity = (props: BedCapacityProps) => {
},
);
setIsLoading(false);
let updatedBedTypes;
if (data) {
const updatedBedTypes = bedTypes.map((type) => {
updatedBedTypes = bedTypes.map((type) => {
return {
...type,
disabled: data.room_type !== type.id ? type.disabled : true,
Expand All @@ -204,10 +190,23 @@ export const BedCapacity = (props: BedCapacityProps) => {
}
handleUpdate();
}
if (btnType == "Save and Exit") handleClose();
const disabledBedTypesLength = updatedBedTypes?.filter(
(item) => item.disabled,
).length;

if (
source !== "save-and-add-more" ||
disabledBedTypesLength === BED_TYPES.length
)
handleClose();
}
};

const additionalButtonLabel =
!isLastOptionType && headerText === "Add Bed Capacity"
? "Save & Add More"
: "";

return (
<div className={className}>
{isLoading ? (
Expand All @@ -234,62 +233,67 @@ export const BedCapacity = (props: BedCapacityProps) => {
</div>
) : (
<div className={className}>
<SelectFormField
name="bedType"
id="bed-type"
label="Bed Type"
required
value={state.form.bedType}
options={bedTypes.filter((type) => !type.disabled)}
optionLabel={(option) => option.text}
optionValue={(option) => option.id}
onChange={handleChange}
disabled={!!id}
error={state.errors.bedType}
/>
<div className="flex flex-col gap-7 md:flex-row">
<TextFormField
className="w-full"
id="total-capacity"
name="totalCapacity"
label="Total Capacity"
required
type="number"
value={state.form.totalCapacity}
onChange={handleChange}
error={state.errors.totalCapacity}
min={1}
/>
<TextFormField
className="w-full"
id="currently-occupied"
label="Currently Occupied"
required
name="currentOccupancy"
type="number"
value={state.form.currentOccupancy}
onChange={handleChange}
error={state.errors.currentOccupancy}
min={0}
max={state.form.totalCapacity}
/>
</div>

<div className="cui-form-button-group mt-4">
<Cancel onClick={handleClose} />
{!isLastOptionType && headerText === "Add Bed Capacity" && (
<Submit
id="bed-capacity-save-and-exit"
onClick={(e) => handleSubmit(e, "Save and Exit")}
Jacobjeevan marked this conversation as resolved.
Show resolved Hide resolved
label="Save Bed Capacity"
/>
<Form
defaults={state.form}
onSubmit={handleSubmit}
onCancel={handleClose}
submitLabel={buttonText}
className="my-auto p-0"
noPadding
hideRestoreDraft
additionalButtons={[
{
id: "save-and-add-more",
type: "submit",
label: additionalButtonLabel,
},
]}
>
{(field) => (
<>
<SelectFormField
name="bedType"
id="bed-type"
label="Bed Type"
required
value={field("bedType").value}
options={bedTypes.filter((type) => !type.disabled)}
optionLabel={(option) => option.text}
optionValue={(option) => option.id}
onChange={(e: any) => field("bedType").onChange(e)}
disabled={!!id}
error={state.errors.bedType}
/>
<div className="flex flex-col gap-7 md:flex-row">
<TextFormField
className="w-full"
id="total-capacity"
name="totalCapacity"
label="Total Capacity"
required
type="number"
value={field("totalCapacity").value}
onChange={(e: any) => field("totalCapacity").onChange(e)}
error={state.errors.totalCapacity}
min={1}
/>
<TextFormField
className="w-full"
id="currently-occupied"
label="Currently Occupied"
required
name="currentOccupancy"
type="number"
value={field("currentOccupancy").value}
onChange={(e: any) => field("currentOccupancy").onChange(e)}
error={state.errors.currentOccupancy}
min={0}
max={state.form.totalCapacity}
/>
</div>
</>
)}
<Submit
id="bed-capacity-save"
onClick={(e) => handleSubmit(e)}
label={buttonText}
/>
</div>
</Form>
</div>
)}
</div>
Expand Down
1 change: 1 addition & 0 deletions src/components/Facility/FacilityBedCapacity.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ export const FacilityBedCapacity = (props: any) => {
id="facility-add-bedtype"
className="w-full md:w-auto"
onClick={() => setBedCapacityModalOpen(true)}
disabled={BED_TYPES.length === capacityQuery.data?.count}
authorizeFor={NonReadOnlyUsers}
>
<CareIcon icon="l-bed" className="mr-2 text-lg text-white" />
Expand Down
Loading
Loading