Repository: ohcnetwork/care_fe
Pull request #11719: Added : Edit option for department/team
Author: login: AdityaJ2305
Labels: name: needs review
name: Tested
Created: 2025-04-03T19:53:14Z | Merged: 2025-04-07T17:07:41Z

## Proposed Changes

- Fixes #11319
- [x] Updated the form to use form, formfield and react hook form and zod 
- [x] Added Edit option button in org card to open the edit-form-sheet


https://github.com/user-attachments/assets/8ff68b71-92b8-45f7-997a-4ee88cb4066f


@ohcnetwork/care-fe-code-reviewers

## Merge Checklist

- [ ] Add specs that demonstrate bug / test a new feature.
- [ ] Update [product documentation](https://docs.ohc.network).
- [x] Ensure that UI text is kept in I18n files.
- [x] Prep screenshot or demo video for changelog entry, and attach it to issue.
- [x] Request for Peer Reviews
- [x] Completion of QA in Mobile Devices
- [x] Completion of QA in Desktop Devices


<!-- This is an auto-generated comment: release notes by coderabbit.ai -->
## Summary by CodeRabbit

- **New Features**
  - Updated on-screen text and notifications to support enhanced editing options for departments/teams and organization updates.
  - Introduced an improved form experience for both creating and editing organizations with real-time validation and dynamic interface feedback.
  - Enabled conditional display of editing features based on user permissions.

- **Refactor**
  - Streamlined the component structure and update operations for a more intuitive and responsive user experience.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Linked issue #11319: Enable edit option for department/team name within a facility
Enable option for facility admin to edit/update name of the department/facility.

<img width="1678" alt="Image" src="https://github.com/user-attachments/assets/b1a10f87-2b3b-4489-bad6-cf9be340c6c1" />
Linked issue comments: user: login: AdityaJ2305
created_at: 2025-03-16T14:01:01Z
body: Hey @aravindm4 , I would like to work on this eta 2 days
author_association: MEMBER
user: login: Mahendar0701
created_at: 2025-03-16T14:01:08Z
body: Can i work on this? ETA tmr eod. I have no active issues can i get assigned?
author_association: CONTRIBUTOR
user: login: hrit2773
created_at: 2025-03-16T14:07:37Z
body: @aravindm4 @rithviknishad can I take this up. ETA: tomorrow EOD. I don't have new issues to take up.
author_association: CONTRIBUTOR
user: login: hrit2773
created_at: 2025-03-16T14:29:02Z
body: https://github.com/ohcnetwork/care_fe/issues/11271 I opened an issue for fixing this but was closed as not planned as @rithviknishad  mentioned that there are redesigns being done not sure if its valid. Can I get it assigned if valid
author_association: CONTRIBUTOR
user: login: abhimanyurajeesh
created_at: 2025-03-16T14:35:11Z
body: > [#11271](https://github.com/ohcnetwork/care_fe/issues/11271) I opened an issue for fixing this but was closed as not planned as [@rithviknishad](https://github.com/rithviknishad) mentioned that there are redesigns being done not sure if its valid. Can I get it assigned if valid

are you sure about that!?

<img width="957" alt="Image" src="https://github.com/user-attachments/assets/212c1b28-fc1c-47e2-b025-4ad8887e2adf" />

This says something else 🤔 
author_association: CONTRIBUTOR
user: login: hrit2773
created_at: 2025-03-16T14:46:47Z
body: @abhimanyurajeesh yes edit/delete buttons for each department in departments list. I was updating that issue then it got closed....
author_association: CONTRIBUTOR
user: login: AdityaJ2305
created_at: 2025-03-16T14:47:43Z
body: @rithviknishad , I messaged first for assignment 😅 , Could you assign it to me 
author_association: MEMBER

Diff:
diff --git a/public/locale/en.json b/public/locale/en.json
index b7d88bb49da..878543f64e6 100644
--- a/public/locale/en.json
+++ b/public/locale/en.json
@@ -817,7 +817,7 @@
   "create_consent": "Create Consent",
   "create_consultation": "Create Consultation",
   "create_department_team": "Create Department/Team",
-  "create_department_team_description": "Create a new department/team in this facility.",
+  "create_department_team_description": "Create a new department/team in this facility",
   "create_encounter": "Create Encounter",
   "create_facility": "Create Facility",
   "create_location_association": "Create Location Association",
@@ -1032,6 +1032,8 @@
   "edit_bed_names": "Edit {{count}} bed names ",
   "edit_caution_note": "A new prescription will be added to the consultation with the edited details and the current prescription will be discontinued.",
   "edit_cover_photo": "Edit Cover Photo",
+  "edit_department_team": "Edit Department/Team",
+  "edit_department_team_description": "Edit the current department/team",
   "edit_device": "Edit Device",
   "edit_device_description": "Edit the details of the device",
   "edit_facility": "Edit Facility",
@@ -1943,6 +1945,7 @@
   "organization_removed_successfully": "Organization removed successfully",
   "organization_required": "Organization is required",
   "organization_selection_required": "At least one organization must be selected",
+  "organization_updated_successfully": "Organization updated successfully",
   "organizations": "Organizations",
   "organizations_fetch_error": "Error while fetching organizations",
   "origin_facility": "Current facility",
@@ -2685,6 +2688,7 @@
   "taken": "Taken",
   "taper_titrate_dosage": "Taper & Titrate Dosage",
   "target_dosage": "Target Dosage",
+  "team": "Team",
   "template_deleted": "Template has been deleted",
   "test_type": "Type of test done",
   "tested_on": "Tested on",
@@ -2830,6 +2834,7 @@
   "update_hospitalisation_details": "Update Hospitalisation Details",
   "update_location": "Update Location",
   "update_log": "Update Log",
+  "update_organization": "Update Organization",
   "update_password": "Update Password",
   "update_patient_details": "Update Patient Details",
   "update_preset": "Update Preset",
diff --git a/src/pages/Facility/settings/organizations/FacilityOrganizationView.tsx b/src/pages/Facility/settings/organizations/FacilityOrganizationView.tsx
index 750c28c3b55..fef204e5267 100644
--- a/src/pages/Facility/settings/organizations/FacilityOrganizationView.tsx
+++ b/src/pages/Facility/settings/organizations/FacilityOrganizationView.tsx
@@ -20,7 +20,7 @@ import { usePermissions } from "@/context/PermissionContext";
 import { FacilityOrganization } from "@/types/facilityOrganization/facilityOrganization";
 import facilityOrganizationApi from "@/types/facilityOrganization/facilityOrganizationApi";
 
-import CreateFacilityOrganizationSheet from "./components/CreateFacilityOrganizationSheet";
+import FacilityOrganizationFormSheet from "./components/CreateFacilityOrganizationSheet";
 
 interface Props {
   id?: string;
@@ -30,9 +30,14 @@ interface Props {
 
 function OrganizationCard({
   org,
+  facilityId,
+  parentId,
+  canWrite,
 }: {
   org: FacilityOrganization;
   facilityId: string;
+  parentId?: string;
+  canWrite: boolean;
 }) {
   const { t } = useTranslation();
 
@@ -52,11 +57,25 @@ function OrganizationCard({
                 </Badge>
               </div>
             </div>
-            <Button variant="white" size="sm" className="font-semibold" asChild>
-              <Link href={`/departments/${org.id}/departments`}>
-                {t("see_details")}
-              </Link>
-            </Button>
+            <div className="flex flex-row gap-2">
+              {canWrite && org.org_type !== "root" && (
+                <FacilityOrganizationFormSheet
+                  facilityId={facilityId}
+                  parentId={parentId}
+                  org={org}
+                />
+              )}
+              <Button
+                variant="white"
+                size="sm"
+                className="font-semibold"
+                asChild
+              >
+                <Link href={`/departments/${org.id}/departments`}>
+                  {t("see_details")}
+                </Link>
+              </Button>
+            </div>
           </div>
         </div>
       </CardContent>
@@ -98,10 +117,8 @@ export default function FacilityOrganizationView({
     }),
   });
 
-  const { canCreateFacilityOrganization } = getPermissions(
-    hasPermission,
-    permissions,
-  );
+  const { canCreateFacilityOrganization, canManageFacilityOrganization } =
+    getPermissions(hasPermission, permissions);
 
   return (
     <div className="space-y-6 mx-auto max-w-4xl">
@@ -125,7 +142,7 @@ export default function FacilityOrganizationView({
           </div>
           <div className="w-auto">
             {canCreateFacilityOrganization && (
-              <CreateFacilityOrganizationSheet
+              <FacilityOrganizationFormSheet
                 facilityId={facilityId}
                 parentId={id}
               />
@@ -146,7 +163,9 @@ export default function FacilityOrganizationView({
                 <OrganizationCard
                   key={org.id}
                   org={org}
+                  canWrite={canManageFacilityOrganization}
                   facilityId={facilityId}
+                  parentId={id}
                 />
               ))
             ) : (
diff --git a/src/pages/Facility/settings/organizations/components/CreateFacilityOrganizationSheet.tsx b/src/pages/Facility/settings/organizations/components/CreateFacilityOrganizationSheet.tsx
index b0f8208e9ba..3944e3786c4 100644
--- a/src/pages/Facility/settings/organizations/components/CreateFacilityOrganizationSheet.tsx
+++ b/src/pages/Facility/settings/organizations/components/CreateFacilityOrganizationSheet.tsx
@@ -1,11 +1,22 @@
+import { zodResolver } from "@hookform/resolvers/zod";
 import { useMutation, useQueryClient } from "@tanstack/react-query";
 import { t } from "i18next";
-import { useState } from "react";
+import { useEffect, useState } from "react";
+import { useForm } from "react-hook-form";
 import { toast } from "sonner";
+import * as z from "zod";
 
 import CareIcon from "@/CAREUI/icons/CareIcon";
 
 import { Button } from "@/components/ui/button";
+import {
+  Form,
+  FormControl,
+  FormField,
+  FormItem,
+  FormLabel,
+  FormMessage,
+} from "@/components/ui/form";
 import { Input } from "@/components/ui/input";
 import {
   Select,
@@ -25,32 +36,66 @@ import {
 import { Textarea } from "@/components/ui/textarea";
 
 import mutate from "@/Utils/request/mutate";
-import { FacilityOrganizationCreate } from "@/types/facilityOrganization/facilityOrganization";
+import {
+  FacilityOrganization,
+  FacilityOrganizationCreate,
+  FacilityOrganizationEdit,
+} from "@/types/facilityOrganization/facilityOrganization";
 import facilityOrganizationApi from "@/types/facilityOrganization/facilityOrganizationApi";
 
 interface Props {
   facilityId: string;
   parentId?: string;
+  org?: FacilityOrganization;
 }
 
 const ORG_TYPES = [
-  { value: "dept", label: "Department" },
-  { value: "team", label: "Team" },
+  { value: "dept", label: "department" },
+  { value: "team", label: "team" },
 ] as const;
 
 type OrgType = (typeof ORG_TYPES)[number]["value"];
 
-export default function FacilityOrganizationSheet({
+const formSchema = z.object({
+  name: z
+    .string()
+    .trim()
+    .min(1, { message: t("field_required") }),
+  description: z.string().optional(),
+  org_type: z.enum(["dept", "team"]),
+});
+
+type FormValues = z.infer<typeof formSchema>;
+
+export default function FacilityOrganizationFormSheet({
   facilityId,
   parentId,
+  org,
 }: Props) {
+  const isEditMode = !!org;
   const queryClient = useQueryClient();
   const [open, setOpen] = useState(false);
-  const [name, setName] = useState("");
-  const [description, setDescription] = useState("");
-  const [orgType, setOrgType] = useState<OrgType>("dept");
 
-  const { mutate: createOrganization, isPending } = useMutation({
+  const form = useForm<FormValues>({
+    resolver: zodResolver(formSchema),
+    defaultValues: {
+      name: "",
+      description: "",
+      org_type: "dept" as OrgType,
+    },
+  });
+
+  useEffect(() => {
+    if (isEditMode && org) {
+      form.reset({
+        name: org.name || "",
+        description: org.description || "",
+        org_type: org.org_type as OrgType,
+      });
+    }
+  }, [isEditMode, org, open]);
+
+  const { mutate: createOrganization, isPending: isCreating } = useMutation({
     mutationFn: (body: FacilityOrganizationCreate) =>
       mutate(facilityOrganizationApi.create, {
         pathParams: { facilityId },
@@ -65,9 +110,7 @@ export default function FacilityOrganizationSheet({
       });
       toast.success(t("organization_created_successfully"));
       setOpen(false);
-      setName("");
-      setDescription("");
-      setOrgType("dept");
+      form.reset();
     },
     onError: (error) => {
       const errorData = error.cause as { errors: { msg: string }[] };
@@ -77,81 +120,145 @@ export default function FacilityOrganizationSheet({
     },
   });
 
-  const handleSubmit = () => {
-    if (!name.trim()) {
-      toast.error(t("please_enter_organization_name"));
-      return;
-    }
+  const { mutate: updateOrganization, isPending: isUpdating } = useMutation({
+    mutationFn: (body: FacilityOrganizationEdit) =>
+      mutate(facilityOrganizationApi.update, {
+        pathParams: { facilityId, organizationId: org?.id },
+        body,
+      })(body),
+    onSuccess: () => {
+      queryClient.invalidateQueries({
+        queryKey: ["facilityOrganization", "list", facilityId, parentId],
+      });
+      queryClient.invalidateQueries({
+        queryKey: ["getCurrentUser"],
+      });
+      toast.success(t("organization_updated_successfully"));
+      setOpen(false);
+    },
+  });
 
-    createOrganization({
-      name: name.trim(),
-      description: description.trim() || undefined,
-      org_type: orgType,
+  const onSubmit = (values: FormValues) => {
+    const data = {
+      name: values.name.trim(),
+      description: values.description?.trim() || undefined,
+      org_type: values.org_type,
       parent: parentId,
-    });
+    };
+
+    if (isEditMode) {
+      updateOrganization({ ...data, facility: facilityId });
+    } else {
+      createOrganization(data);
+    }
   };
 
+  const isPending = isCreating || isUpdating;
+
   return (
     <Sheet open={open} onOpenChange={setOpen}>
       <SheetTrigger asChild>
-        <Button>
-          <CareIcon icon="l-plus" className="mr-2 size-4" />
-          {t("add_department_team")}
-        </Button>
+        {isEditMode ? (
+          <Button variant="white" size="sm" className="font-semibold">
+            {t("edit")}
+          </Button>
+        ) : (
+          <Button>
+            <CareIcon icon="l-plus" className="mr-2 size-4" />
+            {t("add_department_team")}
+          </Button>
+        )}
       </SheetTrigger>
       <SheetContent>
         <SheetHeader>
-          <SheetTitle>{t("create_department_team")}</SheetTitle>
+          <SheetTitle>
+            {isEditMode
+              ? t("edit_department_team")
+              : t("create_department_team")}
+          </SheetTitle>
           <SheetDescription>
-            {t("create_department_team_description")}
+            {isEditMode
+              ? t("edit_department_team_description")
+              : t("create_department_team_description")}
           </SheetDescription>
         </SheetHeader>
-        <div className="space-y-6 py-4">
-          <div className="space-y-2">
-            <label className="text-sm font-medium">Name</label>
-            <Input
-              value={name}
-              onChange={(e) => setName(e.target.value)}
-              placeholder={t("enter_department_team_name")}
+        <Form {...form}>
+          <form
+            onSubmit={form.handleSubmit(onSubmit)}
+            className="space-y-6 py-4"
+          >
+            <FormField
+              control={form.control}
+              name="name"
+              render={({ field }) => (
+                <FormItem className="space-y-2">
+                  <FormLabel>{t("name")}</FormLabel>
+                  <FormControl>
+                    <Input
+                      {...field}
+                      placeholder={t("enter_department_team_name")}
+                    />
+                  </FormControl>
+                  <FormMessage />
+                </FormItem>
+              )}
+            />
+
+            <FormField
+              control={form.control}
+              name="org_type"
+              render={({ field }) => (
+                <FormItem className="space-y-2">
+                  <FormLabel>{t(`type`)}</FormLabel>
+                  <Select value={field.value} onValueChange={field.onChange}>
+                    <FormControl>
+                      <SelectTrigger>
+                        <SelectValue
+                          placeholder={t("select_organization_type")}
+                        />
+                      </SelectTrigger>
+                    </FormControl>
+                    <SelectContent>
+                      {ORG_TYPES.map((type) => (
+                        <SelectItem key={type.value} value={type.value}>
+                          {t(type.label)}
+                        </SelectItem>
+                      ))}
+                    </SelectContent>
+                  </Select>
+                  <FormMessage />
+                </FormItem>
+              )}
             />
-          </div>
-
-          <div className="space-y-2">
-            <label className="text-sm font-medium">{t(`type`)}</label>
-            <Select
-              value={orgType}
-              onValueChange={(value: OrgType) => setOrgType(value)}
-            >
-              <SelectTrigger>
-                <SelectValue placeholder={t("select_organization_type")} />
-              </SelectTrigger>
-              <SelectContent>
-                {ORG_TYPES.map((type) => (
-                  <SelectItem key={type.value} value={type.value}>
-                    {type.label}
-                  </SelectItem>
-                ))}
-              </SelectContent>
-            </Select>
-          </div>
-
-          <div className="space-y-2">
-            <label className="text-sm font-medium">Description</label>
-            <Textarea
-              value={description}
-              onChange={(e) => setDescription(e.target.value)}
-              placeholder={t("enter_department_team_description")}
+
+            <FormField
+              control={form.control}
+              name="description"
+              render={({ field }) => (
+                <FormItem className="space-y-2">
+                  <FormLabel>{t("description")}</FormLabel>
+                  <FormControl>
+                    <Textarea
+                      {...field}
+                      placeholder={t("enter_department_team_description")}
+                    />
+                  </FormControl>
+                  <FormMessage />
+                </FormItem>
+              )}
             />
-          </div>
 
-          <Button
-            className="w-full"
-            onClick={handleSubmit}
-            disabled={isPending || !name.trim()}
-          >
-            {isPending ? t("creating") : t("create_organization")}
-          </Button>
-        </div>
+            <Button type="submit" className="w-full" disabled={isPending}>
+              {isPending
+                ? isEditMode
+                  ? t("updating")
+                  : t("creating")
+                : isEditMode
+                  ? t("update_organization")
+                  : t("create_organization")}
+            </Button>
+          </form>
+        </Form>
       </SheetContent>
     </Sheet>
   );
diff --git a/src/types/facilityOrganization/facilityOrganization.ts b/src/types/facilityOrganization/facilityOrganization.ts
index 8f5122610bf..b5a583839c6 100644
--- a/src/types/facilityOrganization/facilityOrganization.ts
+++ b/src/types/facilityOrganization/facilityOrganization.ts
@@ -32,6 +32,10 @@ export interface FacilityOrganizationCreate {
   parent?: string;
 }
 
+export interface FacilityOrganizationEdit extends FacilityOrganizationCreate {
+  facility: string;
+}
+
 export interface FacilityOrganizationUserRole {
   id: string;
   user: UserBase;
diff --git a/src/types/facilityOrganization/facilityOrganizationApi.ts b/src/types/facilityOrganization/facilityOrganizationApi.ts
index f87e26fadc6..5eb7b600c4b 100644
--- a/src/types/facilityOrganization/facilityOrganizationApi.ts
+++ b/src/types/facilityOrganization/facilityOrganizationApi.ts
@@ -3,6 +3,7 @@ import { PaginatedResponse } from "@/Utils/request/types";
 import {
   FacilityOrganization,
   FacilityOrganizationCreate,
+  FacilityOrganizationEdit,
   FacilityOrganizationResponse,
 } from "@/types/facilityOrganization/facilityOrganization";
 import { OrganizationUserRole } from "@/types/organization/organization";
@@ -29,6 +30,12 @@ export default {
     TRes: Type<FacilityOrganization>(),
     TBody: Type<FacilityOrganizationCreate>(),
   },
+  update: {
+    path: "/api/v1/facility/{facilityId}/organizations/{organizationId}/",
+    method: HttpMethod.PUT,
+    TRes: Type<FacilityOrganization>(),
+    TBody: Type<FacilityOrganizationEdit>(),
+  },
   listUsers: {
     path: "/api/v1/facility/{facilityId}/organizations/{organizationId}/users/",
     method: HttpMethod.GET,


Reviews:
user: login: coderabbitai[bot]
body: **Actionable comments posted: 1**

<details>
<summary>🧹 Nitpick comments (3)</summary><blockquote>

<details>
<summary>public/locale/en.json (1)</summary><blockquote>

`820-820`: **Punctuation Consistency in Description**  
The existing key `"create_department_team_description"` has been modified by removing the period at the end. This aligns with the style of other description texts in the file. Please verify that this change is consistent with your UI guidelines.

</blockquote></details>
<details>
<summary>src/pages/Facility/settings/organizations/components/FacilityOrganizationFormSheet.tsx (2)</summary><blockquote>

`192-193`: **Add translations for form field labels**

Form labels "Name" and "Description" are not using the translation function, unlike other text in the component. For consistency and to support internationalization, consider using the translation function.


```diff
-                  <FormLabel>Name</FormLabel>
+                  <FormLabel>{t("name")}</FormLabel>
```

```diff
-                  <FormLabel>Description</FormLabel>
+                  <FormLabel>{t("description")}</FormLabel>
```


Also applies to: 236-237

---

`67-262`: **Consider form reset on cancel for create mode**

While the form is properly reset after successful submission and when entering edit mode (via useEffect), there's no explicit reset when the user closes the sheet without submitting in create mode. Consider adding this to ensure a clean state when reopening the form.


You could modify the `onOpenChange` handler to reset the form when closing in create mode:

```diff
-    <Sheet open={open} onOpenChange={setOpen}>
+    <Sheet 
+      open={open} 
+      onOpenChange={(newOpen) => {
+        setOpen(newOpen);
+        if (!newOpen && !isEditMode) {
+          form.reset();
+        }
+      }}
+    >
```

</blockquote></details>

</blockquote></details>

<details>
<summary>📜 Review details</summary>

**Configuration used: CodeRabbit UI**
**Review profile: CHILL**
**Plan: Pro**

<details>
<summary>📥 Commits</summary>

Reviewing files that changed from the base of the PR and between 76fc376b961e31ec998fcd5edb423b571eeed172 and 33e85c0b89d04bd2e3f087189294c520a012f5a9.

</details>

<details>
<summary>📒 Files selected for processing (6)</summary>

* `public/locale/en.json` (4 hunks)
* `src/pages/Facility/settings/organizations/FacilityOrganizationView.tsx` (6 hunks)
* `src/pages/Facility/settings/organizations/components/CreateFacilityOrganizationSheet.tsx` (0 hunks)
* `src/pages/Facility/settings/organizations/components/FacilityOrganizationFormSheet.tsx` (1 hunks)
* `src/types/facilityOrganization/facilityOrganization.ts` (1 hunks)
* `src/types/facilityOrganization/facilityOrganizationApi.ts` (2 hunks)

</details>

<details>
<summary>💤 Files with no reviewable changes (1)</summary>

* src/pages/Facility/settings/organizations/components/CreateFacilityOrganizationSheet.tsx

</details>

<details>
<summary>🧰 Additional context used</summary>

<details>
<summary>🧬 Code Definitions (3)</summary>

<details>
<summary>src/types/facilityOrganization/facilityOrganizationApi.ts (2)</summary><blockquote>

<details>
<summary>src/Utils/request/api.tsx (1)</summary>

* `Type` (48-50)

</details>
<details>
<summary>src/types/facilityOrganization/facilityOrganization.ts (2)</summary>

* `FacilityOrganization` (15-26)
* `FacilityOrganizationEdit` (35-41)

</details>

</blockquote></details>
<details>
<summary>src/pages/Facility/settings/organizations/FacilityOrganizationView.tsx (3)</summary><blockquote>

<details>
<summary>src/types/facilityOrganization/facilityOrganization.ts (1)</summary>

* `FacilityOrganization` (15-26)

</details>
<details>
<summary>src/pages/Facility/settings/organizations/components/FacilityOrganizationFormSheet.tsx (1)</summary>

* `FacilityOrganizationFormSheet` (67-262)

</details>
<details>
<summary>src/common/Permissions.tsx (1)</summary>

* `getPermissions` (191-350)

</details>

</blockquote></details>
<details>
<summary>src/pages/Facility/settings/organizations/components/FacilityOrganizationFormSheet.tsx (1)</summary><blockquote>

<details>
<summary>src/types/facilityOrganization/facilityOrganization.ts (3)</summary>

* `FacilityOrganization` (15-26)
* `FacilityOrganizationCreate` (28-33)
* `FacilityOrganizationEdit` (35-41)

</details>

</blockquote></details>

</details>

</details>

<details>
<summary>⏰ Context from checks skipped due to timeout of 90000ms (1)</summary>

* GitHub Check: cypress-run (1)

</details>

<details>
<summary>🔇 Additional comments (20)</summary><blockquote>

<details>
<summary>src/types/facilityOrganization/facilityOrganization.ts (1)</summary>

`35-41`: **Interface implementation looks good!**

The new `FacilityOrganizationEdit` interface properly defines the structure needed for editing facility organizations. Including the `facility` field as a required parameter makes sense for the edit operation, while keeping the rest of the structure similar to the existing `FacilityOrganizationCreate` interface.

</details>
<details>
<summary>src/types/facilityOrganization/facilityOrganizationApi.ts (2)</summary>

`6-6`: **Correct import of the new interface.**

The import statement has been properly updated to include the new `FacilityOrganizationEdit` interface.

---

`33-38`: **Good implementation of the update endpoint.**

The new `update` method follows RESTful principles with:
- Appropriate HTTP PUT method for updates
- Well-structured path parameters for both facility and organization IDs
- Correct response and request body types

This implementation aligns perfectly with the PR objective to add an edit option for departments/teams.

</details>
<details>
<summary>src/pages/Facility/settings/organizations/FacilityOrganizationView.tsx (6)</summary>

`23-23`: **Good component import.**

Correctly importing the new `FacilityOrganizationFormSheet` component that handles both creation and editing functionality.

---

`31-41`: **Props structure enhanced appropriately.**

The `OrganizationCard` component now accepts additional props needed for the edit functionality:
- `facilityId` for API requests
- `parentId` for hierarchy management
- `editPermission` to control the visibility of the edit option

This is a good approach to extend the component's functionality while maintaining backward compatibility.

---

`60-78`: **Well-structured UI update for edit functionality.**

The changes effectively:
1. Wrap the existing button and new form sheet in a flex container for proper horizontal alignment
2. Conditionally render the edit form sheet based on user permissions
3. Pass the necessary props to the form sheet component

The UI changes are clean and maintain the existing design pattern.

---

`120-121`: **Good permission handling.**

Appropriately retrieving the `canManageFacilityOrganization` permission to control access to the edit functionality.

---

`145-148`: **Consistent component usage for create functionality.**

Using the same `FacilityOrganizationFormSheet` component for both creating and editing organizations is a good pattern that reduces code duplication.

---

`163-169`: **Properly passing props to child component.**

All necessary props are correctly passed to the `OrganizationCard` component:
- `editPermission` based on the user's permissions
- `facilityId` for API requests
- `parentId` for maintaining the organization hierarchy

This ensures that the edit functionality is available only to users with appropriate permissions.

</details>
<details>
<summary>public/locale/en.json (3)</summary>

`1035-1036`: **Addition of Edit Department/Team Keys**  
The new keys `"edit_department_team"` and `"edit_department_team_description"` have been added with clear and concise wording. They appropriately support the new Edit option for departments/teams in the UI. Confirm that these keys are correctly integrated with the corresponding components.

---

`1948-1948`: **New Success Message for Organization Update**  
The key `"organization_updated_successfully"` has been introduced to provide feedback when an organization update is performed. Its phrasing is clear; please ensure that its style (capitalization, punctuation, etc.) is consistent with other similar success messages in the application.

---

`2836-2836`: **Addition of Update Organization Button Text**  
The new key `"update_organization"` with the value `"Update Organization"` has been added to support the action text of the organization update functionality. Verify that this text meets the design and localization requirements in the UI.

</details>
<details>
<summary>src/pages/Facility/settings/organizations/components/FacilityOrganizationFormSheet.tsx (8)</summary>

`59-65`: **Form schema validation looks good**

The Zod schema properly validates required fields and organization types. The type inference for form values creates a strong TypeScript integration.

---

`85-93`: **Good implementation of form reset for edit mode**

The useEffect hook properly resets form values when in edit mode and when the component is opened. This ensures the form is correctly populated with existing organization data.

---

`95-118`: **Creation mutation implementation is well structured**

The create mutation correctly handles success and error scenarios, invalidates relevant queries, and provides user feedback through toast notifications.

---

`138-151`: **Form submission logic is correct**

The onSubmit function properly handles both create and update operations, trims input values, and conditionally includes the parentId. The logic for determining which mutation to call based on edit mode is also correct.

---

`158-168`: **Contextual trigger button implementation is good**

The component intelligently renders different button styles and labels based on whether it's being used for editing (showing "Edit") or creation (showing "Add department/team"). This provides good visual differentiation for users.

---

`170-181`: **Dynamic sheet title and description based on mode**

The header adapts correctly to the current mode (edit or create) and uses appropriate translations for both title and description.

---

`248-256`: **Well-implemented submit button with dynamic text**

The submit button correctly displays different text based on both the form mode (edit/create) and the loading state (pending/idle). It also properly disables during form submission to prevent double submissions.

---

`1-45`: **Imports and dependencies are appropriate**

All necessary imports for form handling, UI components, API integration, and type definitions are properly included. The component structure follows good organization practices.

</details>

</blockquote></details>

</details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-04-03T20:00:00Z
user: login: AdityaJ2305
state: COMMENTED
author_association: MEMBER
submitted_at: 2025-04-03T20:01:08Z
user: login: coderabbitai[bot]
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-04-03T20:04:07Z
user: login: coderabbitai[bot]
body: **Actionable comments posted: 0**

<details>
<summary>🧹 Nitpick comments (1)</summary><blockquote>

<details>
<summary>src/pages/Facility/settings/organizations/components/FacilityOrganizationFormSheet.tsx (1)</summary><blockquote>

`52-55`: **Optional: Externalize organization types for future expansion.**

Defining `ORG_TYPES` inline is workable now but might become cumbersome if you add more types later. Consider moving them into a dedicated constants file or typed enum for cleaner maintenance and reuse.

</blockquote></details>

</blockquote></details>

<details>
<summary>📜 Review details</summary>

**Configuration used: CodeRabbit UI**
**Review profile: CHILL**
**Plan: Pro**

<details>
<summary>📥 Commits</summary>

Reviewing files that changed from the base of the PR and between 33e85c0b89d04bd2e3f087189294c520a012f5a9 and 7c0f3ee88008bfa7c39e01c5667e288d9733d12c.

</details>

<details>
<summary>📒 Files selected for processing (2)</summary>

* `.env` (1 hunks)
* `src/pages/Facility/settings/organizations/components/FacilityOrganizationFormSheet.tsx` (1 hunks)

</details>

<details>
<summary>🧰 Additional context used</summary>

<details>
<summary>🧠 Learnings (1)</summary>

<details>
<summary>src/pages/Facility/settings/organizations/components/FacilityOrganizationFormSheet.tsx (1)</summary>

```
Learnt from: AdityaJ2305
PR: ohcnetwork/care_fe#11719
File: src/pages/Facility/settings/organizations/components/FacilityOrganizationFormSheet.tsx:120-136
Timestamp: 2025-04-03T20:01:56.211Z
Learning: The codebase has a global error handler that can take care of API errors, including handling errors from mutations like updateOrganization.
```

</details>

</details><details>
<summary>🧬 Code Definitions (1)</summary>

<details>
<summary>src/pages/Facility/settings/organizations/components/FacilityOrganizationFormSheet.tsx (1)</summary><blockquote>

<details>
<summary>src/types/facilityOrganization/facilityOrganization.ts (3)</summary>

* `FacilityOrganization` (15-26)
* `FacilityOrganizationCreate` (28-33)
* `FacilityOrganizationEdit` (35-41)

</details>

</blockquote></details>

</details>

</details>

<details>
<summary>⏰ Context from checks skipped due to timeout of 90000ms (1)</summary>

* GitHub Check: cypress-run (1)

</details>

<details>
<summary>🔇 Additional comments (3)</summary><blockquote>

<details>
<summary>.env (1)</summary>

`12-12`: **Confirm appropriateness of switching to localhost endpoint.**

You've changed the `REACT_CARE_API_URL` from a production URL to a localhost URL. Please ensure that this change is intentional for development or testing, and won't inadvertently affect your production environment.

</details>
<details>
<summary>src/pages/Facility/settings/organizations/components/FacilityOrganizationFormSheet.tsx (2)</summary>

`59-66`: **Great usage of Zod for schema validation.**

Enforcing a minimum length for the name field and optional description aligns well with validation best practices, ensuring safe and consistent inputs.

---

`123-139`: **Confirm reliance on the global error handler for update mutations.**

Unlike the create mutation, the update mutation doesn't have an explicit `onError` callback. If you're depending on the global error handler to process update errors, please verify that it provides sufficient user feedback (e.g., toast messages). Otherwise, consider replicating the explicit error handling logic for clarity and consistency.

</details>

</blockquote></details>

</details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-04-03T20:15:24Z
user: login: coderabbitai[bot]
body: **Actionable comments posted: 0**

<details>
<summary>🧹 Nitpick comments (1)</summary><blockquote>

<details>
<summary>src/pages/Facility/settings/organizations/components/FacilityOrganizationFormSheet.tsx (1)</summary><blockquote>

`88-96`: **Consider adding parent ID to dependency array**

Currently, the effect resets the form whenever `isEditMode`, `org`, or `open` changes. If you intend to reset the form when the `parentId` changes, you may include `[parentId]` in the dependencies.  

```diff
 useEffect(() => {
   if (isEditMode && org) {
     form.reset({
       name: org.name || "",
       description: org.description || "",
       org_type: org.org_type as OrgType,
     });
   }
-}, [isEditMode, org, open]);
+}, [isEditMode, org, open, parentId]);
```

</blockquote></details>

</blockquote></details>

<details>
<summary>📜 Review details</summary>

**Configuration used: CodeRabbit UI**
**Review profile: CHILL**
**Plan: Pro**

<details>
<summary>📥 Commits</summary>

Reviewing files that changed from the base of the PR and between 7c0f3ee88008bfa7c39e01c5667e288d9733d12c and b590bb6f4e133b3c3f4aa0aadd6fde7abaa88f37.

</details>

<details>
<summary>📒 Files selected for processing (2)</summary>

* `public/locale/en.json` (5 hunks)
* `src/pages/Facility/settings/organizations/components/FacilityOrganizationFormSheet.tsx` (1 hunks)

</details>

<details>
<summary>🚧 Files skipped from review as they are similar to previous changes (1)</summary>

* public/locale/en.json

</details>

<details>
<summary>🧰 Additional context used</summary>

<details>
<summary>🧠 Learnings (1)</summary>

<details>
<summary>src/pages/Facility/settings/organizations/components/FacilityOrganizationFormSheet.tsx (1)</summary>

```
Learnt from: AdityaJ2305
PR: ohcnetwork/care_fe#11719
File: src/pages/Facility/settings/organizations/components/FacilityOrganizationFormSheet.tsx:120-136
Timestamp: 2025-04-03T20:01:56.211Z
Learning: The codebase has a global error handler that can take care of API errors, including handling errors from mutations like updateOrganization.
```

</details>

</details><details>
<summary>🧬 Code Definitions (1)</summary>

<details>
<summary>src/pages/Facility/settings/organizations/components/FacilityOrganizationFormSheet.tsx (1)</summary><blockquote>

<details>
<summary>src/types/facilityOrganization/facilityOrganization.ts (3)</summary>

* `FacilityOrganization` (15-26)
* `FacilityOrganizationCreate` (28-33)
* `FacilityOrganizationEdit` (35-41)

</details>

</blockquote></details>

</details>

</details>

<details>
<summary>⏰ Context from checks skipped due to timeout of 90000ms (1)</summary>

* GitHub Check: cypress-run (1)

</details>

<details>
<summary>🔇 Additional comments (3)</summary><blockquote>

<details>
<summary>src/pages/Facility/settings/organizations/components/FacilityOrganizationFormSheet.tsx (3)</summary>

`59-66`: **Confirm editing scope aligns with the original requirement**

You've allowed editing of both the organization’s name and description, whereas the original issue #11319 primarily mentioned editing only the name. Please confirm if this broader edit scope is intentional or if you prefer it limited to just the name.

---

`123-139`: **Error handling is missing in the update mutation**  
A previous review has already suggested adding explicit error handling here for consistency with the create mutation. You mentioned a global error handler covers it, which is valid. If you prefer complete consistency with the create flow, you can either remove onError from the create mutation or replicate it here.

---

`1-265`: **Overall, well-structured with effective React Hook Form integration**  
The component is clear, uses Zod for validation, and cleanly handles create and edit flows. Good job!

</details>

</blockquote></details>

</details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-04-03T20:26:42Z
user: login: Jacobjeevan
state: CHANGES_REQUESTED
author_association: CONTRIBUTOR
submitted_at: 2025-04-04T05:16:45Z
user: login: AdityaJ2305
state: COMMENTED
author_association: MEMBER
submitted_at: 2025-04-04T08:03:35Z
user: login: AdityaJ2305
state: COMMENTED
author_association: MEMBER
submitted_at: 2025-04-04T08:04:47Z
user: login: AdityaJ2305
state: COMMENTED
author_association: MEMBER
submitted_at: 2025-04-04T08:06:11Z
user: login: AdityaJ2305
state: COMMENTED
author_association: MEMBER
submitted_at: 2025-04-04T09:31:05Z
user: login: Jacobjeevan
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-04-04T09:41:30Z
user: login: Jacobjeevan
state: APPROVED
author_association: CONTRIBUTOR
submitted_at: 2025-04-07T09:14:12Z
user: login: coderabbitai[bot]
body: **Actionable comments posted: 1**

<details>
<summary>🧹 Nitpick comments (3)</summary><blockquote>

<details>
<summary>src/pages/Facility/settings/organizations/components/CreateFacilityOrganizationSheet.tsx (3)</summary><blockquote>

`70-74`: **Component name doesn't match filename.**

The component has been renamed to `FacilityOrganizationFormSheet` but the filename is still `CreateFacilityOrganizationSheet.tsx`. This discrepancy could lead to confusion when importing or using this component.

Consider renaming the file to match the component name:

```diff
-// CreateFacilityOrganizationSheet.tsx
+// FacilityOrganizationFormSheet.tsx
```

---

`88-96`: **Form reset effect uses open state as dependency.**

The effect to reset the form when in edit mode includes `open` in its dependency array. This means the form will be reset whenever the sheet is opened or closed, which could lead to unintended form resets if the user has already started editing.

Consider modifying the effect to only reset the form when initially opening in edit mode:

```diff
useEffect(() => {
-  if (isEditMode && org) {
+  if (isEditMode && org && open) {
    form.reset({
      name: org.name || "",
      description: org.description || "",
      org_type: org.org_type as OrgType,
    });
  }
-}, [isEditMode, org, open]);
+}, [isEditMode, org, open, form.reset]);
```

---

`207-232`: **Consider disabling org_type field in edit mode.**

In the PR objectives, there was a discussion about whether the org_type should be editable. Consider disabling this field in edit mode if it shouldn't be editable.

Modify the org_type field to be disabled in edit mode:

```diff
<FormField
  control={form.control}
  name="org_type"
  render={({ field }) => (
    <FormItem className="space-y-2">
      <FormLabel>{t(`type`)}</FormLabel>
-      <Select value={field.value} onValueChange={field.onChange}>
+      <Select value={field.value} onValueChange={field.onChange} disabled={isEditMode}>
        <FormControl>
          <SelectTrigger>
            <SelectValue
              placeholder={t("select_organization_type")}
            />
          </SelectTrigger>
        </FormControl>
        <SelectContent>
          {ORG_TYPES.map((type) => (
            <SelectItem key={type.value} value={type.value}>
              {t(type.label)}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>
      <FormMessage />
    </FormItem>
  )}
/>
```

</blockquote></details>

</blockquote></details>

<details>
<summary>📜 Review details</summary>

**Configuration used: CodeRabbit UI**
**Review profile: CHILL**
**Plan: Pro**

<details>
<summary>📥 Commits</summary>

Reviewing files that changed from the base of the PR and between 98df8c99018269954b9d8743b64df5ee64667b5d and df2761fe4034ff47eb2f9a06ec8e907086e3b16c.

</details>

<details>
<summary>📒 Files selected for processing (2)</summary>

* `src/pages/Facility/settings/organizations/FacilityOrganizationView.tsx` (6 hunks)
* `src/pages/Facility/settings/organizations/components/CreateFacilityOrganizationSheet.tsx` (4 hunks)

</details>

<details>
<summary>🚧 Files skipped from review as they are similar to previous changes (1)</summary>

* src/pages/Facility/settings/organizations/FacilityOrganizationView.tsx

</details>

<details>
<summary>🧰 Additional context used</summary>

<details>
<summary>🧠 Learnings (1)</summary>

<details>
<summary>src/pages/Facility/settings/organizations/components/CreateFacilityOrganizationSheet.tsx (1)</summary>

```
Learnt from: AdityaJ2305
PR: ohcnetwork/care_fe#11719
File: src/pages/Facility/settings/organizations/components/FacilityOrganizationFormSheet.tsx:120-136
Timestamp: 2025-04-03T20:01:56.211Z
Learning: The codebase has a global error handler that can take care of API errors, including handling errors from mutations like updateOrganization.
```

</details>

</details><details>
<summary>🧬 Code Definitions (1)</summary>

<details>
<summary>src/pages/Facility/settings/organizations/components/CreateFacilityOrganizationSheet.tsx (2)</summary><blockquote>

<details>
<summary>src/types/facilityOrganization/facilityOrganization.ts (2)</summary>

* `FacilityOrganization` (15-26)
* `FacilityOrganizationEdit` (35-37)

</details>
<details>
<summary>src/components/ui/input.tsx (1)</summary>

* `Input` (28-28)

</details>

</blockquote></details>

</details>

</details>

<details>
<summary>⏰ Context from checks skipped due to timeout of 90000ms (1)</summary>

* GitHub Check: cypress-run (1)

</details>

<details>
<summary>🔇 Additional comments (6)</summary><blockquote>

<details>
<summary>src/pages/Facility/settings/organizations/components/CreateFacilityOrganizationSheet.tsx (6)</summary>

`1-8`: **Good use of react-hook-form and Zod for form validation.**

The implementation of form validation with react-hook-form and Zod provides robust type safety and validation for the form data. This improves code quality and user experience by preventing invalid submissions.

---

`46-50`: **Component supports edit mode with clear type definition.**

The addition of the optional `org` prop enables the component to function in both create and edit modes, with proper typing to ensure type safety.

---

`59-68`: **Well-structured form schema with appropriate validation rules.**

The Zod schema provides proper validation for all fields with appropriate rules:
- Required name with minimum length validation
- Optional description
- Enumerated org_type validation

The derived FormValues type ensures type safety throughout the component.

---

`149-154`: **Clean conditional logic for create/update operations.**

The implementation elegantly handles both create and update operations based on the edit mode, with proper data preparation before submission.

---

`251-259`: **Good UX with dynamic button text based on operation state.**

The button text changes based on the current operation (creating/updating) and pending state, providing clear feedback to the user about what's happening.

---

`161-170`: <details>
<summary>✅ Verification successful</summary>

**Consider hiding edit button for Root organization.**

According to the PR objectives, the Root organization should not be editable. There's currently no check to hide the edit button for the Root organization.

Add logic to hide the edit button for Root organization:

```diff
{isEditMode ? (
+  org?.org_type !== "root" ? (
    <Button variant="white" size="sm" className="font-semibold">
      {t("edit")}
    </Button>
+  ) : null
) : (
  <Button>
    <CareIcon icon="l-plus" className="mr-2 size-4" />
    {t("add_department_team")}
  </Button>
)}
```

Let's verify whether the organization has a type property that identifies it as Root:

---

🏁 Script executed:

```shell
#!/bin/bash
# Check if organization has a type property that identifies it as Root
rg -A 3 "type\s*=?\s*['\"]\s*root" --type ts
```

Length of output: 371

---



</details>

**Hide Edit Button for Root Organization**  
The review comment stands valid. The organization’s type is indeed defined in `src/types/facilityOrganization/facilityOrganization.ts` as `"root" | "dept" | "team"`. To comply with the PR objectives, please update the logic so that when in edit mode, the edit button is hidden if `org?.org_type === "root"`. For example:

```diff
{isEditMode ? (
+  org?.org_type !== "root" ? (
    <Button variant="white" size="sm" className="font-semibold">
      {t("edit")}
    </Button>
+  ) : null
) : (
  <Button>
    <CareIcon icon="l-plus" className="mr-2 size-4" />
    {t("add_department_team")}
  </Button>
)}
```

</details>

</blockquote></details>

</details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-04-07T09:15:39Z
user: login: AdityaJ2305
state: COMMENTED
author_association: MEMBER
submitted_at: 2025-04-07T09:17:32Z
user: login: coderabbitai[bot]
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-04-07T09:17:56Z
user: login: rithviknishad
state: APPROVED
author_association: MEMBER
submitted_at: 2025-04-07T17:07:27Z

Review comments:
diff_hunk: @@ -0,0 +1,262 @@
+import { zodResolver } from "@hookform/resolvers/zod";
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import { t } from "i18next";
+import { useEffect, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import * as z from "zod";
+
+import CareIcon from "@/CAREUI/icons/CareIcon";
+
+import { Button } from "@/components/ui/button";
+import {
+  Form,
+  FormControl,
+  FormField,
+  FormItem,
+  FormLabel,
+  FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import {
+  Select,
+  SelectContent,
+  SelectItem,
+  SelectTrigger,
+  SelectValue,
+} from "@/components/ui/select";
+import {
+  Sheet,
+  SheetContent,
+  SheetDescription,
+  SheetHeader,
+  SheetTitle,
+  SheetTrigger,
+} from "@/components/ui/sheet";
+import { Textarea } from "@/components/ui/textarea";
+
+import mutate from "@/Utils/request/mutate";
+import {
+  FacilityOrganization,
+  FacilityOrganizationCreate,
+  FacilityOrganizationEdit,
+} from "@/types/facilityOrganization/facilityOrganization";
+import facilityOrganizationApi from "@/types/facilityOrganization/facilityOrganizationApi";
+
+interface Props {
+  facilityId: string;
+  parentId?: string;
+  org?: FacilityOrganization;
+}
+
+const ORG_TYPES = [
+  { value: "dept", label: "Department" },
+  { value: "team", label: "Team" },
+] as const;
+
+type OrgType = (typeof ORG_TYPES)[number]["value"];
+
+const formSchema = z.object({
+  name: z.string().min(1, { message: t("field_required") }),
+  description: z.string().optional(),
+  org_type: z.enum(["dept", "team"]),
+});
+
+type FormValues = z.infer<typeof formSchema>;
+
+export default function FacilityOrganizationFormSheet({
+  facilityId,
+  parentId,
+  org,
+}: Props) {
+  const isEditMode = !!org;
+  const queryClient = useQueryClient();
+  const [open, setOpen] = useState(false);
+
+  const form = useForm<FormValues>({
+    resolver: zodResolver(formSchema),
+    defaultValues: {
+      name: "",
+      description: "",
+      org_type: "dept" as OrgType,
+    },
+  });
+
+  useEffect(() => {
+    if (isEditMode && org) {
+      form.reset({
+        name: org.name || "",
+        description: org.description || "",
+        org_type: org.org_type as OrgType,
+      });
+    }
+  }, [isEditMode, org, open]);
+
+  const { mutate: createOrganization, isPending: isCreating } = useMutation({
+    mutationFn: (body: FacilityOrganizationCreate) =>
+      mutate(facilityOrganizationApi.create, {
+        pathParams: { facilityId },
+        body,
+      })(body),
+    onSuccess: () => {
+      queryClient.invalidateQueries({
+        queryKey: ["facilityOrganization", "list", facilityId, parentId],
+      });
+      queryClient.invalidateQueries({
+        queryKey: ["getCurrentUser"],
+      });
+      toast.success(t("organization_created_successfully"));
+      setOpen(false);
+      form.reset();
+    },
+    onError: (error) => {
+      const errorData = error.cause as { errors: { msg: string }[] };
+      errorData.errors.forEach((er) => {
+        toast.error(er.msg);
+      });
+    },
+  });
+
+  const { mutate: updateOrganization, isPending: isUpdating } = useMutation({
+    mutationFn: (body: FacilityOrganizationEdit) =>
+      mutate(facilityOrganizationApi.update, {
+        pathParams: { facilityId, organizationId: org?.id },
+        body,
+      })(body),
+    onSuccess: () => {
+      queryClient.invalidateQueries({
+        queryKey: ["facilityOrganization", "list", facilityId, parentId],
+      });
+      queryClient.invalidateQueries({
+        queryKey: ["getCurrentUser"],
+      });
+      toast.success(t("organization_updated_successfully"));
+      setOpen(false);
+    },
+  });
path: src/pages/Facility/settings/organizations/components/FacilityOrganizationFormSheet.tsx
user: login: coderabbitai[bot]
body: _🛠️ Refactor suggestion_

**Add error handling for update mutation**

Unlike the create mutation, the update mutation lacks error handling. This could lead to silent failures if the update operation encounters errors.


```diff
  const { mutate: updateOrganization, isPending: isUpdating } = useMutation({
    mutationFn: (body: FacilityOrganizationEdit) =>
      mutate(facilityOrganizationApi.update, {
        pathParams: { facilityId, organizationId: org?.id },
        body,
      })(body),
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: ["facilityOrganization", "list", facilityId, parentId],
      });
      queryClient.invalidateQueries({
        queryKey: ["getCurrentUser"],
      });
      toast.success(t("organization_updated_successfully"));
      setOpen(false);
    },
+   onError: (error) => {
+     const errorData = error.cause as { errors: { msg: string }[] };
+     errorData.errors.forEach((er) => {
+       toast.error(er.msg);
+     });
+   },
  });
```


<!-- suggestion_start -->

<details>
<summary>📝 Committable suggestion</summary>

> ‼️ **IMPORTANT**
> Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

`````suggestion
  const { mutate: updateOrganization, isPending: isUpdating } = useMutation({
    mutationFn: (body: FacilityOrganizationEdit) =>
      mutate(facilityOrganizationApi.update, {
        pathParams: { facilityId, organizationId: org?.id },
        body,
      })(body),
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: ["facilityOrganization", "list", facilityId, parentId],
      });
      queryClient.invalidateQueries({
        queryKey: ["getCurrentUser"],
      });
      toast.success(t("organization_updated_successfully"));
      setOpen(false);
    },
    onError: (error) => {
      const errorData = error.cause as { errors: { msg: string }[] };
      errorData.errors.forEach((er) => {
        toast.error(er.msg);
      });
    },
  });
`````

</details>

<!-- suggestion_end -->

<!-- This is an auto-generated reply by CodeRabbit -->
created_at: 2025-04-03T19:59:59Z
author_association: CONTRIBUTOR
diff_hunk: @@ -0,0 +1,262 @@
+import { zodResolver } from "@hookform/resolvers/zod";
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import { t } from "i18next";
+import { useEffect, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import * as z from "zod";
+
+import CareIcon from "@/CAREUI/icons/CareIcon";
+
+import { Button } from "@/components/ui/button";
+import {
+  Form,
+  FormControl,
+  FormField,
+  FormItem,
+  FormLabel,
+  FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import {
+  Select,
+  SelectContent,
+  SelectItem,
+  SelectTrigger,
+  SelectValue,
+} from "@/components/ui/select";
+import {
+  Sheet,
+  SheetContent,
+  SheetDescription,
+  SheetHeader,
+  SheetTitle,
+  SheetTrigger,
+} from "@/components/ui/sheet";
+import { Textarea } from "@/components/ui/textarea";
+
+import mutate from "@/Utils/request/mutate";
+import {
+  FacilityOrganization,
+  FacilityOrganizationCreate,
+  FacilityOrganizationEdit,
+} from "@/types/facilityOrganization/facilityOrganization";
+import facilityOrganizationApi from "@/types/facilityOrganization/facilityOrganizationApi";
+
+interface Props {
+  facilityId: string;
+  parentId?: string;
+  org?: FacilityOrganization;
+}
+
+const ORG_TYPES = [
+  { value: "dept", label: "Department" },
+  { value: "team", label: "Team" },
+] as const;
+
+type OrgType = (typeof ORG_TYPES)[number]["value"];
+
+const formSchema = z.object({
+  name: z.string().min(1, { message: t("field_required") }),
+  description: z.string().optional(),
+  org_type: z.enum(["dept", "team"]),
+});
+
+type FormValues = z.infer<typeof formSchema>;
+
+export default function FacilityOrganizationFormSheet({
+  facilityId,
+  parentId,
+  org,
+}: Props) {
+  const isEditMode = !!org;
+  const queryClient = useQueryClient();
+  const [open, setOpen] = useState(false);
+
+  const form = useForm<FormValues>({
+    resolver: zodResolver(formSchema),
+    defaultValues: {
+      name: "",
+      description: "",
+      org_type: "dept" as OrgType,
+    },
+  });
+
+  useEffect(() => {
+    if (isEditMode && org) {
+      form.reset({
+        name: org.name || "",
+        description: org.description || "",
+        org_type: org.org_type as OrgType,
+      });
+    }
+  }, [isEditMode, org, open]);
+
+  const { mutate: createOrganization, isPending: isCreating } = useMutation({
+    mutationFn: (body: FacilityOrganizationCreate) =>
+      mutate(facilityOrganizationApi.create, {
+        pathParams: { facilityId },
+        body,
+      })(body),
+    onSuccess: () => {
+      queryClient.invalidateQueries({
+        queryKey: ["facilityOrganization", "list", facilityId, parentId],
+      });
+      queryClient.invalidateQueries({
+        queryKey: ["getCurrentUser"],
+      });
+      toast.success(t("organization_created_successfully"));
+      setOpen(false);
+      form.reset();
+    },
+    onError: (error) => {
+      const errorData = error.cause as { errors: { msg: string }[] };
+      errorData.errors.forEach((er) => {
+        toast.error(er.msg);
+      });
+    },
+  });
+
+  const { mutate: updateOrganization, isPending: isUpdating } = useMutation({
+    mutationFn: (body: FacilityOrganizationEdit) =>
+      mutate(facilityOrganizationApi.update, {
+        pathParams: { facilityId, organizationId: org?.id },
+        body,
+      })(body),
+    onSuccess: () => {
+      queryClient.invalidateQueries({
+        queryKey: ["facilityOrganization", "list", facilityId, parentId],
+      });
+      queryClient.invalidateQueries({
+        queryKey: ["getCurrentUser"],
+      });
+      toast.success(t("organization_updated_successfully"));
+      setOpen(false);
+    },
+  });
path: src/pages/Facility/settings/organizations/components/FacilityOrganizationFormSheet.tsx
user: login: AdityaJ2305
body: We have global error handler so that can take care of this 
created_at: 2025-04-03T20:01:08Z
author_association: MEMBER
diff_hunk: @@ -0,0 +1,262 @@
+import { zodResolver } from "@hookform/resolvers/zod";
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import { t } from "i18next";
+import { useEffect, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import * as z from "zod";
+
+import CareIcon from "@/CAREUI/icons/CareIcon";
+
+import { Button } from "@/components/ui/button";
+import {
+  Form,
+  FormControl,
+  FormField,
+  FormItem,
+  FormLabel,
+  FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import {
+  Select,
+  SelectContent,
+  SelectItem,
+  SelectTrigger,
+  SelectValue,
+} from "@/components/ui/select";
+import {
+  Sheet,
+  SheetContent,
+  SheetDescription,
+  SheetHeader,
+  SheetTitle,
+  SheetTrigger,
+} from "@/components/ui/sheet";
+import { Textarea } from "@/components/ui/textarea";
+
+import mutate from "@/Utils/request/mutate";
+import {
+  FacilityOrganization,
+  FacilityOrganizationCreate,
+  FacilityOrganizationEdit,
+} from "@/types/facilityOrganization/facilityOrganization";
+import facilityOrganizationApi from "@/types/facilityOrganization/facilityOrganizationApi";
+
+interface Props {
+  facilityId: string;
+  parentId?: string;
+  org?: FacilityOrganization;
+}
+
+const ORG_TYPES = [
+  { value: "dept", label: "Department" },
+  { value: "team", label: "Team" },
+] as const;
+
+type OrgType = (typeof ORG_TYPES)[number]["value"];
+
+const formSchema = z.object({
+  name: z.string().min(1, { message: t("field_required") }),
+  description: z.string().optional(),
+  org_type: z.enum(["dept", "team"]),
+});
+
+type FormValues = z.infer<typeof formSchema>;
+
+export default function FacilityOrganizationFormSheet({
+  facilityId,
+  parentId,
+  org,
+}: Props) {
+  const isEditMode = !!org;
+  const queryClient = useQueryClient();
+  const [open, setOpen] = useState(false);
+
+  const form = useForm<FormValues>({
+    resolver: zodResolver(formSchema),
+    defaultValues: {
+      name: "",
+      description: "",
+      org_type: "dept" as OrgType,
+    },
+  });
+
+  useEffect(() => {
+    if (isEditMode && org) {
+      form.reset({
+        name: org.name || "",
+        description: org.description || "",
+        org_type: org.org_type as OrgType,
+      });
+    }
+  }, [isEditMode, org, open]);
+
+  const { mutate: createOrganization, isPending: isCreating } = useMutation({
+    mutationFn: (body: FacilityOrganizationCreate) =>
+      mutate(facilityOrganizationApi.create, {
+        pathParams: { facilityId },
+        body,
+      })(body),
+    onSuccess: () => {
+      queryClient.invalidateQueries({
+        queryKey: ["facilityOrganization", "list", facilityId, parentId],
+      });
+      queryClient.invalidateQueries({
+        queryKey: ["getCurrentUser"],
+      });
+      toast.success(t("organization_created_successfully"));
+      setOpen(false);
+      form.reset();
+    },
+    onError: (error) => {
+      const errorData = error.cause as { errors: { msg: string }[] };
+      errorData.errors.forEach((er) => {
+        toast.error(er.msg);
+      });
+    },
+  });
+
+  const { mutate: updateOrganization, isPending: isUpdating } = useMutation({
+    mutationFn: (body: FacilityOrganizationEdit) =>
+      mutate(facilityOrganizationApi.update, {
+        pathParams: { facilityId, organizationId: org?.id },
+        body,
+      })(body),
+    onSuccess: () => {
+      queryClient.invalidateQueries({
+        queryKey: ["facilityOrganization", "list", facilityId, parentId],
+      });
+      queryClient.invalidateQueries({
+        queryKey: ["getCurrentUser"],
+      });
+      toast.success(t("organization_updated_successfully"));
+      setOpen(false);
+    },
+  });
path: src/pages/Facility/settings/organizations/components/FacilityOrganizationFormSheet.tsx
user: login: coderabbitai[bot]
body: @AdityaJ2305 I understand that you have a global error handler that can handle errors from the update mutation. I noticed that the create mutation still has explicit error handling while the update mutation doesn't. For consistency, would you prefer to keep the explicit handling only for create or remove it from there as well?



(⌐■_■)ノ

---
<details>
<summary>🧬 Code Definitions Used</summary>

### Relevant Code Snippets

#### Filename: `src/types/facilityOrganization/facilityOrganization.ts`

**Lines 15-26:**
```typescript
export interface FacilityOrganization {
  id: string;
  name: string;
  description?: string;
  org_type: org_type;
  level_cache: number;
  has_children: boolean;
  active: boolean;
  parent?: FacilityOrganizationParent;
  created_at: string;
  updated_at: string;
}
```
- **Description**: This interface defines the structure of a `FacilityOrganization` object, which includes properties such as `id`, `name`, `description`, `org_type`, and timestamps for creation and updates.

---

**Lines 28-33:**
```typescript
export interface FacilityOrganizationCreate {
  name: string;
  description?: string;
  org_type: org_type;
  parent?: string;
}
```
- **Description**: This interface outlines the required fields for creating a new `FacilityOrganization`. It includes `name`, an optional `description`, `org_type`, and an optional `parent` identifier.

---

**Lines 35-41:**
```typescript
export interface FacilityOrganizationEdit {
  name: string;
  description?: string;
  org_type: org_type;
  parent?: string;
  facility: string;
}
```
- **Description**: This interface specifies the structure for editing an existing `FacilityOrganization`. It includes `name`, an optional `description`, `org_type`, an optional `parent`, and a required `facility` identifier.

---

#### Filename: `src/components/ui/input.tsx`

**Lines 28-28:**
```typescript
Input
```
- **Description**: This is a reference to the `Input` component, which is used in the form for user input fields. It is likely a custom component that handles rendering and validation of input fields.

--- 

These snippets provide context on the data structures used for creating and editing facility organizations, which may be relevant to the global error handling mentioned in the user comment.

</details>
---
<details>
<summary>✏️ Learnings added</summary>

```
Learnt from: AdityaJ2305
PR: ohcnetwork/care_fe#11719
File: src/pages/Facility/settings/organizations/components/FacilityOrganizationFormSheet.tsx:120-136
Timestamp: 2025-04-03T20:01:55.112Z
Learning: The codebase has a global error handler that can take care of API errors, including handling errors from mutations like updateOrganization.
```

> Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure [review instructions](https://docs.coderabbit.ai/guides/review-instructions). You can manage existing learnings in the [app](https://app.coderabbit.ai/learnings).

</details>



<details>
<summary>Code Analysis Tools</summary>

## Tool Analysis Results
CodeRabbit ran static analysis tools on your files and found the following:
<toolResults></toolResults>

No specific issues were found in your files. You can proceed with your changes.

</details>

<!-- <agentComponentType>chat-answer</agentComponentType> -->

<!-- <rawResChunk><answer>@AdityaJ2305 I understand that you have a global error handler that can handle errors from the update mutation. I noticed that the create mutation still has explicit error handling while the update mutation doesn't. For consistency, would you prefer to keep the explicit handling only for create or remove it from there as well?



(⌐■_■)ノ

---

<details>
<summary>🧬 Code Definitions Used</summary>

### Relevant Code Snippets

#### Filename: `src/types/facilityOrganization/facilityOrganization.ts`

**Lines 15-26:**
```typescript
export interface FacilityOrganization {
  id: string;
  name: string;
  description?: string;
  org_type: org_type;
  level_cache: number;
  has_children: boolean;
  active: boolean;
  parent?: FacilityOrganizationParent;
  created_at: string;
  updated_at: string;
}
```
- **Description**: This interface defines the structure of a `FacilityOrganization` object, which includes properties such as `id`, `name`, `description`, `org_type`, and timestamps for creation and updates.

---

**Lines 28-33:**
```typescript
export interface FacilityOrganizationCreate {
  name: string;
  description?: string;
  org_type: org_type;
  parent?: string;
}
```
- **Description**: This interface outlines the required fields for creating a new `FacilityOrganization`. It includes `name`, an optional `description`, `org_type`, and an optional `parent` identifier.

---

**Lines 35-41:**
```typescript
export interface FacilityOrganizationEdit {
  name: string;
  description?: string;
  org_type: org_type;
  parent?: string;
  facility: string;
}
```
- **Description**: This interface specifies the structure for editing an existing `FacilityOrganization`. It includes `name`, an optional `description`, `org_type`, an optional `parent`, and a required `facility` identifier.

---

#### Filename: `src/components/ui/input.tsx`

**Lines 28-28:**
```typescript
Input
```
- **Description**: This is a reference to the `Input` component, which is used in the form for user input fields. It is likely a custom component that handles rendering and validation of input fields.

--- 

These snippets provide context on the data structures used for creating and editing facility organizations, which may be relevant to the global error handling mentioned in the user comment.

</details>


---

<details>
<summary>✏️ Learnings added</summary>

```
Learnt from: AdityaJ2305
PR: ohcnetwork/care_fe#11719
File: src/pages/Facility/settings/organizations/components/FacilityOrganizationFormSheet.tsx:120-136
Timestamp: 2025-04-03T20:01:55.112Z
Learning: The codebase has a global error handler that can take care of API errors, including handling errors from mutations like updateOrganization.
```

> Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure [review instructions](https://docs.coderabbit.ai/guides/review-instructions). You can manage existing learnings in the [app](https://app.coderabbit.ai/learnings).

</details></answer></rawResChunk> -->

<!-- This is an auto-generated reply by CodeRabbit -->
created_at: 2025-04-03T20:04:07Z
author_association: CONTRIBUTOR
path: .env
user: login: Jacobjeevan
body: discard changes in this file
created_at: 2025-04-04T05:03:53Z
author_association: CONTRIBUTOR
diff_hunk: @@ -32,6 +32,14 @@ export interface FacilityOrganizationCreate {
   parent?: string;
 }
 
+export interface FacilityOrganizationEdit {
path: src/types/facilityOrganization/facilityOrganization.ts
user: login: Jacobjeevan
body: this can be dependent on FacilityOrganizationCreate type as they share elements
created_at: 2025-04-04T05:06:55Z
author_association: CONTRIBUTOR
path: src/pages/Facility/settings/organizations/components/FacilityOrganizationFormSheet.tsx
user: login: Jacobjeevan
body: Hmm, the history isn't ideal here - would have preferred git history show that this is a modified version of CreateFacilityOrganizationSheet; it would have helped with comparing with older version of the file as well.

You should use git rename command in such cases.

You should be able to do this - delete the new file, commit, checkout the older file from develop using git checkout, rename and copy over the logic in new file.

checkout using `git checkout develop -- /path/to/file`
created_at: 2025-04-04T05:10:09Z
author_association: CONTRIBUTOR
diff_hunk: @@ -32,6 +32,14 @@ export interface FacilityOrganizationCreate {
   parent?: string;
 }
 
+export interface FacilityOrganizationEdit {
path: src/types/facilityOrganization/facilityOrganization.ts
user: login: AdityaJ2305
body: done
created_at: 2025-04-04T08:03:35Z
author_association: MEMBER
path: .env
user: login: AdityaJ2305
body: done
created_at: 2025-04-04T08:04:47Z
author_association: MEMBER
path: src/pages/Facility/settings/organizations/components/FacilityOrganizationFormSheet.tsx
user: login: AdityaJ2305
body: I tried, but not able to do that , I have renamed to file to CreateFacilityOrganizationSheet.tsx so it would be easy for you to review, I'll update the name at last if you alllow ? 
created_at: 2025-04-04T08:06:11Z
author_association: MEMBER
diff_hunk: @@ -98,10 +117,8 @@ export default function FacilityOrganizationView({
     }),
   });
 
-  const { canCreateFacilityOrganization } = getPermissions(
-    hasPermission,
-    permissions,
-  );
+  const { canCreateFacilityOrganization, canManageFacilityOrganization } =
path: src/pages/Facility/settings/organizations/FacilityOrganizationView.tsx
user: login: AdityaJ2305
body: @Jacobjeevan I totally agree with hiding the edit button for root, but ideally this should be handled based on permissions—not by hardcoding org type checks,This needs backend changes
created_at: 2025-04-04T09:31:05Z
author_association: MEMBER
diff_hunk: @@ -98,10 +117,8 @@ export default function FacilityOrganizationView({
     }),
   });
 
-  const { canCreateFacilityOrganization } = getPermissions(
-    hasPermission,
-    permissions,
-  );
+  const { canCreateFacilityOrganization, canManageFacilityOrganization } =
path: src/pages/Facility/settings/organizations/FacilityOrganizationView.tsx
user: login: Jacobjeevan
body: Just hide the button for org_type of root. It's one root org per facility, we don't need to add special permissions for that.
created_at: 2025-04-04T09:41:30Z
author_association: CONTRIBUTOR
diff_hunk: @@ -77,81 +120,145 @@ export default function FacilityOrganizationSheet({
     },
   });
 
-  const handleSubmit = () => {
-    if (!name.trim()) {
-      toast.error(t("please_enter_organization_name"));
-      return;
-    }
+  const { mutate: updateOrganization, isPending: isUpdating } = useMutation({
+    mutationFn: (body: FacilityOrganizationEdit) =>
+      mutate(facilityOrganizationApi.update, {
+        pathParams: { facilityId, organizationId: org?.id },
+        body,
+      })(body),
+    onSuccess: () => {
+      queryClient.invalidateQueries({
+        queryKey: ["facilityOrganization", "list", facilityId, parentId],
+      });
+      queryClient.invalidateQueries({
+        queryKey: ["getCurrentUser"],
+      });
+      toast.success(t("organization_updated_successfully"));
+      setOpen(false);
+    },
+  });
path: src/pages/Facility/settings/organizations/components/CreateFacilityOrganizationSheet.tsx
user: login: coderabbitai[bot]
body: _🛠️ Refactor suggestion_

**Missing error handling for update mutation.**

Unlike the create mutation, the update mutation doesn't have explicit error handling. While the codebase may have a global error handler, consistent error handling would improve the user experience by providing specific feedback for update failures.

Add error handling to the update mutation:

```diff
const { mutate: updateOrganization, isPending: isUpdating } = useMutation({
  mutationFn: (body: FacilityOrganizationEdit) =>
    mutate(facilityOrganizationApi.update, {
      pathParams: { facilityId, organizationId: org?.id },
      body,
    })(body),
  onSuccess: () => {
    queryClient.invalidateQueries({
      queryKey: ["facilityOrganization", "list", facilityId, parentId],
    });
    queryClient.invalidateQueries({
      queryKey: ["getCurrentUser"],
    });
    toast.success(t("organization_updated_successfully"));
    setOpen(false);
  },
+  onError: (error) => {
+    const errorData = error.cause as { errors: { msg: string }[] };
+    errorData.errors.forEach((er) => {
+      toast.error(er.msg);
+    });
+  },
});
```


<!-- suggestion_start -->

<details>
<summary>📝 Committable suggestion</summary>

> ‼️ **IMPORTANT**
> Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

`````suggestion
  const { mutate: updateOrganization, isPending: isUpdating } = useMutation({
    mutationFn: (body: FacilityOrganizationEdit) =>
      mutate(facilityOrganizationApi.update, {
        pathParams: { facilityId, organizationId: org?.id },
        body,
      })(body),
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: ["facilityOrganization", "list", facilityId, parentId],
      });
      queryClient.invalidateQueries({
        queryKey: ["getCurrentUser"],
      });
      toast.success(t("organization_updated_successfully"));
      setOpen(false);
    },
    onError: (error) => {
      const errorData = error.cause as { errors: { msg: string }[] };
      errorData.errors.forEach((er) => {
        toast.error(er.msg);
      });
    },
  });
`````

</details>

<!-- suggestion_end -->

<!-- This is an auto-generated reply by CodeRabbit -->
created_at: 2025-04-07T09:15:38Z
author_association: CONTRIBUTOR
diff_hunk: @@ -77,81 +120,145 @@ export default function FacilityOrganizationSheet({
     },
   });
 
-  const handleSubmit = () => {
-    if (!name.trim()) {
-      toast.error(t("please_enter_organization_name"));
-      return;
-    }
+  const { mutate: updateOrganization, isPending: isUpdating } = useMutation({
+    mutationFn: (body: FacilityOrganizationEdit) =>
+      mutate(facilityOrganizationApi.update, {
+        pathParams: { facilityId, organizationId: org?.id },
+        body,
+      })(body),
+    onSuccess: () => {
+      queryClient.invalidateQueries({
+        queryKey: ["facilityOrganization", "list", facilityId, parentId],
+      });
+      queryClient.invalidateQueries({
+        queryKey: ["getCurrentUser"],
+      });
+      toast.success(t("organization_updated_successfully"));
+      setOpen(false);
+    },
+  });
path: src/pages/Facility/settings/organizations/components/CreateFacilityOrganizationSheet.tsx
user: login: AdityaJ2305
body: Global Error handler going to take care of this 
created_at: 2025-04-07T09:17:31Z
author_association: MEMBER
diff_hunk: @@ -77,81 +120,145 @@ export default function FacilityOrganizationSheet({
     },
   });
 
-  const handleSubmit = () => {
-    if (!name.trim()) {
-      toast.error(t("please_enter_organization_name"));
-      return;
-    }
+  const { mutate: updateOrganization, isPending: isUpdating } = useMutation({
+    mutationFn: (body: FacilityOrganizationEdit) =>
+      mutate(facilityOrganizationApi.update, {
+        pathParams: { facilityId, organizationId: org?.id },
+        body,
+      })(body),
+    onSuccess: () => {
+      queryClient.invalidateQueries({
+        queryKey: ["facilityOrganization", "list", facilityId, parentId],
+      });
+      queryClient.invalidateQueries({
+        queryKey: ["getCurrentUser"],
+      });
+      toast.success(t("organization_updated_successfully"));
+      setOpen(false);
+    },
+  });
path: src/pages/Facility/settings/organizations/components/CreateFacilityOrganizationSheet.tsx
user: login: coderabbitai[bot]
body: @AdityaJ2305 You're right. Looking at our existing learning records, I see that your codebase already has a global error handler that takes care of API errors, including those from mutations like `updateOrganization`. Given this architecture, there's no need to duplicate error handling logic in the component. Thanks for the clarification!

---
<details>
<summary>🧠 Learnings used</summary>

```
Learnt from: AdityaJ2305
PR: ohcnetwork/care_fe#11719
File: src/pages/Facility/settings/organizations/components/FacilityOrganizationFormSheet.tsx:120-136
Timestamp: 2025-04-03T20:01:56.211Z
Learning: The codebase has a global error handler that can take care of API errors, including handling errors from mutations like updateOrganization.
```
</details>



<!-- <agentComponentType>chat-answer</agentComponentType> -->

<!-- <rawResChunk><answer>@AdityaJ2305 You're right. Looking at our existing learning records, I see that your codebase already has a global error handler that takes care of API errors, including those from mutations like `updateOrganization`. Given this architecture, there's no need to duplicate error handling logic in the component. Thanks for the clarification!

---

<details>
<summary>🧠 Learnings used</summary>

```
Learnt from: AdityaJ2305
PR: ohcnetwork/care_fe#11719
File: src/pages/Facility/settings/organizations/components/FacilityOrganizationFormSheet.tsx:120-136
Timestamp: 2025-04-03T20:01:56.211Z
Learning: The codebase has a global error handler that can take care of API errors, including handling errors from mutations like updateOrganization.
```

</details></answer></rawResChunk> -->

<!-- This is an auto-generated reply by CodeRabbit -->
created_at: 2025-04-07T09:17:56Z
author_association: CONTRIBUTOR

PR comments:
user: login: coderabbitai[bot]
created_at: 2025-04-03T19:53:23Z
body: <!-- This is an auto-generated comment: summarize by coderabbit.ai -->
<!-- walkthrough_start -->

## Walkthrough
This pull request updates facility organization management by modifying localization strings and refactoring UI components. The changes include updated text entries for department/team actions, renaming and enhancing components to support editing functionality with additional properties, implementing form management with `react-hook-form` and Zod validation, and adding a new API endpoint for updating organizations. Additionally, a new TypeScript interface for editing organizations is introduced to secure data consistency.

## Changes

| File(s) | Change Summary |
|---------|----------------|
| `public/locale/en.json` | Updated department/team descriptions (removed trailing period) and added new entries for editing (keys: `edit_department_team`, `edit_department_team_description`) and organization update messages (`organization_updated_successfully`, `update_organization`). |
| `src/pages/Facility/settings/organizations/FacilityOrganizationView.tsx` | Renamed imported component to `FacilityOrganizationFormSheet`; updated `OrganizationCard` to accept `parentId` and `canWrite` props; passed new permission `canManageFacilityOrganization` to control conditional rendering. |
| `src/pages/Facility/settings/organizations/components/CreateFacilityOrganizationSheet.tsx` | Refactored component to `FacilityOrganizationFormSheet` with `react-hook-form` and Zod integration; added support for edit mode via an `org` prop; restructured form submission to handle both creation and updating of organizations. |
| `src/types/facilityOrganization/facilityOrganization.ts` | Added new interface `FacilityOrganizationEdit` that extends the creation interface by including a required `facility` property. |
| `src/types/facilityOrganization/facilityOrganizationApi.ts` | Introduced a new API endpoint `update` using HTTP PUT, accepting a `FacilityOrganizationEdit` request body and returning a `FacilityOrganization`. |

## Sequence Diagram(s)

```mermaid
sequenceDiagram
    participant U as User
    participant OC as OrganizationCard
    participant FS as FacilityOrganizationFormSheet
    participant API as API Server

    U->>OC: Clicks edit button
    OC->>FS: Renders form sheet in edit mode with organization data
    U->>FS: Modifies fields and submits form
    FS->>API: Sends PUT request to update organization
    API-->>FS: Returns updated organization data
    FS-->>OC: Passes updated details for UI refresh
    OC-->>U: Displays updated organization information
```

## Assessment against linked issues

| Objective                                                                 | Addressed | Explanation |
|---------------------------------------------------------------------------|-----------|-------------|
| Enable edit option for department/team name within a facility (#11319)     | ✅        |             |

## Possibly related PRs
- **ohcnetwork/care_fe#11066**: Updates in localization keys for text strings show a direct relation to similar modifications in this PR.

## Suggested labels
`needs review`, `needs testing`, `tested`

## Suggested reviewers
- rithviknishad

## Poem
> I’m a bunny of code, with hops so bright,  
> Transforming forms and strings in the light.  
> New edit paths I joyfully tread,  
> In each updated line where changes are spread.  
> With carrots and code, I cheer this delight!  
> 🥕🐰

<!-- walkthrough_end -->
<!-- internal state start -->


<!-- DwQgtGAEAqAWCWBnSTIEMB26CuAXA9mAOYCmGJATmriQCaQDG+Ats2bgFyQAOFk+AIwBWJBrngA3EsgEBPRvlqU0AgfFwA6NPEgQAfACgjoCEYDEZyAAUASpADK2VmgqyjcEj2wAbb5AokAI7Y0riQ4rjedJAARACCtEr0XACitOr83OL4WABm+HxK3C64bBi4APQ0aMwxkADuaMiI2ALM6jT0cpDYiJSQCeqyaABSAEwAzAAMAKzoGPSo8Erl8Lnw0U2QGE4C/QCM+wDs+wCcGjCwnrzwzC7ygiJikp74ueEIyLYoyAToiQFEMgkC1PGZDhMzhp3FceBR8Nx8H16AxYJhSMCMAxvNglD1uLRqPAMEQPp58hRmOF8D1xN54AAvckFZgAGkgFOY6xI3lo7Mwi3KJCIVHEJMgNhIaDEkAAEvh8ABrSAAMRZ6G8OVJ9XUsEgAC1FByCpAJGh6YTshgLgl0lbzd5ZPysGkMgirZABHgCFg0TISGR/klqWT+BQiJhGUScowXHyGghURrNfVkL1KL8aQjA5hIHQMpzIIgriQwhTIMxFGt4AxoxhENCDB5rHZidjcdJ0IwrgxFfTEGWTWxw8SiOz6om9fg8PTyM0SFIqH5cE1Fb80WFyNE/nsFMxuFFOp6SBTPLhYaj0Z3a1hd+sMObGXQLh4+uFV5j23i0IlR0XuKI1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wIKNwt6TmTy96TqLzMAGKr290cGD/QEL1AKL1Ty9/sLdKTlMBMKTqeqTh9+T7kKcFty96INzxD0cPN472T/sC98D7V8T1ABDI10HS16VG17QFdM8voEAA -->

<!-- internal state end -->
<!-- finishing_touch_checkbox_start -->

<details>
<summary>✨ Finishing Touches</summary>

- [ ] <!-- {"checkboxId": "7962f53c-55bc-4827-bfbf-6a18da830691"} --> 📝 Generate Docstrings

</details>

<!-- finishing_touch_checkbox_end -->
<!-- tips_start -->

---



<details>
<summary>🪧 Tips</summary>

### Chat

There are 3 ways to chat with [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=ohcnetwork/care_fe&utm_content=11719):

- Review comments: Directly reply to a review comment made by CodeRabbit. Example:
  - `I pushed a fix in commit <commit_id>, please review it.`
  - `Generate unit testing code for this file.`
  - `Open a follow-up GitHub issue for this discussion.`
- Files and specific lines of code (under the "Files changed" tab): Tag `@coderabbitai` in a new review comment at the desired location with your query. Examples:
  - `@coderabbitai generate unit testing code for this file.`
  -	`@coderabbitai modularize this function.`
- PR comments: Tag `@coderabbitai` in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
  - `@coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.`
  - `@coderabbitai read src/utils.ts and generate unit testing code.`
  - `@coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.`
  - `@coderabbitai help me debug CodeRabbit configuration file.`

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

### CodeRabbit Commands (Invoked using PR comments)

- `@coderabbitai pause` to pause the reviews on a PR.
- `@coderabbitai resume` to resume the paused reviews.
- `@coderabbitai review` to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
- `@coderabbitai full review` to do a full review from scratch and review all the files again.
- `@coderabbitai summary` to regenerate the summary of the PR.
- `@coderabbitai generate docstrings` to [generate docstrings](https://docs.coderabbit.ai/finishing-touches/docstrings) for this PR.
- `@coderabbitai resolve` resolve all the CodeRabbit review comments.
- `@coderabbitai plan` to trigger planning for file edits and PR creation.
- `@coderabbitai configuration` to show the current CodeRabbit configuration for the repository.
- `@coderabbitai help` to get help.

### Other keywords and placeholders

- Add `@coderabbitai ignore` anywhere in the PR description to prevent this PR from being reviewed.
- Add `@coderabbitai summary` to generate the high-level summary at a specific location in the PR description.
- Add `@coderabbitai` anywhere in the PR title to generate the title automatically.

### CodeRabbit Configuration File (`.coderabbit.yaml`)

- You can programmatically configure CodeRabbit by adding a `.coderabbit.yaml` file to the root of your repository.
- Please see the [configuration documentation](https://docs.coderabbit.ai/guides/configure-coderabbit) for more information.
- If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: `# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json`

### Documentation and Community

- Visit our [Documentation](https://docs.coderabbit.ai) for detailed information on how to use CodeRabbit.
- Join our [Discord Community](http://discord.gg/coderabbit) to get help, request features, and share feedback.
- Follow us on [X/Twitter](https://twitter.com/coderabbitai) for updates and announcements.

</details>

<!-- tips_end -->
author_association: CONTRIBUTOR
user: login: netlify[bot]
created_at: 2025-04-03T19:53:43Z
body: ### <span aria-hidden="true">✅</span> Deploy Preview for *care-ohc* ready!


|  Name | Link |
|:-:|------------------------|
|<span aria-hidden="true">🔨</span> Latest commit | df2761fe4034ff47eb2f9a06ec8e907086e3b16c |
|<span aria-hidden="true">🔍</span> Latest deploy log | https://app.netlify.com/sites/care-ohc/deploys/67f396aa51a7330008f5aca1 |
|<span aria-hidden="true">😎</span> Deploy Preview | [https://deploy-preview-11719.preview.ohc.network](https://deploy-preview-11719.preview.ohc.network) |
|<span aria-hidden="true">📱</span> Preview on mobile | <details><summary> Toggle QR Code... </summary><br /><br />![QR Code](https://app.netlify.com/qr-code/eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1cmwiOiJodHRwczovL2RlcGxveS1wcmV2aWV3LTExNzE5LnByZXZpZXcub2hjLm5ldHdvcmsifQ.i5pJl9nzUihp8yEqG0qMNFvMuxhGRiJNSG4kVPWghZg)<br /><br />_Use your smartphone camera to open QR code link._</details> |
---
<!-- [care-ohc Preview](https://deploy-preview-11719.preview.ohc.network) -->
_To edit notification comments on pull requests, go to your [Netlify site configuration](https://app.netlify.com/sites/care-ohc/configuration/notifications#deploy-webhooks)._
author_association: NONE
user: login: AdityaJ2305
created_at: 2025-04-03T19:58:24Z
body: Hey Team, as per the issue, we only need to enable editing for the name. However, the previously closed PR (before it was assigned to me) allowed editing of all details—name, description, and type of dept/team—without any mention of restricting it. So, I followed the same approach in my new PR. Just need confirmation—should I update it accordingly? and Please don't close this PR I am ready to make changes according to feedback 😅 

PS: I noticed it while linking Pr with issue 
cc: @Jacobjeevan @rithviknishad 
author_association: MEMBER
user: login: AdityaJ2305
created_at: 2025-04-03T19:59:57Z
body: I think we can enable to edit name + description and avoid the type ? 
author_association: MEMBER
user: login: AdityaJ2305
created_at: 2025-04-04T08:09:24Z
body: @Jacobjeevan , If you observe in the demo video It is showing edit option for Root as well which I think should be dependent of canManageRootFacility from permission which I noticed is absent in backend and frontend, It shouldn't be great practice to hide to edit button for root by checking org.type am I right ? so need backned changes to push the permission for managerootorg
author_association: MEMBER
user: login: Jacobjeevan
created_at: 2025-04-04T09:13:58Z
body: > @Jacobjeevan , If you observe in the demo video It is showing edit option for Root as well which I think should be dependent of canManageRootFacility from permission which I noticed is absent in backend and frontend, It shouldn't be great practice to hide to edit button for root by checking org.type am I right ? so need backned changes to push the permission for managerootorg

No, hide the edit button for root, it should not be editable.
author_association: CONTRIBUTOR
user: login: AdityaJ2305
created_at: 2025-04-04T09:44:00Z
body: @Jacobjeevan @rithviknishad Ready for review and testing 
author_association: MEMBER
user: login: nihal467
created_at: 2025-04-07T11:00:54Z
body: LGTM
author_association: MEMBER
user: login: github-actions[bot]
created_at: 2025-04-07T17:08:00Z
body: @AdityaJ2305 Your efforts have helped advance digital healthcare and TeleICU systems. :rocket: Thank you for taking the time out to make CARE better. We hope you continue to innovate and contribute; your impact is immense! :raised_hands:
author_association: NONE