{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "openlmis-user-roles-page",
  "title": "User Roles Page",
  "description": "Edit User Roles on mock data: Supervision, Fulfillment, Reports and Administration tabs with counts over one draft, Add Role, Import Roles and View Rights dialogs, Remove with Undo, and Cancel and Save Changes in a bar at the bottom that asks before discarding unsaved changes.",
  "dependencies": [
    "@tanstack/react-form@^1",
    "@tanstack/react-table@^9",
    "lucide-react@^1",
    "zod@^4",
    "@base-ui/react@^1"
  ],
  "registryDependencies": [
    "badge",
    "button",
    "dialog",
    "dropdown-menu",
    "field",
    "skeleton",
    "tabs",
    "https://registry.soldevelo.com/r/openlmis-callout.json",
    "https://registry.soldevelo.com/r/openlmis-discard-changes-dialog.json",
    "https://registry.soldevelo.com/r/openlmis-form-dialog.json",
    "https://registry.soldevelo.com/r/openlmis-form-fields.json",
    "https://registry.soldevelo.com/r/openlmis-page-breadcrumbs.json",
    "https://registry.soldevelo.com/r/openlmis-role-assignments.json",
    "https://registry.soldevelo.com/r/openlmis-workspace.json"
  ],
  "files": [
    {
      "path": "registry/templates/openlmis/user-roles-page/components/add-role-dialog/add-role-dialog.tsx",
      "content": "\"use client\"\n\nimport { revalidateLogic } from \"@tanstack/react-form\"\nimport { useMemo } from \"react\"\n\nimport { FieldGroup } from \"@/components/ui/field\"\nimport {\n  type Facility,\n  type Program,\n  type RightType,\n  type Role,\n  type RoleAssignment,\n  rightLabel,\n  roleTypeOf,\n  type SupervisoryNode,\n} from \"@/components/blocks/openlmis/role-assignments/role-assignments\"\nimport {\n  FormDialog,\n  FormDialogBody,\n  FormDialogCancel,\n  FormDialogDescription,\n  FormDialogFooter,\n  FormDialogForm,\n  FormDialogHeader,\n  FormDialogSubmit,\n  FormDialogTitle,\n} from \"@/components/openlmis/form-dialog/form-dialog\"\nimport { Callout } from \"@/components/openlmis/callout\"\nimport { useDialogTarget } from \"@/components/openlmis/form-dialog/use-dialog-target\"\nimport { useAppForm } from \"@/components/openlmis/form-fields/form\"\nimport {\n  ComboboxField,\n  FieldSkeleton,\n} from \"@/components/openlmis/form-fields/form-fields\"\n\nimport {\n  EMPTY_ROLE_FORM,\n  type RoleFormValues,\n  roleFormSchema,\n  toRoleAssignment,\n} from \"@/components/openlmis/user-roles-page/role-form\"\n\nconst TYPE_LABEL: Record<RightType, string> = {\n  SUPERVISION: \"Supervision\",\n  ORDER_FULFILLMENT: \"Fulfillment\",\n  REPORTS: \"Reports\",\n  GENERAL_ADMIN: \"Administration\",\n}\n\n/** The dialog's choices; a list left undefined shows a skeleton in its field. */\nexport type AddRoleOptions = {\n  roles: readonly Role[] | undefined\n  programs: readonly Program[] | undefined\n  nodes: readonly SupervisoryNode[] | undefined\n  facilities: readonly Facility[] | undefined\n}\n\ntype AddRoleDialogProps = AddRoleOptions & {\n  /** The type of role being added; the dialog is open while it is set. */\n  type: RightType | undefined\n  /** The roles the user holds now, so the same one cannot be added twice. */\n  assigned: readonly RoleAssignment[]\n  username: string\n  hasHomeFacility: boolean\n  onAdd: (assignment: RoleAssignment) => void\n  onClose: () => void\n}\n\nexport function AddRoleDialog({ type, onClose, ...props }: AddRoleDialogProps) {\n  const { shown, dialogProps } = useDialogTarget(type, onClose)\n\n  return (\n    <FormDialog {...dialogProps()}>\n      {shown && (\n        <AddRoleContent key={shown} onDone={onClose} type={shown} {...props} />\n      )}\n    </FormDialog>\n  )\n}\n\ntype ContentProps = Omit<AddRoleDialogProps, \"type\" | \"onClose\"> & {\n  type: RightType\n  onDone: () => void\n}\n\nconst byName = <T extends { name: string }>(a: T, b: T) =>\n  a.name.localeCompare(b.name)\n\nfunction AddRoleContent({ roles, ...props }: ContentProps) {\n  const { type, username } = props\n  const ofType = useMemo(\n    () =>\n      // oxlint-disable-next-line unicorn/no-array-sort -- sorts the fresh filtered array\n      roles?.filter((role) => roleTypeOf(role) === type).sort(byName),\n    [roles, type]\n  )\n\n  if (!ofType) {\n    return (\n      <>\n        <AddRoleHeader type={type} username={username} />\n        <FormDialogBody>\n          <div aria-busy>\n            <FieldGroup>\n              {type === \"SUPERVISION\" && (\n                <FieldSkeleton label=\"Program\" required />\n              )}\n              <FieldSkeleton label=\"Role\" required />\n            </FieldGroup>\n          </div>\n        </FormDialogBody>\n        <FormDialogFooter>\n          <FormDialogCancel />\n          <FormDialogSubmit disabled>Add Role</FormDialogSubmit>\n        </FormDialogFooter>\n      </>\n    )\n  }\n  return <AddRoleForm {...props} roles={ofType} />\n}\n\nfunction AddRoleHeader({\n  type,\n  username,\n}: {\n  type: RightType\n  username: string\n}) {\n  return (\n    <FormDialogHeader>\n      <FormDialogTitle>Add {TYPE_LABEL[type]} Role</FormDialogTitle>\n      <FormDialogDescription>\n        Choose a {TYPE_LABEL[type].toLowerCase()} role to grant to {username}.\n      </FormDialogDescription>\n    </FormDialogHeader>\n  )\n}\n\nfunction AddRoleForm({\n  type,\n  roles,\n  assigned,\n  username,\n  hasHomeFacility,\n  onAdd,\n  onDone,\n  programs,\n  nodes,\n  facilities,\n}: Omit<ContentProps, \"roles\"> & { roles: Role[] }) {\n  const schema = useMemo(() => roleFormSchema(type, assigned), [type, assigned])\n\n  const form = useAppForm({\n    // A type with a single role has nothing to choose, so it starts chosen.\n    defaultValues: {\n      ...EMPTY_ROLE_FORM,\n      roleId: roles.length === 1 ? (roles[0]?.id ?? null) : null,\n    } satisfies RoleFormValues,\n    validationLogic: revalidateLogic({\n      mode: \"submit\",\n      modeAfterSubmission: \"change\",\n    }),\n    validators: { onDynamic: schema },\n    onSubmit: ({ value }) => {\n      onAdd(toRoleAssignment(type, value))\n      onDone()\n    },\n  })\n\n  return (\n    <FormDialogForm onSubmit={() => void form.handleSubmit()}>\n      <AddRoleHeader type={type} username={username} />\n      <FormDialogBody>\n        <FieldGroup>\n          {type === \"SUPERVISION\" && (\n            <>\n              <form.AppField name=\"programId\">\n                {() => <ProgramField programs={programs} />}\n              </form.AppField>\n              <form.AppField name=\"supervisoryNodeId\">\n                {() => <NodeField facilities={facilities} nodes={nodes} />}\n              </form.AppField>\n            </>\n          )}\n          {type === \"ORDER_FULFILLMENT\" && (\n            <form.AppField name=\"warehouseId\">\n              {() => <FacilityField facilities={facilities} />}\n            </form.AppField>\n          )}\n          <form.AppField name=\"roleId\">\n            {(field) => <RoleField roleId={field.state.value} roles={roles} />}\n          </form.AppField>\n          {type === \"SUPERVISION\" && !hasHomeFacility && (\n            <form.Subscribe\n              selector={(state) => state.values.supervisoryNodeId}\n            >\n              {(nodeId) =>\n                !nodeId && (\n                  <Callout title=\"No Home Facility\" tone=\"warning\">\n                    Without a supervisory node this role applies at the home\n                    facility, and {username} has none, so it grants nothing\n                    until one is set.\n                  </Callout>\n                )\n              }\n            </form.Subscribe>\n          )}\n        </FieldGroup>\n      </FormDialogBody>\n      <FormDialogFooter>\n        <FormDialogCancel />\n        <FormDialogSubmit>Add Role</FormDialogSubmit>\n      </FormDialogFooter>\n    </FormDialogForm>\n  )\n}\n\n/** Hints how many there are, since the list shows the first 50 until the user types. */\nconst searchHint = (count: number, noun: string) =>\n  `Type to search ${count} ${noun}.`\n\nfunction ProgramField({ programs }: Pick<AddRoleOptions, \"programs\">) {\n  const items = useMemo(() => {\n    const sorted = [...(programs ?? [])]\n    // oxlint-disable-next-line unicorn/no-array-sort -- sorts a copy\n    sorted.sort(byName)\n    return sorted.map((program) => ({ value: program.id, label: program.name }))\n  }, [programs])\n  if (!programs) return <FieldSkeleton label=\"Program\" required />\n  return (\n    <ComboboxField\n      clearLabel=\"Clear Program\"\n      emptyMessage=\"No programs found.\"\n      items={items}\n      label=\"Program\"\n      placeholder=\"Search Programs...\"\n      required\n    />\n  )\n}\n\n/** Each node with its facility, as OpenLMIS names them, e.g. \"FP Approval Point (Balaka)\". */\nfunction NodeField({\n  nodes,\n  facilities,\n}: Pick<AddRoleOptions, \"nodes\" | \"facilities\">) {\n  const items = useMemo(() => {\n    const names = new Map(\n      (facilities ?? []).map((facility) => [facility.id, facility.name])\n    )\n    // oxlint-disable-next-line unicorn/no-array-sort -- sorts a copy\n    return [...(nodes ?? [])].sort(byName).map((node) => {\n      const facility = node.facility && names.get(node.facility.id)\n      return {\n        value: node.id,\n        label: facility ? `${node.name} (${facility})` : node.name,\n      }\n    })\n  }, [nodes, facilities])\n\n  if (!nodes || !facilities) return <FieldSkeleton label=\"Supervisory Node\" />\n  return (\n    <ComboboxField\n      clearLabel=\"Clear Supervisory Node\"\n      description={`${searchHint(items.length, \"nodes\")} Leave empty for the home facility.`}\n      emptyMessage=\"No supervisory nodes found.\"\n      items={items}\n      label=\"Supervisory Node\"\n      placeholder=\"Search Supervisory Nodes...\"\n    />\n  )\n}\n\nfunction FacilityField({ facilities }: Pick<AddRoleOptions, \"facilities\">) {\n  const items = useMemo(\n    () =>\n      // oxlint-disable-next-line unicorn/no-array-sort -- sorts a copy\n      [...(facilities ?? [])].sort(byName).map((facility) => ({\n        value: facility.id,\n        label: `${facility.code} - ${facility.name}`,\n      })),\n    [facilities]\n  )\n  if (!facilities) return <FieldSkeleton label=\"Facility\" required />\n  return (\n    <ComboboxField\n      clearLabel=\"Clear Facility\"\n      description={searchHint(items.length, \"facilities\")}\n      emptyMessage=\"No facilities found.\"\n      items={items}\n      label=\"Facility\"\n      placeholder=\"Search Facilities...\"\n      required\n    />\n  )\n}\n\n/** The roles of this type; once one is picked, the rights it grants show beneath. */\nfunction RoleField({\n  roles,\n  roleId,\n}: {\n  roles: Role[]\n  roleId: string | null\n}) {\n  const items = useMemo(\n    () => roles.map((role) => ({ value: role.id, label: role.name })),\n    [roles]\n  )\n  const labels = roles\n    .find((role) => role.id === roleId)\n    ?.rights.map((right) => rightLabel(right.name))\n  // oxlint-disable-next-line unicorn/no-array-sort -- sorts the fresh mapped array\n  const rights = labels?.sort().join(\", \")\n\n  return (\n    <ComboboxField\n      clearLabel=\"Clear Role\"\n      description={rights && `Grants ${rights}.`}\n      emptyMessage=\"No roles found.\"\n      items={items}\n      label=\"Role\"\n      placeholder=\"Search Roles...\"\n      required\n    />\n  )\n}",
      "type": "registry:component",
      "target": "components/openlmis/user-roles-page/add-role-dialog.tsx"
    },
    {
      "path": "registry/templates/openlmis/user-roles-page/components/add-role-dialog/role-form.ts",
      "content": "import { z } from \"zod\"\n\nimport {\n  assignmentKey,\n  type RightType,\n  type RoleAssignment,\n  toSavedAssignment,\n} from \"@/components/blocks/openlmis/role-assignments/role-assignments\"\n\nconst roleFormFields = z.object({\n  roleId: z.string().nullable(),\n  programId: z.string().nullable(),\n  supervisoryNodeId: z.string().nullable(),\n  warehouseId: z.string().nullable(),\n})\n\nexport type RoleFormValues = z.input<typeof roleFormFields>\n\nexport const EMPTY_ROLE_FORM: RoleFormValues = {\n  roleId: null,\n  programId: null,\n  supervisoryNodeId: null,\n  warehouseId: null,\n}\n\n/** The assignment the form describes, with only the ids its type uses. */\nexport function toRoleAssignment(\n  type: RightType,\n  values: RoleFormValues\n): RoleAssignment {\n  return toSavedAssignment({\n    roleId: values.roleId ?? \"\",\n    ...(type === \"SUPERVISION\" && {\n      programId: values.programId,\n      supervisoryNodeId: values.supervisoryNodeId,\n    }),\n    ...(type === \"ORDER_FULFILLMENT\" && { warehouseId: values.warehouseId }),\n  })\n}\n\n/** Each type needs its own fields; the same role twice, in the same place, is refused. */\nexport function roleFormSchema(\n  type: RightType,\n  assigned: readonly RoleAssignment[]\n) {\n  const assignedKeys = new Set(assigned.map(assignmentKey))\n\n  return roleFormFields.superRefine((values, context) => {\n    const require = (path: keyof RoleFormValues, message: string) => {\n      if (!values[path])\n        context.addIssue({ code: \"custom\", path: [path], message })\n    }\n    if (type === \"SUPERVISION\") require(\"programId\", \"Choose a program.\")\n    if (type === \"ORDER_FULFILLMENT\")\n      require(\"warehouseId\", \"Choose a facility.\")\n    require(\"roleId\", \"Choose a role.\")\n\n    if (\n      values.roleId &&\n      assignedKeys.has(assignmentKey(toRoleAssignment(type, values)))\n    ) {\n      context.addIssue({\n        code: \"custom\",\n        path: [\"roleId\"],\n        message: \"This user already has this role here.\",\n      })\n    }\n  })\n}",
      "type": "registry:lib",
      "target": "components/openlmis/user-roles-page/role-form.ts"
    },
    {
      "path": "registry/templates/openlmis/user-roles-page/components/import-roles-dialog/import-roles-dialog.tsx",
      "content": "\"use client\"\n\nimport { revalidateLogic, useStore } from \"@tanstack/react-form\"\nimport { useMemo } from \"react\"\nimport { z } from \"zod\"\n\nimport { FieldDescription, FieldGroup } from \"@/components/ui/field\"\nimport {\n  mergeAssignments,\n  type RoleAssignment,\n} from \"@/components/blocks/openlmis/role-assignments/role-assignments\"\nimport {\n  FormDialog,\n  FormDialogBody,\n  FormDialogCancel,\n  FormDialogDescription,\n  FormDialogFooter,\n  FormDialogForm,\n  FormDialogHeader,\n  FormDialogSubmit,\n  FormDialogTitle,\n} from \"@/components/openlmis/form-dialog/form-dialog\"\nimport { useDialogTarget } from \"@/components/openlmis/form-dialog/use-dialog-target\"\nimport { useAppForm } from \"@/components/openlmis/form-fields/form\"\nimport {\n  ComboboxField,\n  FieldSkeleton,\n} from \"@/components/openlmis/form-fields/form-fields\"\n\nexport type ImportSourceUser = {\n  id: string\n  username: string\n  firstName?: string | null\n  lastName?: string | null\n  roleAssignments: RoleAssignment[]\n}\n\nconst importSchema = z.object({\n  userId: z\n    .string()\n    .nullable()\n    .refine(Boolean, \"Choose a user to copy roles from.\"),\n})\n\ntype ImportRolesDialogProps = {\n  open: boolean\n  /** The user being edited, left out of the list. */\n  userId: string\n  username: string\n  /** The roles being edited now, to count which ones are new. */\n  draft: readonly RoleAssignment[]\n  /** Who roles can be copied from; the field shows a skeleton until it is set. */\n  users: readonly ImportSourceUser[] | undefined\n  onImport: (assignments: RoleAssignment[], fromUsername: string) => void\n  onClose: () => void\n}\n\n/** Copies another user's roles into the draft; nothing is saved until the page is. */\nexport function ImportRolesDialog({\n  open,\n  onClose,\n  ...props\n}: ImportRolesDialogProps) {\n  const { shown, dialogProps } = useDialogTarget(open || undefined, onClose)\n  return (\n    <FormDialog {...dialogProps()}>\n      {shown && <ImportRolesForm onDone={onClose} {...props} />}\n    </FormDialog>\n  )\n}\n\nfunction ImportRolesForm({\n  userId,\n  username,\n  draft,\n  users,\n  onImport,\n  onDone,\n}: Omit<ImportRolesDialogProps, \"open\" | \"onClose\"> & { onDone: () => void }) {\n  const form = useAppForm({\n    defaultValues: { userId: null as string | null },\n    validationLogic: revalidateLogic({\n      mode: \"submit\",\n      modeAfterSubmission: \"change\",\n    }),\n    validators: { onDynamic: importSchema },\n    onSubmit: ({ value }) => {\n      const from = users?.find((user) => user.id === value.userId)\n      if (!from) return\n      onImport(from.roleAssignments, from.username)\n      onDone()\n    },\n  })\n  const sourceId = useStore(form.store, (state) => state.values.userId)\n  const source = users?.find((user) => user.id === sourceId)\n\n  return (\n    <FormDialogForm onSubmit={() => void form.handleSubmit()}>\n      <FormDialogHeader>\n        <FormDialogTitle>Import Roles</FormDialogTitle>\n        <FormDialogDescription>\n          Copy another user's roles to {username}. They are added to the roles\n          on this page and saved with them.\n        </FormDialogDescription>\n      </FormDialogHeader>\n      <FormDialogBody>\n        <FieldGroup>\n          <form.AppField name=\"userId\">\n            {() =>\n              users ? (\n                <UserField excludeId={userId} users={users} />\n              ) : (\n                <FieldSkeleton label=\"User\" required />\n              )\n            }\n          </form.AppField>\n          {source && (\n            <ImportPreview draft={draft} roles={source.roleAssignments} />\n          )}\n        </FieldGroup>\n      </FormDialogBody>\n      <FormDialogFooter>\n        <FormDialogCancel />\n        <FormDialogSubmit>Import Roles</FormDialogSubmit>\n      </FormDialogFooter>\n    </FormDialogForm>\n  )\n}\n\n/** Reads its field from the surrounding `AppField`. */\nfunction UserField({\n  users,\n  excludeId,\n}: {\n  users: readonly ImportSourceUser[]\n  excludeId: string\n}) {\n  const items = useMemo(\n    () =>\n      users\n        .filter((user) => user.id !== excludeId)\n        .map((user) => {\n          const name = [user.firstName, user.lastName].filter(Boolean).join(\" \")\n          return {\n            value: user.id,\n            label: name ? `${user.username} (${name})` : user.username,\n          }\n        }),\n    [users, excludeId]\n  )\n  return (\n    <ComboboxField\n      clearLabel=\"Clear User\"\n      description={`Type to search ${items.length} users.`}\n      emptyMessage=\"No users found.\"\n      items={items}\n      label=\"User\"\n      placeholder=\"Search Users...\"\n      required\n    />\n  )\n}\n\nconst count = (n: number) => (n === 1 ? \"1 role\" : `${n} roles`)\n\n/** How many of the chosen user's roles are new here, before anything is added. */\nfunction ImportPreview({\n  draft,\n  roles,\n}: {\n  draft: readonly RoleAssignment[]\n  roles: readonly RoleAssignment[]\n}) {\n  const { added, skipped } = mergeAssignments(draft, roles)\n  return (\n    <FieldDescription>\n      {added === 0\n        ? \"They have no roles this user does not already have.\"\n        : skipped === 0\n          ? `Adds ${count(added)}.`\n          : `Adds ${count(added)}; ${count(skipped)} this user already has.`}\n    </FieldDescription>\n  )\n}",
      "type": "registry:component",
      "target": "components/openlmis/user-roles-page/import-roles-dialog.tsx"
    },
    {
      "path": "registry/templates/openlmis/user-roles-page/components/mock-roles.ts",
      "content": "// Mock users, roles and reference data, so the page runs with no backend. Pass your own instead.\n\nimport type {\n  Facility,\n  Program,\n  Role,\n  RoleAssignment,\n  SupervisoryNode,\n} from \"@/components/blocks/openlmis/role-assignments/role-assignments\"\n\nexport type RolesUser = {\n  id: string\n  username: string\n  firstName: string\n  lastName: string\n  homeFacilityId: string | null\n  roleAssignments: RoleAssignment[]\n}\n\nexport const MOCK_ROLES: Role[] = [\n  {\n    id: \"role-storeroom\",\n    name: \"Storeroom Manager\",\n    description: \"Creates and submits requisitions for a facility.\",\n    rights: [\n      { name: \"REQUISITION_CREATE\", type: \"SUPERVISION\" },\n      { name: \"REQUISITION_VIEW\", type: \"SUPERVISION\" },\n      { name: \"REQUISITION_DELETE\", type: \"SUPERVISION\" },\n    ],\n  },\n  {\n    id: \"role-approver\",\n    name: \"Program Supervisor\",\n    description: \"Authorizes and approves requisitions under a node.\",\n    rights: [\n      { name: \"REQUISITION_AUTHORIZE\", type: \"SUPERVISION\" },\n      { name: \"REQUISITION_APPROVE\", type: \"SUPERVISION\" },\n      { name: \"REQUISITION_VIEW\", type: \"SUPERVISION\" },\n    ],\n  },\n  {\n    id: \"role-warehouse\",\n    name: \"Warehouse Manager\",\n    description: \"Fulfills orders and records proofs of delivery.\",\n    rights: [\n      { name: \"ORDERS_VIEW\", type: \"ORDER_FULFILLMENT\" },\n      { name: \"ORDERS_EDIT\", type: \"ORDER_FULFILLMENT\" },\n      { name: \"PODS_MANAGE\", type: \"ORDER_FULFILLMENT\" },\n      { name: \"SHIPMENTS_EDIT\", type: \"ORDER_FULFILLMENT\" },\n    ],\n  },\n  {\n    id: \"role-reports\",\n    name: \"Report Viewer\",\n    description: \"Views reporting rate and stock reports.\",\n    rights: [{ name: \"REPORTS_VIEW\", type: \"REPORTS\" }],\n  },\n  {\n    id: \"role-admin\",\n    name: \"System Administrator\",\n    description: \"Manages users, facilities and reference data.\",\n    rights: [\n      { name: \"USERS_MANAGE\", type: \"GENERAL_ADMIN\" },\n      { name: \"USER_ROLES_MANAGE\", type: \"GENERAL_ADMIN\" },\n      { name: \"FACILITIES_MANAGE\", type: \"GENERAL_ADMIN\" },\n      { name: \"CCE_MANAGE\", type: \"GENERAL_ADMIN\" },\n    ],\n  },\n]\n\nexport const MOCK_PROGRAMS: Program[] = [\n  { id: \"program-fp\", name: \"Family Planning\" },\n  { id: \"program-em\", name: \"Essential Meds\" },\n  { id: \"program-arv\", name: \"ARV\" },\n]\n\nexport const MOCK_FACILITIES: Facility[] = [\n  { id: \"facility-1\", code: \"HC01\", name: \"Comfort Health Clinic\" },\n  { id: \"facility-2\", code: \"HC02\", name: \"Nandumbo Health Center\" },\n  { id: \"facility-3\", code: \"DH01\", name: \"Balaka District Hospital\" },\n  { id: \"facility-4\", code: \"W001\", name: \"Ntcheu District Warehouse\" },\n  { id: \"facility-5\", code: \"W002\", name: \"Balaka District Warehouse\" },\n]\n\nexport const MOCK_NODES: SupervisoryNode[] = [\n  { id: \"node-1\", name: \"FP Approval Point\", facility: { id: \"facility-3\" } },\n  { id: \"node-2\", name: \"EM Approval Point\", facility: { id: \"facility-3\" } },\n  { id: \"node-3\", name: \"ARV Approval Point\", facility: { id: \"facility-2\" } },\n]\n\nexport const MOCK_USERS: RolesUser[] = [\n  {\n    id: \"user-1\",\n    username: \"divo1\",\n    firstName: \"Grace\",\n    lastName: \"Banda\",\n    homeFacilityId: \"facility-1\",\n    roleAssignments: [\n      { roleId: \"role-storeroom\", programId: \"program-fp\" },\n      { roleId: \"role-storeroom\", programId: \"program-em\" },\n      {\n        roleId: \"role-approver\",\n        programId: \"program-fp\",\n        supervisoryNodeId: \"node-1\",\n      },\n      { roleId: \"role-warehouse\", warehouseId: \"facility-4\" },\n      { roleId: \"role-reports\" },\n    ],\n  },\n  {\n    id: \"user-2\",\n    username: \"administrator\",\n    firstName: \"Alan\",\n    lastName: \"Mwale\",\n    homeFacilityId: \"facility-3\",\n    roleAssignments: [\n      { roleId: \"role-admin\" },\n      { roleId: \"role-reports\" },\n      {\n        roleId: \"role-approver\",\n        programId: \"program-em\",\n        supervisoryNodeId: \"node-2\",\n      },\n      { roleId: \"role-warehouse\", warehouseId: \"facility-5\" },\n    ],\n  },\n  {\n    id: \"user-3\",\n    username: \"srmanager2\",\n    firstName: \"Tendai\",\n    lastName: \"Okafor\",\n    homeFacilityId: null,\n    roleAssignments: [{ roleId: \"role-storeroom\", programId: \"program-arv\" }],\n  },\n]\n\nexport const MOCK_USER_ID = \"user-1\"",
      "type": "registry:lib",
      "target": "components/openlmis/user-roles-page/mock-roles.ts"
    },
    {
      "path": "registry/templates/openlmis/user-roles-page/components/use-role-draft.ts",
      "content": "\"use client\"\n\nimport { useCallback, useMemo, useState } from \"react\"\n\nimport {\n  assignmentKey,\n  countChanges,\n  mergeAssignments,\n  type RoleAssignment,\n} from \"@/components/blocks/openlmis/role-assignments/role-assignments\"\n\n/** The roles being edited, kept apart from the saved ones until they are saved. */\nexport function useRoleDraft(saved: RoleAssignment[]) {\n  const [draft, setDraft] = useState(saved)\n  const changes = useMemo(() => countChanges(saved, draft), [saved, draft])\n\n  const add = useCallback(\n    (assignment: RoleAssignment) =>\n      setDraft(\n        (current) => mergeAssignments(current, [assignment]).assignments\n      ),\n    []\n  )\n  const remove = useCallback((assignment: RoleAssignment) => {\n    const key = assignmentKey(assignment)\n    setDraft((current) => current.filter((item) => assignmentKey(item) !== key))\n  }, [])\n  /** Adds another user's roles; returns how many were new and how many were already held. */\n  const merge = useCallback(\n    (incoming: RoleAssignment[]) => {\n      const result = mergeAssignments(draft, incoming)\n      setDraft(result.assignments)\n      return result\n    },\n    [draft]\n  )\n  const reset = useCallback(() => setDraft(saved), [saved])\n\n  return { draft, changes, add, remove, merge, reset }\n}",
      "type": "registry:hook",
      "target": "components/openlmis/user-roles-page/use-role-draft.ts"
    },
    {
      "path": "registry/templates/openlmis/user-roles-page/components/user-roles-page.tsx",
      "content": "\"use client\"\n\nimport { CopyPlusIcon, ShieldIcon } from \"lucide-react\"\nimport { useCallback, useMemo, useState } from \"react\"\n\nimport { Badge } from \"@/components/ui/badge\"\nimport { Button } from \"@/components/ui/button\"\nimport { Tabs, TabsContent, TabsList, TabsTrigger } from \"@/components/ui/tabs\"\nimport { AddRoleDialog } from \"@/components/openlmis/user-roles-page/add-role-dialog\"\nimport { ImportRolesDialog } from \"@/components/openlmis/user-roles-page/import-roles-dialog\"\nimport {\n  byId,\n  countByType,\n  type Facility,\n  type Program,\n  type Role,\n  type RoleAssignment,\n  type RoleRow,\n  ROLE_TABS,\n  type RoleTab,\n  type SupervisoryNode,\n  toRoleRows,\n  assignmentKey,\n} from \"@/components/blocks/openlmis/role-assignments/role-assignments\"\nimport {\n  type LookupStatus,\n  RoleAssignmentsTable,\n} from \"@/components/blocks/openlmis/role-assignments/role-assignments-table\"\nimport {\n  Workspace,\n  WorkspaceActions,\n  WorkspaceContent,\n  WorkspaceDescription,\n  WorkspaceFooter,\n  WorkspaceHeader,\n  WorkspaceHeading,\n  WorkspaceIcon,\n  WorkspaceLayout,\n  WorkspaceTitle,\n} from \"@/components/blocks/openlmis/workspace\"\nimport { Callout } from \"@/components/openlmis/callout\"\nimport { DiscardChangesDialog } from \"@/components/openlmis/discard-changes-dialog\"\nimport { PageBreadcrumbs } from \"@/components/openlmis/page-breadcrumbs\"\n\nimport {\n  MOCK_FACILITIES,\n  MOCK_NODES,\n  MOCK_PROGRAMS,\n  MOCK_ROLES,\n  MOCK_USER_ID,\n  MOCK_USERS,\n  type RolesUser,\n} from \"@/components/openlmis/user-roles-page/mock-roles\"\nimport { useRoleDraft } from \"@/components/openlmis/user-roles-page/use-role-draft\"\n\ntype UserRolesPageProps = {\n  /** The user whose roles are edited. */\n  user?: RolesUser\n  /** Who roles can be imported from. */\n  users?: readonly RolesUser[]\n  roles?: readonly Role[]\n  programs?: readonly Program[]\n  /** Leave undefined while they load; their names show as placeholders meanwhile. */\n  nodes?: readonly SupervisoryNode[]\n  facilities?: readonly Facility[]\n  /** Save the roles, e.g. with one request; the draft becomes the saved roles. */\n  onSave?: (assignments: RoleAssignment[]) => void\n  /** Leave the page, e.g. back to the users list; asked first when there are unsaved changes. */\n  onCancel?: () => void\n}\n\ntype Notice =\n  | { kind: \"removed\"; row: RoleRow }\n  | { kind: \"imported\"; added: number; from: string }\n  | { kind: \"saved\" }\n\ntype OpenDialog =\n  | { kind: \"add\"; tab: RoleTab }\n  | { kind: \"import\" }\n  | { kind: \"discard\" }\n\nconst mockUser = MOCK_USERS.find((candidate) => candidate.id === MOCK_USER_ID)\n\n/** Edit User Roles: one draft across the four role tabs, saved together from the bar at the bottom. */\nexport function UserRolesPage({\n  user = mockUser,\n  users = MOCK_USERS,\n  roles = MOCK_ROLES,\n  programs = MOCK_PROGRAMS,\n  nodes = MOCK_NODES,\n  facilities = MOCK_FACILITIES,\n  onSave,\n  onCancel,\n}: UserRolesPageProps) {\n  // The page needs a user; the mock always has one.\n  if (!user) return null\n  return (\n    <RolesEditor\n      facilities={facilities}\n      key={user.id}\n      nodes={nodes}\n      onCancel={onCancel}\n      onSave={onSave}\n      programs={programs}\n      roles={roles}\n      user={user}\n      users={users}\n    />\n  )\n}\n\nfunction RolesEditor({\n  user,\n  users,\n  roles,\n  programs,\n  nodes,\n  facilities,\n  onSave,\n  onCancel,\n}: Omit<\n  Required<UserRolesPageProps>,\n  \"onSave\" | \"onCancel\" | \"nodes\" | \"facilities\"\n> &\n  Pick<UserRolesPageProps, \"onSave\" | \"onCancel\" | \"nodes\" | \"facilities\">) {\n  const [saved, setSaved] = useState(user.roleAssignments)\n  const draft = useRoleDraft(saved)\n  const [tab, setTab] = useState<RoleTab>(ROLE_TABS[0])\n  const [dialog, setDialog] = useState<OpenDialog>()\n  const [notice, setNotice] = useState<Notice>()\n  const closeDialog = () => setDialog(undefined)\n\n  const lookups = useMemo(\n    () => ({\n      roles: byId(roles),\n      programs: byId(programs),\n      nodes: nodes && byId(nodes),\n      facilities: facilities && byId(facilities),\n    }),\n    [roles, programs, nodes, facilities]\n  )\n  const status = useMemo<LookupStatus>(\n    () => ({\n      nodes: nodes ? \"ready\" : \"pending\",\n      facilities: facilities ? \"ready\" : \"pending\",\n    }),\n    [nodes, facilities]\n  )\n  const savedKeys = useMemo(() => new Set(saved.map(assignmentKey)), [saved])\n  const rows = useMemo(\n    () =>\n      toRoleRows(draft.draft, tab.type, {\n        lookups,\n        savedKeys,\n        homeFacilityId: user.homeFacilityId,\n      }),\n    [draft.draft, tab.type, lookups, savedKeys, user.homeFacilityId]\n  )\n  const counts = useMemo(\n    () => countByType(draft.draft, lookups.roles),\n    [draft.draft, lookups.roles]\n  )\n\n  const { remove } = draft\n  const removeRole = useCallback(\n    (row: RoleRow) => {\n      remove(row.assignment)\n      setNotice({ kind: \"removed\", row })\n    },\n    [remove]\n  )\n\n  const save = () => {\n    onSave?.(draft.draft)\n    setSaved(draft.draft)\n    setNotice({ kind: \"saved\" })\n  }\n  const cancel = () => {\n    if (draft.changes > 0) setDialog({ kind: \"discard\" })\n    else onCancel?.()\n  }\n  const name = [user.firstName, user.lastName].filter(Boolean).join(\" \")\n\n  return (\n    <WorkspaceLayout>\n      <Workspace>\n        <PageBreadcrumbs\n          items={[\n            { label: \"Home\", href: \"#\" },\n            { label: \"Administration\" },\n            { label: \"Users\", href: \"#\" },\n            { label: \"Roles\" },\n          ]}\n        />\n        <WorkspaceHeader>\n          <WorkspaceHeading>\n            <WorkspaceIcon>\n              <ShieldIcon />\n            </WorkspaceIcon>\n            <WorkspaceTitle>Roles for {name || user.username}</WorkspaceTitle>\n            <WorkspaceDescription>\n              What {user.username} can do in OpenLMIS, and where.\n            </WorkspaceDescription>\n          </WorkspaceHeading>\n          <WorkspaceActions>\n            <Button\n              onClick={() => setDialog({ kind: \"import\" })}\n              size=\"lg\"\n              variant=\"outline\"\n            >\n              <CopyPlusIcon data-icon=\"inline-start\" />\n              Import Roles\n            </Button>\n          </WorkspaceActions>\n        </WorkspaceHeader>\n        <WorkspaceContent>\n          {notice && (\n            <NoticeAlert\n              notice={notice}\n              onUndo={(row) => {\n                draft.add(row.assignment)\n                setNotice(undefined)\n              }}\n            />\n          )}\n          <Tabs\n            onValueChange={(value) =>\n              setTab(\n                ROLE_TABS.find((item) => item.id === value) ?? ROLE_TABS[0]\n              )\n            }\n            value={tab.id}\n          >\n            {/* A size container, so the tabs go two by two when four do not fit in a row. */}\n            <div className=\"@container/tabs\">\n              <TabsList\n                aria-label=\"Role types\"\n                className=\"grid h-auto w-full grid-cols-2 group-data-horizontal/tabs:h-auto @xl/tabs:flex @xl/tabs:w-fit\"\n              >\n                {ROLE_TABS.map((item) => (\n                  <TabsTrigger className=\"h-7\" key={item.id} value={item.id}>\n                    {item.label}\n                    <Badge variant=\"secondary\">{counts[item.type]}</Badge>\n                  </TabsTrigger>\n                ))}\n              </TabsList>\n            </div>\n            {ROLE_TABS.map((item) => (\n              <TabsContent className=\"pt-2\" key={item.id} value={item.id}>\n                {item.id === tab.id && (\n                  <RoleAssignmentsTable\n                    // Keyed, so each tab starts its own search, sort and paging.\n                    key={item.id}\n                    onAdd={() => setDialog({ kind: \"add\", tab: item })}\n                    onRemove={removeRole}\n                    rows={rows}\n                    status={status}\n                    tab={item}\n                  />\n                )}\n              </TabsContent>\n            ))}\n          </Tabs>\n        </WorkspaceContent>\n      </Workspace>\n      <WorkspaceFooter>\n        <Button onClick={cancel} size=\"lg\" variant=\"outline\">\n          Cancel\n        </Button>\n        <Button disabled={draft.changes === 0} onClick={save} size=\"lg\">\n          Save Changes\n          {draft.changes > 0 && (\n            <Badge variant=\"secondary\">\n              <span aria-hidden=\"true\">{draft.changes}</span>\n              <span className=\"sr-only\">\n                {draft.changes === 1\n                  ? \"1 unsaved change\"\n                  : `${draft.changes} unsaved changes`}\n              </span>\n            </Badge>\n          )}\n        </Button>\n      </WorkspaceFooter>\n\n      <AddRoleDialog\n        assigned={draft.draft}\n        facilities={facilities}\n        hasHomeFacility={Boolean(user.homeFacilityId)}\n        nodes={nodes}\n        onAdd={(assignment) => {\n          draft.add(assignment)\n          setNotice(undefined)\n        }}\n        onClose={closeDialog}\n        programs={programs}\n        roles={roles}\n        type={dialog?.kind === \"add\" ? dialog.tab.type : undefined}\n        username={user.username}\n      />\n      <ImportRolesDialog\n        draft={draft.draft}\n        onClose={closeDialog}\n        onImport={(assignments, from) => {\n          const { added } = draft.merge(assignments)\n          setNotice({ kind: \"imported\", added, from })\n        }}\n        open={dialog?.kind === \"import\"}\n        userId={user.id}\n        username={user.username}\n        users={users}\n      />\n      <DiscardChangesDialog\n        changes={draft.changes}\n        onDiscard={() => {\n          draft.reset()\n          setNotice(undefined)\n          closeDialog()\n          onCancel?.()\n        }}\n        onKeepEditing={closeDialog}\n        open={dialog?.kind === \"discard\"}\n        subject={`the roles of ${user.username}`}\n      />\n    </WorkspaceLayout>\n  )\n}\n\n/** What just happened to the draft, with Undo for a removal; it stays until the next change. */\nfunction NoticeAlert({\n  notice,\n  onUndo,\n}: {\n  notice: Notice\n  onUndo: (row: RoleRow) => void\n}) {\n  if (notice.kind === \"saved\") {\n    return (\n      <Callout title=\"Roles Saved\" tone=\"success\">\n        The changes are saved.\n      </Callout>\n    )\n  }\n  if (notice.kind === \"imported\") {\n    return (\n      <Callout title=\"Roles Imported\" tone=\"info\">\n        {notice.added === 1 ? \"1 role\" : `${notice.added} roles`} added from{\" \"}\n        {notice.from}. Save to keep them.\n      </Callout>\n    )\n  }\n  return (\n    <Callout\n      action={\n        <Button\n          onClick={() => onUndo(notice.row)}\n          size=\"sm\"\n          type=\"button\"\n          variant=\"outline\"\n        >\n          Undo\n        </Button>\n      }\n      title=\"Role Removed\"\n      tone=\"info\"\n    >\n      {notice.row.role ?? \"The role\"} is removed. Save to keep the change.\n    </Callout>\n  )\n}",
      "type": "registry:component",
      "target": "components/openlmis/user-roles-page/user-roles-page.tsx"
    },
    {
      "path": "registry/templates/openlmis/user-roles-page/page.tsx",
      "content": "import { UserRolesPage } from \"@/components/openlmis/user-roles-page/user-roles-page\"\n\n// A Next.js App Router route; in any other React app, render UserRolesPage from your own route.\nexport default function Page() {\n  return <UserRolesPage />\n}",
      "type": "registry:page",
      "target": "app/user-roles-page/page.tsx"
    }
  ],
  "cssVars": {
    "light": {
      "destructive": "oklch(0.577 0.245 27.325)",
      "destructive-foreground": "oklch(0.985 0 0)",
      "success": "oklch(0.596 0.145 163.225)",
      "success-foreground": "oklch(0.985 0 0)",
      "warning": "oklch(0.666 0.179 58.318)",
      "warning-foreground": "oklch(0.985 0 0)",
      "info": "oklch(0.55 0.13 237)",
      "info-foreground": "oklch(0.985 0 0)"
    },
    "dark": {
      "destructive": "oklch(0.704 0.191 22.216)",
      "destructive-foreground": "oklch(0.21 0.04 25)",
      "success": "oklch(0.696 0.17 162.48)",
      "success-foreground": "oklch(0.21 0.04 163)",
      "warning": "oklch(0.769 0.188 70.08)",
      "warning-foreground": "oklch(0.22 0.04 60)",
      "info": "oklch(0.7 0.14 237)",
      "info-foreground": "oklch(0.2 0.04 240)"
    }
  },
  "meta": {
    "project": "openlmis",
    "height": "561px"
  },
  "categories": [
    "users",
    "roles"
  ],
  "type": "registry:page"
}
