{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "openlmis-profile-page",
  "title": "Profile Page",
  "description": "A mock profile with basic information, read-only role assignments, notification settings and a change password dialog.",
  "dependencies": [
    "@tanstack/react-form@^1",
    "@tanstack/react-table@^9",
    "lucide-react@^1",
    "react-dom@^19",
    "zod@^4",
    "@base-ui/react@^1"
  ],
  "registryDependencies": [
    "alert",
    "badge",
    "button",
    "dropdown-menu",
    "field",
    "skeleton",
    "spinner",
    "table",
    "tabs",
    "utils",
    "https://registry.soldevelo.com/r/openlmis-callout.json",
    "https://registry.soldevelo.com/r/openlmis-data-table.json",
    "https://registry.soldevelo.com/r/openlmis-discard-changes-dialog.json",
    "https://registry.soldevelo.com/r/openlmis-form-actions.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-password-requirements.json",
    "https://registry.soldevelo.com/r/openlmis-role-assignments.json",
    "https://registry.soldevelo.com/r/openlmis-settings-list.json",
    "https://registry.soldevelo.com/r/openlmis-status-badge.json",
    "https://registry.soldevelo.com/r/openlmis-workspace.json",
    "https://registry.soldevelo.com/r/openlmis-workspace-tabs.json"
  ],
  "files": [
    {
      "path": "registry/templates/openlmis/profile-page/components/change-password-dialog/change-password-dialog.tsx",
      "content": "\"use client\"\n\nimport { revalidateLogic } from \"@tanstack/react-form\"\nimport { type ReactNode, useId, useMemo } from \"react\"\n\nimport { FieldGroup } from \"@/components/ui/field\"\nimport {\n  FormDialog,\n  FormDialogBody,\n  FormDialogCancel,\n  FormDialogDescription,\n  FormDialogError,\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 { PasswordRequirements } from \"@/components/openlmis/password-requirements/password-requirements\"\nimport type { PasswordOwner } from \"@/components/openlmis/password-requirements/password-rules\"\nimport { newPasswordSchema } from \"@/components/openlmis/password-requirements/password-schema\"\n\n// Re-exported so existing imports from this block keep working.\nexport { newPasswordSchema }\n\ntype ChangePasswordDialogProps = {\n  open: boolean\n  /** Whose password it is; its username also lets a password manager file the new one. */\n  user: PasswordOwner\n  /** Called with the new password; change it, then close, e.g. by signing out. */\n  onSubmit: (password: string) => void\n  /** Keeps the dialog open and shows a spinner while the password is changed. */\n  pending?: boolean\n  /** Shown above the fields, e.g. why the change was refused. */\n  error?: ReactNode\n  onClose: () => void\n}\n\nexport function ChangePasswordDialog({\n  open,\n  user,\n  onSubmit,\n  pending = false,\n  error,\n  onClose,\n}: ChangePasswordDialogProps) {\n  const { shown, dialogProps } = useDialogTarget(\n    open ? true : undefined,\n    onClose\n  )\n\n  return (\n    <FormDialog {...dialogProps(pending)}>\n      {shown && (\n        <ChangePasswordForm\n          error={error}\n          onSubmit={onSubmit}\n          pending={pending}\n          user={user}\n        />\n      )}\n    </FormDialog>\n  )\n}\n\nfunction ChangePasswordForm({\n  user,\n  onSubmit,\n  pending,\n  error,\n}: Pick<ChangePasswordDialogProps, \"user\" | \"onSubmit\" | \"error\"> & {\n  pending: boolean\n}) {\n  const requirementsId = useId()\n  const schema = useMemo(() => newPasswordSchema(user), [user])\n  const form = useAppForm({\n    defaultValues: { password: \"\", confirm: \"\" },\n    // Quiet until the first submit, then each field re-checks as it is corrected.\n    validationLogic: revalidateLogic({\n      mode: \"submit\",\n      modeAfterSubmission: \"change\",\n    }),\n    validators: { onDynamic: schema },\n    onSubmit: ({ value }) => onSubmit(value.password),\n  })\n\n  return (\n    <FormDialogForm onSubmit={form.handleSubmit}>\n      <FormDialogHeader>\n        <FormDialogTitle>Change Password</FormDialogTitle>\n        <FormDialogDescription>\n          After changing it you will be signed out, so you can sign in with the\n          new password.\n        </FormDialogDescription>\n      </FormDialogHeader>\n      <FormDialogBody>\n        <FieldGroup>\n          {error && (\n            <FormDialogError\n              description={error}\n              title=\"Could Not Change Password\"\n            />\n          )}\n          {/* Lets password managers file the new password under the right account. */}\n          <input\n            autoComplete=\"username\"\n            hidden\n            readOnly\n            value={user.username}\n          />\n          <form.AppField name=\"password\">\n            {(field) => (\n              <div className=\"grid gap-3\">\n                <field.PasswordField\n                  describedBy={requirementsId}\n                  label=\"New Password\"\n                  required\n                />\n                <PasswordRequirements\n                  id={requirementsId}\n                  owner={user}\n                  password={field.state.value}\n                />\n              </div>\n            )}\n          </form.AppField>\n          <form.AppField name=\"confirm\">\n            {(field) => (\n              <field.PasswordField label=\"Confirm New Password\" required />\n            )}\n          </form.AppField>\n        </FieldGroup>\n      </FormDialogBody>\n      <FormDialogFooter>\n        <FormDialogCancel disabled={pending} />\n        <FormDialogSubmit pending={pending}>Change Password</FormDialogSubmit>\n      </FormDialogFooter>\n    </FormDialogForm>\n  )\n}",
      "type": "registry:component",
      "target": "components/openlmis/profile-page/change-password-dialog.tsx"
    },
    {
      "path": "registry/templates/openlmis/profile-page/components/mock-profile.ts",
      "content": "// A mock signed-in user, their roles and notification settings, so the page runs with no backend.\n\nimport type { Profile } from \"@/components/openlmis/profile-page/profile\"\nimport type {\n  DigestConfiguration,\n  DigestSubscription,\n} from \"@/components/openlmis/profile-page/digest\"\nimport type {\n  Facility,\n  Program,\n  Role,\n  RoleAssignment,\n  SupervisoryNode,\n} from \"@/components/blocks/openlmis/role-assignments/role-assignments\"\n\nexport const MOCK_PROFILE: Profile = {\n  user: {\n    id: \"user-divo1\",\n    username: \"divo1\",\n    firstName: \"Grace\",\n    lastName: \"Banda\",\n    jobTitle: \"District Immunization Officer\",\n    homeFacility: \"HC02 - Comfort Health Clinic\",\n  },\n  contact: {\n    email: \"grace.banda@example.org\",\n    emailVerified: true,\n    phoneNumber: \"+265 999 123 456\",\n    allowNotify: true,\n  },\n}\n\nexport const MOCK_HOME_FACILITY_ID = \"facility-hc02\"\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    ],\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\nexport const MOCK_PROGRAMS: Program[] = [\n  { id: \"program-family\", name: \"Family Planning\" },\n  { id: \"program-epi\", name: \"EPI\" },\n  { id: \"program-essential\", name: \"Essential Meds\" },\n]\n\nexport const MOCK_FACILITIES: Facility[] = [\n  { id: \"facility-hc02\", code: \"HC02\", name: \"Comfort Health Clinic\" },\n  { id: \"facility-dh01\", code: \"DH01\", name: \"Balaka District Hospital\" },\n  { id: \"facility-ww01\", code: \"WH01\", name: \"Ninitall Warehouse\" },\n  { id: \"facility-ww02\", code: \"WH02\", name: \"Balaka District Warehouse\" },\n]\n\nexport const MOCK_NODES: SupervisoryNode[] = [\n  {\n    id: \"node-fp-approval\",\n    name: \"FP Approval Point\",\n    facility: { id: \"facility-dh01\" },\n  },\n  {\n    id: \"node-epi-southern\",\n    name: \"EPI Southern Region\",\n    facility: { id: \"facility-dh01\" },\n  },\n]\n\nexport const MOCK_ASSIGNMENTS: RoleAssignment[] = [\n  { roleId: \"role-storeroom\", programId: \"program-family\" },\n  { roleId: \"role-storeroom\", programId: \"program-essential\" },\n  {\n    roleId: \"role-approver\",\n    programId: \"program-family\",\n    supervisoryNodeId: \"node-fp-approval\",\n  },\n  {\n    roleId: \"role-approver\",\n    programId: \"program-epi\",\n    supervisoryNodeId: \"node-epi-southern\",\n  },\n  { roleId: \"role-warehouse\", warehouseId: \"facility-ww01\" },\n  { roleId: \"role-warehouse\", warehouseId: \"facility-ww02\" },\n  { roleId: \"role-reports\" },\n]\n\nexport const MOCK_DIGEST_CONFIGURATIONS: DigestConfiguration[] = [\n  { id: \"digest-action-required\", tag: \"requisition-actionRequired\" },\n  { id: \"digest-status-update\", tag: \"requisition-statusUpdate\" },\n  { id: \"digest-order-shipped\", tag: \"order-shipped\" },\n  { id: \"digest-low-stock\", tag: \"stockEvent-lowStock\" },\n]\n\nexport const MOCK_SUBSCRIPTIONS: DigestSubscription[] = [\n  {\n    digestConfiguration: { id: \"digest-action-required\" },\n    preferredChannel: \"EMAIL\",\n    useDigest: true,\n    cronExpression: \"0 0 8 * * 1\",\n  },\n  {\n    digestConfiguration: { id: \"digest-status-update\" },\n    preferredChannel: \"SMS\",\n    useDigest: false,\n  },\n  {\n    digestConfiguration: { id: \"digest-order-shipped\" },\n    preferredChannel: \"EMAIL\",\n    useDigest: true,\n    cronExpression: \"0 0 7 * * *\",\n  },\n]",
      "type": "registry:lib",
      "target": "components/openlmis/profile-page/mock-profile.ts"
    },
    {
      "path": "registry/templates/openlmis/profile-page/components/profile-basic-information/profile-basic-information.tsx",
      "content": "\"use client\"\n\nimport { revalidateLogic, useStore } from \"@tanstack/react-form\"\nimport { MailIcon } from \"lucide-react\"\nimport { type ReactNode, useEffect, useId, useRef } from \"react\"\n\nimport {\n  Alert,\n  AlertAction,\n  AlertDescription,\n  AlertTitle,\n} from \"@/components/ui/alert\"\nimport { Badge } from \"@/components/ui/badge\"\nimport { Button } from \"@/components/ui/button\"\nimport { Skeleton } from \"@/components/ui/skeleton\"\nimport { Spinner } from \"@/components/ui/spinner\"\nimport { cn } from \"@/lib/utils\"\nimport { FormDialogError } from \"@/components/openlmis/form-dialog/form-dialog\"\nimport { useAppForm } from \"@/components/openlmis/form-fields/form\"\nimport { FieldLabelText } from \"@/components/openlmis/form-fields/form-fields\"\nimport {\n  SettingsItem,\n  SettingsList,\n  SettingsRowFrame,\n} from \"@/components/blocks/openlmis/settings-list\"\nimport { StatusBadge } from \"@/components/openlmis/status-badge\"\n\nimport {\n  type Profile,\n  type ProfileFormValues,\n  countProfileChanges,\n  profileFormSchema,\n  toProfileFormValues,\n} from \"@/components/openlmis/profile-page/profile\"\nimport {\n  type FormActionState as ProfileFormActions,\n  FormActions as ProfileFormButtons,\n} from \"@/components/openlmis/form-actions\"\n\ntype ProfileBasicInformationProps = {\n  /** A skeleton of every row shows until it is set. */\n  profile: Profile | undefined\n  /** Called with the values when something changed; save them, then pass the saved profile back. */\n  onSubmit: (values: ProfileFormValues, profile: Profile) => void\n  /** Disables the buttons and shows a spinner while the profile is saved. */\n  pending?: boolean\n  /** Shown above the rows, e.g. why the save failed. */\n  error?: ReactNode\n  /** A new address waiting for its verification link to be opened. */\n  pendingEmail?: string | null\n  /** Sends the verification link again; Resend Link is hidden without it. */\n  onResendEmail?: () => void\n  resendPending?: boolean\n  /** Tells the page how many fields have unsaved changes, e.g. to ask before leaving. */\n  onChangesChange?: (changes: number) => void\n  onCancel?: () => void\n  /** Places Cancel and Save; by default they sit in a row under the form. */\n  renderActions?: (actions: ProfileFormActions) => ReactNode\n}\n\n/** The user's own details as rows of settings: what an administrator set, then what they can edit. */\nexport function ProfileBasicInformation({\n  profile,\n  ...props\n}: ProfileBasicInformationProps) {\n  if (!profile) return <ProfileBasicInformationSkeleton />\n  return <ProfileForm profile={profile} {...props} />\n}\n\nfunction ProfileForm({\n  profile,\n  onSubmit,\n  pending = false,\n  error,\n  pendingEmail,\n  onResendEmail,\n  resendPending = false,\n  onChangesChange,\n  onCancel,\n  renderActions,\n}: ProfileBasicInformationProps & { profile: Profile }) {\n  const formId = useId()\n  const { user, contact } = profile\n  const emailVerified = contact?.emailVerified ?? false\n  const savedEmail = contact?.email ?? \"\"\n\n  const form = useAppForm({\n    defaultValues: toProfileFormValues(profile),\n    // Quiet until the first submit, then each field re-checks as it is corrected.\n    validationLogic: revalidateLogic({\n      mode: \"submit\",\n      modeAfterSubmission: \"change\",\n    }),\n    validators: { onDynamic: profileFormSchema },\n    onSubmit: ({ value }) => onSubmit(value, profile),\n  })\n  // Only whether anything changed, so typing re-renders this page, not every part of it.\n  const changes = useStore(form.store, (state) =>\n    countProfileChanges(profile, state.values)\n  )\n  const changed = changes > 0\n\n  const savedSignature = JSON.stringify([user.id, toProfileFormValues(profile)])\n  const lastSaved = useRef(savedSignature)\n\n  // Equivalent props must not replace a draft when a parent renders again.\n  useEffect(() => {\n    if (lastSaved.current === savedSignature) return\n    lastSaved.current = savedSignature\n    form.reset(toProfileFormValues(profile))\n  }, [form, profile, savedSignature])\n  useEffect(() => {\n    onChangesChange?.(changes)\n  }, [changes, onChangesChange])\n\n  const actions: ProfileFormActions = {\n    formId,\n    changed,\n    pending,\n    cancel: () => {\n      form.reset(toProfileFormValues(profile))\n      onCancel?.()\n    },\n  }\n\n  return (\n    <>\n      <form\n        className=\"flex flex-col gap-4\"\n        id={formId}\n        noValidate\n        onSubmit={(event) => {\n          event.preventDefault()\n          if (changed) void form.handleSubmit()\n        }}\n      >\n        {error && (\n          <FormDialogError description={error} title=\"Could Not Save Profile\" />\n        )}\n        {pendingEmail && (\n          <Alert>\n            <MailIcon />\n            <AlertTitle>Email Change Pending</AlertTitle>\n            <AlertDescription>\n              {pendingEmail} is waiting to be verified. Open the link sent to it\n              to start using it.\n            </AlertDescription>\n            {onResendEmail && (\n              <AlertAction>\n                <Button\n                  disabled={resendPending}\n                  onClick={onResendEmail}\n                  size=\"sm\"\n                  type=\"button\"\n                  variant=\"outline\"\n                >\n                  {resendPending && <Spinner data-icon=\"inline-start\" />}\n                  Resend Link\n                </Button>\n              </AlertAction>\n            )}\n          </Alert>\n        )}\n        <SettingsList>\n          <SettingsItem label=\"Username\">{user.username}</SettingsItem>\n          <SettingsItem label=\"Job Title\">\n            {user.jobTitle || <None />}\n          </SettingsItem>\n          <SettingsItem label=\"Home Facility\">\n            {user.homeFacility || <None />}\n          </SettingsItem>\n          <form.AppField name=\"firstName\">\n            {(field) => (\n              <field.TextField\n                autoComplete=\"given-name\"\n                label=\"First Name\"\n                layout=\"row\"\n                required\n              />\n            )}\n          </form.AppField>\n          <form.AppField name=\"lastName\">\n            {(field) => (\n              <field.TextField\n                autoComplete=\"family-name\"\n                label=\"Last Name\"\n                layout=\"row\"\n                required\n              />\n            )}\n          </form.AppField>\n          <form.AppField name=\"email\">\n            {(field) => {\n              const typed = field.state.value.trim()\n              // The saved address shows whether it is verified; a new one, that it waits for its link.\n              const isSaved = typed !== \"\" && typed === savedEmail\n              return (\n                <field.TextField\n                  autoComplete=\"email\"\n                  badge={isSaved && <EmailStatus verified={emailVerified} />}\n                  description={\n                    typed &&\n                    !isSaved &&\n                    \"A link to confirm this address will be sent to it. Your current address stays in use until then.\"\n                  }\n                  dir=\"ltr\"\n                  label=\"Email\"\n                  layout=\"row\"\n                  type=\"email\"\n                />\n              )\n            }}\n          </form.AppField>\n          <form.AppField name=\"phoneNumber\">\n            {(field) => (\n              <field.TextField\n                autoComplete=\"tel\"\n                dir=\"ltr\"\n                label=\"Phone Number\"\n                layout=\"row\"\n                type=\"tel\"\n              />\n            )}\n          </form.AppField>\n          <form.Subscribe\n            selector={(state) => state.values.email.trim() !== \"\"}\n          >\n            {(hasEmail) => (\n              <form.AppField name=\"allowNotify\">\n                {(field) => (\n                  <field.SwitchField\n                    description={\n                      emailVerified && hasEmail\n                        ? \"Get every notification your roles allow. Turn off to get none.\"\n                        : \"Verify your email address to turn this on.\"\n                    }\n                    disabled={!emailVerified || !hasEmail}\n                    label=\"Allow Notifications\"\n                    layout=\"row\"\n                  />\n                )}\n              </form.AppField>\n            )}\n          </form.Subscribe>\n        </SettingsList>\n      </form>\n      {renderActions ? (\n        renderActions(actions)\n      ) : (\n        <div className=\"flex justify-end gap-2\">\n          <ProfileFormButtons actions={actions} saveLabel=\"Save Profile\" />\n        </div>\n      )}\n    </>\n  )\n}\n\nfunction EmailStatus({ verified }: { verified: boolean }) {\n  return verified ? (\n    <StatusBadge tone=\"success\">Verified</StatusBadge>\n  ) : (\n    <Badge variant=\"secondary\">Not Verified</Badge>\n  )\n}\n\nfunction None() {\n  return <span className=\"text-muted-foreground\">None</span>\n}\n\nconst SKELETON_INPUTS = [\n  { label: \"First Name\", required: true },\n  { label: \"Last Name\", required: true },\n  { label: \"Email\" },\n  { label: \"Phone Number\" },\n]\n\n/** The rows while the profile loads: every row under its real label, with placeholders for the values. */\nexport function ProfileBasicInformationSkeleton() {\n  return (\n    <div aria-busy>\n      <SettingsList>\n        <SettingsItem label=\"Username\">\n          <SkeletonText className=\"w-24\" />\n        </SettingsItem>\n        <SettingsItem label=\"Job Title\">\n          <SkeletonText className=\"w-32\" />\n        </SettingsItem>\n        <SettingsItem label=\"Home Facility\">\n          <SkeletonText className=\"w-48\" />\n        </SettingsItem>\n        {SKELETON_INPUTS.map(({ label, required }) => (\n          <SettingsRowFrame\n            key={label}\n            label={\n              <span className=\"text-sm\">\n                <FieldLabelText label={label} required={required} />\n              </span>\n            }\n            value=\"control\"\n          >\n            <Skeleton className=\"h-8 w-full\" />\n          </SettingsRowFrame>\n        ))}\n        <SettingsRowFrame\n          description={\n            <span className=\"flex h-5 items-center\">\n              <Skeleton className=\"h-3.5 w-64 max-w-full\" />\n            </span>\n          }\n          label={<span className=\"text-sm\">Allow Notifications</span>}\n        >\n          {/* A plain element, since Skeleton owns its corner radius and a switch is round. */}\n          <span className=\"h-4.5 w-8 animate-pulse rounded-full bg-muted\" />\n        </SettingsRowFrame>\n      </SettingsList>\n    </div>\n  )\n}\n\n/** A bar inside one line of small text, so it takes the room the text will. */\nfunction SkeletonText({ className }: { className: string }) {\n  return (\n    <span className=\"flex h-5 items-center justify-end\">\n      <Skeleton className={cn(\"h-3.5\", className)} />\n    </span>\n  )\n}",
      "type": "registry:component",
      "target": "components/openlmis/profile-page/profile-basic-information.tsx"
    },
    {
      "path": "registry/templates/openlmis/profile-page/components/profile-basic-information/profile.ts",
      "content": "import { z } from \"zod\"\n\n/** The signed-in user as the profile shows them; an administrator sets the read-only parts. */\nexport type ProfileUser = {\n  id: string\n  username: string\n  firstName: string\n  lastName: string\n  jobTitle?: string | null\n  /** The home facility as display text, e.g. \"HC01 - Balaka District Hospital\". */\n  homeFacility?: string | null\n}\n\nexport type ProfileContact = {\n  email: string | null\n  emailVerified: boolean\n  phoneNumber: string | null\n  allowNotify: boolean\n}\n\n/** The user and their contact details; a user without contact details has `null`. */\nexport type Profile = {\n  user: ProfileUser\n  contact: ProfileContact | null\n}\n\nconst requiredText = (message: string) => z.string().trim().min(1, message)\n\nexport const profileFormSchema = z.object({\n  firstName: requiredText(\"Enter a first name.\"),\n  lastName: requiredText(\"Enter a last name.\"),\n  email: z\n    .string()\n    .trim()\n    .refine(\n      (email) => email === \"\" || z.email().safeParse(email).success,\n      \"Enter a valid email address.\"\n    ),\n  phoneNumber: z.string(),\n  allowNotify: z.boolean(),\n})\n\nexport type ProfileFormValues = z.input<typeof profileFormSchema>\n\nexport function toProfileFormValues({\n  user,\n  contact,\n}: Profile): ProfileFormValues {\n  return {\n    firstName: user.firstName,\n    lastName: user.lastName,\n    email: contact?.email ?? \"\",\n    phoneNumber: contact?.phoneNumber ?? \"\",\n    allowNotify: contact?.allowNotify ?? false,\n  }\n}\n\nconst orNull = (value: string) => value.trim() || null\n\n/** Which parts of the profile the form changed, so a save sends only those. */\nexport function profileChanges(\n  { user, contact }: Profile,\n  values: ProfileFormValues\n) {\n  const email = orNull(values.email) !== (contact?.email ?? null)\n  return {\n    user:\n      values.firstName.trim() !== user.firstName ||\n      values.lastName.trim() !== user.lastName,\n    contact:\n      email ||\n      orNull(values.phoneNumber) !== (contact?.phoneNumber ?? null) ||\n      values.allowNotify !== (contact?.allowNotify ?? false),\n    email,\n  }\n}\n\n/** The profile as a successful save leaves it; a new email waits for its link, so the old one stays. */\nexport function applySaved(\n  profile: Profile,\n  values: ProfileFormValues\n): Profile {\n  const email = orNull(values.email)\n  return {\n    user: {\n      ...profile.user,\n      firstName: values.firstName.trim(),\n      lastName: values.lastName.trim(),\n    },\n    contact: {\n      email: profile.contact?.email ?? null,\n      emailVerified: profile.contact?.emailVerified ?? false,\n      phoneNumber: orNull(values.phoneNumber),\n      // Nothing can be sent without an address, as the legacy UI has it.\n      allowNotify: values.allowNotify && email !== null,\n    },\n  }\n}\n\n/** How many fields differ from the saved profile, e.g. for a discard prompt. */\nexport function countProfileChanges(\n  profile: Profile,\n  values: ProfileFormValues\n): number {\n  const saved = toProfileFormValues(profile)\n  const keys = Object.keys(saved) as (keyof ProfileFormValues)[]\n  return keys.filter((key) => {\n    const before = saved[key]\n    const after = values[key]\n    return typeof before === \"string\" && typeof after === \"string\"\n      ? before.trim() !== after.trim()\n      : before !== after\n  }).length\n}",
      "type": "registry:lib",
      "target": "components/openlmis/profile-page/profile.ts"
    },
    {
      "path": "registry/templates/openlmis/profile-page/components/profile-notification-settings/digest.ts",
      "content": "import { z } from \"zod\"\n\nexport const NOTIFICATION_CHANNELS = [\"EMAIL\", \"SMS\"] as const\n\nexport type NotificationChannel = (typeof NOTIFICATION_CHANNELS)[number]\n\n/** A kind of notification that can be gathered into a digest, e.g. `requisition-actionRequired`. */\nexport type DigestConfiguration = {\n  id: string\n  tag: string\n}\n\nexport type DigestSubscription = {\n  digestConfiguration: { id: string }\n  preferredChannel: NotificationChannel\n  useDigest: boolean\n  cronExpression?: string | null\n}\n\nexport const FREQUENCIES = [\"daily\", \"weekly\", \"custom\"] as const\n\nexport type Frequency = (typeof FREQUENCIES)[number]\n\nexport const FREQUENCY_LABELS: Record<Frequency, string> = {\n  daily: \"Daily\",\n  weekly: \"Weekly\",\n  custom: \"Custom\",\n}\n\n/** A schedule as the form edits it; `weekday` is Sunday 0 to Saturday 6, as in cron. */\nconst scheduleSchema = z.object({\n  frequency: z.enum(FREQUENCIES),\n  weekday: z.string(),\n  time: z.string(),\n  cron: z.string(),\n})\n\nconst rowFields = z.object({\n  configurationId: z.string(),\n  tag: z.string(),\n  channel: z.enum(NOTIFICATION_CHANNELS),\n  useDigest: z.boolean(),\n  schedule: scheduleSchema,\n})\n\ntype Schedule = z.infer<typeof scheduleSchema>\n\nexport type DigestRow = z.infer<typeof rowFields>\n\nexport const WEEKDAYS = [\"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\"] as const\n\n// Seconds, minutes, hours, day of month, month, day of week: the Spring cron OpenLMIS reads.\nconst SIMPLE_CRON = /^0 (\\d{1,2}) (\\d{1,2}) \\* \\* (\\*|[0-6])$/\nconst CRON_FIELD = /^[\\dA-Za-z*?/,#-]+$/\nconst TIME = /^(\\d{2}):(\\d{2})$/\n\nconst pad = (value: number) => String(value).padStart(2, \"0\")\n\n/** Daily or weekly at a time when the expression is that simple, otherwise custom. */\nexport function parseSchedule(cron: string | null | undefined): Schedule {\n  if (!cron)\n    return { frequency: \"daily\", weekday: \"0\", time: \"08:00\", cron: \"\" }\n  const [, minute, hour, weekday] = SIMPLE_CRON.exec(cron) ?? []\n  if (\n    !minute ||\n    !hour ||\n    !weekday ||\n    Number(minute) > 59 ||\n    Number(hour) > 23\n  ) {\n    return { frequency: \"custom\", weekday: \"0\", time: \"08:00\", cron }\n  }\n  return {\n    frequency: weekday === \"*\" ? \"daily\" : \"weekly\",\n    weekday: weekday === \"*\" ? \"0\" : weekday,\n    time: `${pad(Number(hour))}:${pad(Number(minute))}`,\n    cron,\n  }\n}\n\nexport function toCron({ frequency, weekday, time, cron }: Schedule): string {\n  if (frequency === \"custom\") return cron.trim()\n  const [, hour = \"0\", minute = \"0\"] = TIME.exec(time) ?? []\n  return `0 ${Number(minute)} ${Number(hour)} * * ${frequency === \"daily\" ? \"*\" : weekday}`\n}\n\n/** Six fields of cron characters; the server checks the values themselves. */\nexport function isValidCron(cron: string): boolean {\n  const fields = cron.trim().split(/\\s+/)\n  return fields.length === 6 && fields.every((field) => CRON_FIELD.test(field))\n}\n\n/** `requisition-actionRequired` as \"Requisition - Action Required\". */\nexport function tagLabel(tag: string): string {\n  return tag\n    .split(\"-\")\n    .map((part) =>\n      part\n        .replace(/([a-z])([A-Z])/g, \"$1 $2\")\n        .replace(/(^|\\s)\\S/g, (letter) => letter.toUpperCase())\n    )\n    .join(\" - \")\n}\n\n/** One row per configuration; one the user never subscribed to is email without a digest. */\nexport function toDigestRows(\n  configurations: readonly DigestConfiguration[],\n  subscriptions: readonly DigestSubscription[]\n): DigestRow[] {\n  const byId = new Map(\n    subscriptions.map((item) => [item.digestConfiguration.id, item])\n  )\n  return configurations.map(({ id, tag }) => {\n    const subscription = byId.get(id)\n    return {\n      configurationId: id,\n      tag,\n      channel: subscription?.preferredChannel ?? \"EMAIL\",\n      useDigest: subscription?.useDigest ?? false,\n      schedule: parseSchedule(subscription?.cronExpression),\n    }\n  })\n}\n\nexport function toSubscriptions(\n  rows: readonly DigestRow[]\n): DigestSubscription[] {\n  return rows.map(({ configurationId, channel, useDigest, schedule }) => ({\n    digestConfiguration: { id: configurationId },\n    preferredChannel: channel,\n    useDigest,\n    ...(useDigest && { cronExpression: toCron(schedule) }),\n  }))\n}\n\n/** How many notifications would save differently from how they were loaded. */\nexport function countDigestChanges(\n  saved: readonly DigestRow[],\n  rows: readonly DigestRow[]\n): number {\n  const before = toSubscriptions(saved).map((item) => JSON.stringify(item))\n  return toSubscriptions(rows).filter(\n    (item, index) => JSON.stringify(item) !== before[index]\n  ).length\n}\n\nconst rowSchema = rowFields.superRefine(\n  ({ useDigest, channel, schedule }, context) => {\n    if (!useDigest) return\n    if (channel !== \"EMAIL\") {\n      context.addIssue({\n        code: \"custom\",\n        path: [\"channel\"],\n        message: \"Digests are sent by email only.\",\n      })\n    }\n    if (schedule.frequency === \"custom\") {\n      if (!isValidCron(schedule.cron)) {\n        context.addIssue({\n          code: \"custom\",\n          path: [\"schedule\", \"cron\"],\n          message:\n            \"Enter six fields: seconds, minutes, hours, day, month and weekday.\",\n        })\n      }\n    } else if (!TIME.test(schedule.time)) {\n      context.addIssue({\n        code: \"custom\",\n        path: [\"schedule\", \"time\"],\n        message: \"Enter a time.\",\n      })\n    }\n  }\n)\n\nexport const digestFormSchema = z.object({ rows: z.array(rowSchema) })",
      "type": "registry:lib",
      "target": "components/openlmis/profile-page/digest.ts"
    },
    {
      "path": "registry/templates/openlmis/profile-page/components/profile-notification-settings/profile-notification-settings.tsx",
      "content": "\"use client\"\n\nimport { revalidateLogic, useStore } from \"@tanstack/react-form\"\nimport { BellOffIcon, MailXIcon } from \"lucide-react\"\nimport { type ReactNode, useEffect, useId, useMemo, useRef } from \"react\"\n\nimport { Skeleton } from \"@/components/ui/skeleton\"\nimport {\n  Table,\n  TableBody,\n  TableCell,\n  TableHead,\n  TableHeader,\n  TableRow,\n} from \"@/components/ui/table\"\nimport {\n  DataTableCard,\n  DataTableEmpty,\n  DataTableError,\n} from \"@/components/blocks/openlmis/data-table/data-table\"\nimport {\n  type FormActionState as ProfileFormActions,\n  FormActions as ProfileFormButtons,\n} from \"@/components/openlmis/form-actions\"\nimport { FormDialogError } from \"@/components/openlmis/form-dialog/form-dialog\"\nimport { useAppForm } from \"@/components/openlmis/form-fields/form\"\n\nimport {\n  countDigestChanges,\n  type DigestConfiguration,\n  type DigestRow,\n  type DigestSubscription,\n  digestFormSchema,\n  FREQUENCIES,\n  FREQUENCY_LABELS,\n  type Frequency,\n  tagLabel,\n  toCron,\n  toDigestRows,\n  toSubscriptions,\n  WEEKDAYS,\n} from \"@/components/openlmis/profile-page/digest\"\n\n// Isolated left to right with no-break spaces, so it reads the same, on one line, inside right-to-left text.\nconst CRON_EXAMPLE = \"⁦0 0 8 * * MON-FRI⁩\"\n\n// Roomier than a list's rows, since every row holds controls.\nconst TABLE_CLASSES =\n  \"[&_td]:px-4 [&_td]:py-3 [&_td]:align-top [&_th]:h-10 [&_th]:px-4\"\n\nconst FREQUENCY_ITEMS = FREQUENCIES.map((value) => ({\n  value,\n  label: FREQUENCY_LABELS[value],\n}))\n\nconst channels = (useDigest: boolean) => [\n  { value: \"EMAIL\", label: \"Email\" },\n  { value: \"SMS\", label: \"SMS\", disabled: useDigest },\n]\n\ntype ProfileNotificationSettingsProps = {\n  /** Every kind of notification that can be gathered into a digest; a skeleton shows until it is set. */\n  configurations: readonly DigestConfiguration[] | undefined\n  /** What the user chose so far; a skeleton shows until it is set. */\n  subscriptions: readonly DigestSubscription[] | undefined\n  /** Subscriptions belong to the contact details, so a user without them has none to set. */\n  hasContactDetails?: boolean\n  /** The settings could not be loaded; shows an error with Try Again. */\n  failed?: boolean\n  onRetry?: () => void\n  /** Called with every subscription when something changed; save them, then pass them back. */\n  onSubmit: (subscriptions: DigestSubscription[]) => void\n  pending?: boolean\n  /** Shown above the table, e.g. why the save failed. */\n  error?: ReactNode\n  /** The language weekdays are named in. */\n  locale?: string\n  /** Tells the page how many notifications have unsaved changes, e.g. to ask before leaving. */\n  onChangesChange?: (changes: number) => void\n  onCancel?: () => void\n  /** Places Cancel and Save Settings; by default they sit in a row under the table. */\n  renderActions?: (actions: ProfileFormActions) => ReactNode\n}\n\n/** How each notification reaches the user: its channel, and whether it is gathered into a scheduled digest. */\nexport function ProfileNotificationSettings({\n  configurations,\n  subscriptions,\n  hasContactDetails = true,\n  failed = false,\n  onRetry,\n  ...props\n}: ProfileNotificationSettingsProps) {\n  if (!hasContactDetails) {\n    return (\n      <DataTableCard>\n        <DataTableEmpty\n          description=\"Add your email address on the Basic Information tab to set up notifications.\"\n          icon={<MailXIcon />}\n          title=\"No Contact Details Yet\"\n        />\n      </DataTableCard>\n    )\n  }\n  if (failed) {\n    return (\n      <DataTableError\n        description=\"Your notification settings could not be loaded. Check your connection and try again.\"\n        onRetry={onRetry}\n        title=\"Could Not Load Notification Settings\"\n      />\n    )\n  }\n  if (!configurations || !subscriptions) {\n    return <ProfileNotificationSettingsSkeleton />\n  }\n  return (\n    <DigestForm\n      configurations={configurations}\n      subscriptions={subscriptions}\n      {...props}\n    />\n  )\n}\n\ntype DigestFormProps = Omit<\n  ProfileNotificationSettingsProps,\n  \"configurations\" | \"subscriptions\" | \"hasContactDetails\" | \"failed\"\n> & {\n  configurations: readonly DigestConfiguration[]\n  subscriptions: readonly DigestSubscription[]\n}\n\nfunction DigestForm({\n  configurations,\n  subscriptions,\n  onSubmit,\n  pending = false,\n  error,\n  locale = \"en-US\",\n  onChangesChange,\n  onCancel,\n  renderActions,\n}: DigestFormProps) {\n  const formId = useId()\n  const savedRows = useMemo(\n    () => toDigestRows(configurations, subscriptions),\n    [configurations, subscriptions]\n  )\n\n  const form = useAppForm({\n    defaultValues: { rows: savedRows },\n    // Quiet until the first submit, then each field re-checks as it is corrected.\n    validationLogic: revalidateLogic({\n      mode: \"submit\",\n      modeAfterSubmission: \"change\",\n    }),\n    validators: { onDynamic: digestFormSchema },\n    onSubmit: ({ value }) => onSubmit(toSubscriptions(value.rows)),\n    // A refused cell may be scrolled out of the table, so the first one takes focus.\n    onSubmitInvalid: () =>\n      requestAnimationFrame(() =>\n        document\n          .getElementById(formId)\n          ?.querySelector<HTMLElement>('[aria-invalid=\"true\"]')\n          ?.focus()\n      ),\n  })\n  const rows = useStore(form.store, (state) => state.values.rows)\n  const changes = countDigestChanges(savedRows, rows)\n\n  const savedSignature = JSON.stringify(savedRows)\n  const lastSaved = useRef(savedSignature)\n\n  // Equivalent rows must not replace a draft when a parent renders again.\n  useEffect(() => {\n    if (lastSaved.current === savedSignature) return\n    lastSaved.current = savedSignature\n    form.reset({ rows: savedRows })\n  }, [form, savedRows, savedSignature])\n  useEffect(() => {\n    onChangesChange?.(changes)\n  }, [changes, onChangesChange])\n\n  const weekdays = useMemo(() => {\n    const format = new Intl.DateTimeFormat(locale, { weekday: \"long\" })\n    // 7 January 2024 was a Sunday, day 0 in cron.\n    return WEEKDAYS.map((day) => ({\n      value: day,\n      label: format.format(new Date(2024, 0, 7 + Number(day))),\n    }))\n  }, [locale])\n\n  // Inline, so the fields keep the type the form infers.\n  const renderRow = (row: DigestRow, index: number) => {\n    const label = tagLabel(row.tag)\n    // Every row has the same controls, so each is named after its notification too.\n    const named = (control: string) => `${label} ${control}`\n\n    return (\n      <TableRow key={row.configurationId}>\n        <TableCell>\n          <span className=\"flex min-h-8 items-center font-medium whitespace-normal\">\n            {label}\n          </span>\n        </TableCell>\n        <TableCell>\n          <div className=\"min-w-28\">\n            <form.AppField name={`rows[${index}].channel`}>\n              {(field) => (\n                <field.SelectField\n                  items={channels(row.useDigest)}\n                  label={named(\"Channel\")}\n                  layout=\"inline\"\n                />\n              )}\n            </form.AppField>\n          </div>\n        </TableCell>\n        <TableCell>\n          <div className=\"flex min-h-8 items-center\">\n            <form.AppField\n              listeners={{\n                onChange: ({ value }) => {\n                  if (\n                    value &&\n                    form.getFieldValue(`rows[${index}].channel`) !== \"EMAIL\"\n                  )\n                    form.setFieldValue(`rows[${index}].channel`, \"EMAIL\")\n                },\n              }}\n              name={`rows[${index}].useDigest`}\n            >\n              {(field) => (\n                <field.SwitchField\n                  label={named(\"Use Digest\")}\n                  layout=\"inline\"\n                />\n              )}\n            </form.AppField>\n          </div>\n        </TableCell>\n        <TableCell>\n          {row.useDigest ? (\n            <div className=\"flex items-start gap-2 whitespace-normal\">\n              <div className=\"min-w-28\">\n                <form.AppField\n                  listeners={{\n                    onChange: ({ value }: { value: Frequency }) => {\n                      // A custom schedule starts from the simple one it replaces.\n                      if (\n                        value === \"custom\" &&\n                        row.schedule.frequency !== \"custom\"\n                      )\n                        form.setFieldValue(\n                          `rows[${index}].schedule.cron`,\n                          toCron(row.schedule)\n                        )\n                    },\n                  }}\n                  name={`rows[${index}].schedule.frequency`}\n                >\n                  {(field) => (\n                    <field.SelectField\n                      items={FREQUENCY_ITEMS}\n                      label={named(\"Frequency\")}\n                      layout=\"inline\"\n                    />\n                  )}\n                </form.AppField>\n              </div>\n              {row.schedule.frequency === \"weekly\" && (\n                <div className=\"min-w-36\">\n                  <form.AppField name={`rows[${index}].schedule.weekday`}>\n                    {(field) => (\n                      <field.SelectField\n                        items={weekdays}\n                        label={named(\"Day\")}\n                        layout=\"inline\"\n                      />\n                    )}\n                  </form.AppField>\n                </div>\n              )}\n              {row.schedule.frequency === \"custom\" ? (\n                <div className=\"w-44\">\n                  <form.AppField name={`rows[${index}].schedule.cron`}>\n                    {(field) => (\n                      <field.TextField\n                        autoComplete=\"off\"\n                        description={`Seconds, minutes, hours, day, month and weekday, e.g. ${CRON_EXAMPLE}.`}\n                        dir=\"ltr\"\n                        label={named(\"Cron Expression\")}\n                        layout=\"inline\"\n                        required\n                      />\n                    )}\n                  </form.AppField>\n                </div>\n              ) : (\n                <div className=\"w-32\">\n                  <form.AppField name={`rows[${index}].schedule.time`}>\n                    {(field) => (\n                      <field.TextField\n                        dir=\"ltr\"\n                        label={named(\"Time\")}\n                        layout=\"inline\"\n                        required\n                        type=\"time\"\n                      />\n                    )}\n                  </form.AppField>\n                </div>\n              )}\n            </div>\n          ) : (\n            <span className=\"flex min-h-8 items-center text-muted-foreground\">\n              -\n            </span>\n          )}\n        </TableCell>\n      </TableRow>\n    )\n  }\n\n  if (rows.length === 0) {\n    return (\n      <DataTableCard>\n        <DataTableEmpty\n          description=\"There are no notifications that can be gathered into a digest yet.\"\n          icon={<BellOffIcon />}\n          title=\"No Notifications To Set Up\"\n        />\n      </DataTableCard>\n    )\n  }\n\n  const actions: ProfileFormActions = {\n    formId,\n    changed: changes > 0,\n    pending,\n    cancel: () => {\n      form.reset({ rows: savedRows })\n      onCancel?.()\n    },\n  }\n\n  return (\n    <>\n      <form\n        className=\"flex flex-col gap-4\"\n        id={formId}\n        noValidate\n        onSubmit={(event) => {\n          event.preventDefault()\n          if (changes > 0) void form.handleSubmit()\n        }}\n      >\n        {error && (\n          <FormDialogError\n            description={error}\n            title=\"Could Not Save Notification Settings\"\n          />\n        )}\n        <DataTableCard>\n          <Table className={TABLE_CLASSES}>\n            <TableHeader>\n              <TableRow>\n                <TableHead>Notification</TableHead>\n                <TableHead>Channel</TableHead>\n                <TableHead>Use Digest</TableHead>\n                <TableHead>Schedule</TableHead>\n              </TableRow>\n            </TableHeader>\n            <TableBody>\n              {rows.map((row, index) => renderRow(row, index))}\n            </TableBody>\n          </Table>\n        </DataTableCard>\n        {rows.some((row) => row.useDigest) && (\n          <p className=\"text-sm text-muted-foreground\">\n            {rows.some(\n              (row) => row.useDigest && row.schedule.frequency === \"custom\"\n            )\n              ? `Digests are sent by email only. A custom schedule has six fields: seconds, minutes, hours, day, month and weekday, e.g. ${CRON_EXAMPLE}.`\n              : \"Digests are sent by email only.\"}\n          </p>\n        )}\n      </form>\n      {renderActions ? (\n        renderActions(actions)\n      ) : (\n        <div className=\"flex justify-end gap-2\">\n          <ProfileFormButtons actions={actions} saveLabel=\"Save Settings\" />\n        </div>\n      )}\n    </>\n  )\n}\n\nconst SKELETON_ROWS = [\"a\", \"b\", \"c\", \"d\"]\n\n/** The table while the settings load: its real columns, with placeholder rows of controls. */\nexport function ProfileNotificationSettingsSkeleton() {\n  return (\n    <div aria-busy>\n      <DataTableCard>\n        <Table className={TABLE_CLASSES}>\n          <TableHeader>\n            <TableRow>\n              <TableHead>Notification</TableHead>\n              <TableHead>Channel</TableHead>\n              <TableHead>Use Digest</TableHead>\n              <TableHead>Schedule</TableHead>\n            </TableRow>\n          </TableHeader>\n          <TableBody>\n            {SKELETON_ROWS.map((row) => (\n              <TableRow key={row}>\n                <TableCell>\n                  <span className=\"flex h-8 items-center\">\n                    <Skeleton className=\"h-3.5 w-48\" />\n                  </span>\n                </TableCell>\n                <TableCell>\n                  <Skeleton className=\"h-8 w-28\" />\n                </TableCell>\n                <TableCell>\n                  <span className=\"flex h-8 items-center\">\n                    {/* A plain element, since Skeleton owns its corner radius and a switch is round. */}\n                    <span className=\"h-4.5 w-8 animate-pulse rounded-full bg-muted\" />\n                  </span>\n                </TableCell>\n                <TableCell>\n                  <Skeleton className=\"h-8 w-32\" />\n                </TableCell>\n              </TableRow>\n            ))}\n          </TableBody>\n        </Table>\n      </DataTableCard>\n    </div>\n  )\n}",
      "type": "registry:component",
      "target": "components/openlmis/profile-page/profile-notification-settings.tsx"
    },
    {
      "path": "registry/templates/openlmis/profile-page/components/profile-page.tsx",
      "content": "\"use client\"\n\nimport { KeyRoundIcon, UserRoundIcon } from \"lucide-react\"\nimport { useMemo, useState } from \"react\"\nimport { createPortal } from \"react-dom\"\n\nimport { Badge } from \"@/components/ui/badge\"\nimport { Button } from \"@/components/ui/button\"\nimport { Tabs, TabsContent, TabsList, TabsTrigger } from \"@/components/ui/tabs\"\nimport { ChangePasswordDialog } from \"@/components/openlmis/profile-page/change-password-dialog\"\nimport { applySaved, profileChanges } from \"@/components/openlmis/profile-page/profile\"\nimport { ProfileBasicInformation } from \"@/components/openlmis/profile-page/profile-basic-information\"\nimport {\n  type FormActionState as ProfileFormActions,\n  FormActions as ProfileFormButtons,\n} from \"@/components/openlmis/form-actions\"\nimport { ProfileNotificationSettings } from \"@/components/openlmis/profile-page/profile-notification-settings\"\nimport {\n  assignmentKey,\n  byId,\n  countByType,\n  ROLE_TABS,\n  type RoleTab,\n  toRoleRows,\n} from \"@/components/blocks/openlmis/role-assignments/role-assignments\"\nimport { RoleAssignmentsTable } 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\"\nimport {\n  WorkspaceTabs,\n  WorkspaceTabsContent,\n  WorkspaceTabsList,\n  WorkspaceTabsTrigger,\n} from \"@/components/openlmis/workspace-tabs\"\n\nimport {\n  MOCK_ASSIGNMENTS,\n  MOCK_DIGEST_CONFIGURATIONS,\n  MOCK_FACILITIES,\n  MOCK_HOME_FACILITY_ID,\n  MOCK_NODES,\n  MOCK_PROFILE,\n  MOCK_PROGRAMS,\n  MOCK_ROLES,\n  MOCK_SUBSCRIPTIONS,\n} from \"@/components/openlmis/profile-page/mock-profile\"\n\nconst PROFILE_TABS = [\n  { value: \"basic\", label: \"Basic Information\" },\n  { value: \"roles\", label: \"Role Assignments\" },\n  { value: \"notifications\", label: \"Notification Settings\" },\n] as const\n\ntype ProfileTab = (typeof PROFILE_TABS)[number][\"value\"]\n\n/** Leaving the open tab, or signing out after a new password, both lose unsaved changes. */\ntype Leaving = { kind: \"tab\"; tab: ProfileTab } | { kind: \"sign-out\" }\n\ntype Notice = { title: string; description: string }\n\n/** The signed-in user's profile screen; mount it from any route, e.g. the `page.tsx` this template ships. */\nexport function ProfilePage() {\n  const [profile, setProfile] = useState(MOCK_PROFILE)\n  const [profileRevision, setProfileRevision] = useState(0)\n  const [subscriptions, setSubscriptions] = useState(MOCK_SUBSCRIPTIONS)\n  const [pendingEmail, setPendingEmail] = useState<string | null>(null)\n  const [tab, setTab] = useState<ProfileTab>(\"basic\")\n  const [changes, setChanges] = useState(0)\n  const [leaving, setLeaving] = useState<Leaving>()\n  const [passwordOpen, setPasswordOpen] = useState(false)\n  const [notice, setNotice] = useState<Notice>()\n  // The footer's buttons belong to the open tab's form, so the tab renders them into it.\n  const [footer, setFooter] = useState<HTMLDivElement | null>(null)\n  const { user } = profile\n\n  const openTab = (next: ProfileTab) => {\n    // Inactive tabs unmount, so switching throws the open form's changes away.\n    setChanges(0)\n    setNotice(undefined)\n    setTab(next)\n  }\n  const signOut = () => {\n    setProfileRevision((revision) => revision + 1)\n    setChanges(0)\n    setPasswordOpen(false)\n    setNotice({\n      title: \"Password Changed\",\n      description: \"Sign in with your new password.\",\n    })\n  }\n  const toFooter = (saveLabel: string) => (actions: ProfileFormActions) =>\n    footer &&\n    createPortal(\n      <ProfileFormButtons actions={actions} saveLabel={saveLabel} />,\n      footer\n    )\n\n  return (\n    <WorkspaceLayout>\n      <Workspace width=\"narrow\">\n        <PageBreadcrumbs\n          items={[{ label: \"Home\", href: \"#\" }, { label: \"Profile\" }]}\n        />\n        <WorkspaceHeader>\n          <WorkspaceHeading>\n            <WorkspaceIcon>\n              <UserRoundIcon />\n            </WorkspaceIcon>\n            <WorkspaceTitle>Profile</WorkspaceTitle>\n            <WorkspaceDescription>\n              Signed in as {user.username}.\n            </WorkspaceDescription>\n          </WorkspaceHeading>\n          <WorkspaceActions>\n            <Button\n              onClick={() => setPasswordOpen(true)}\n              size=\"lg\"\n              variant=\"outline\"\n            >\n              <KeyRoundIcon data-icon=\"inline-start\" />\n              Change Password\n            </Button>\n          </WorkspaceActions>\n        </WorkspaceHeader>\n        <WorkspaceContent>\n          {notice && (\n            <Callout title={notice.title} tone=\"success\">\n              {notice.description}\n            </Callout>\n          )}\n          <WorkspaceTabs\n            onValueChange={(value) => {\n              const next = value as ProfileTab\n              if (changes > 0) setLeaving({ kind: \"tab\", tab: next })\n              else openTab(next)\n            }}\n            value={tab}\n          >\n            <WorkspaceTabsList label=\"Profile Sections\">\n              {PROFILE_TABS.map((item) => (\n                <WorkspaceTabsTrigger key={item.value} value={item.value}>\n                  {item.label}\n                </WorkspaceTabsTrigger>\n              ))}\n            </WorkspaceTabsList>\n            <WorkspaceTabsContent value=\"basic\">\n              <ProfileBasicInformation\n                key={profileRevision}\n                onCancel={() => setNotice(undefined)}\n                onChangesChange={setChanges}\n                onResendEmail={() =>\n                  setNotice({\n                    title: \"Verification Link Sent\",\n                    description: `A new verification link is on its way to ${pendingEmail}.`,\n                  })\n                }\n                onSubmit={(values, current) => {\n                  const newEmail = profileChanges(current, values).email\n                    ? values.email.trim()\n                    : \"\"\n                  if (newEmail) setPendingEmail(newEmail)\n                  setProfile(applySaved(current, values))\n                  setProfileRevision((revision) => revision + 1)\n                  setNotice({\n                    title: \"Profile Saved\",\n                    description: newEmail\n                      ? `Open the link sent to ${newEmail} to start using it.`\n                      : \"Your profile is up to date.\",\n                  })\n                }}\n                pendingEmail={pendingEmail}\n                profile={profile}\n                renderActions={toFooter(\"Save Profile\")}\n              />\n            </WorkspaceTabsContent>\n            <WorkspaceTabsContent value=\"roles\">\n              <ProfileRoles />\n            </WorkspaceTabsContent>\n            <WorkspaceTabsContent value=\"notifications\">\n              <ProfileNotificationSettings\n                key={profileRevision}\n                onCancel={() => setNotice(undefined)}\n                configurations={MOCK_DIGEST_CONFIGURATIONS}\n                hasContactDetails={profile.contact !== null}\n                onChangesChange={setChanges}\n                onSubmit={(next) => {\n                  setSubscriptions(next)\n                  setNotice({\n                    title: \"Notification Settings Saved\",\n                    description:\n                      \"Your notifications will follow the new settings.\",\n                  })\n                }}\n                renderActions={toFooter(\"Save Settings\")}\n                subscriptions={subscriptions}\n              />\n            </WorkspaceTabsContent>\n          </WorkspaceTabs>\n        </WorkspaceContent>\n      </Workspace>\n      {tab !== \"roles\" && (\n        <WorkspaceFooter width=\"narrow\">\n          <div className=\"contents\" ref={setFooter} />\n        </WorkspaceFooter>\n      )}\n\n      <ChangePasswordDialog\n        onClose={() => setPasswordOpen(false)}\n        onSubmit={() => {\n          // A new password signs the user out, so unsaved changes on the page are asked about first.\n          if (changes > 0) setLeaving({ kind: \"sign-out\" })\n          else signOut()\n        }}\n        open={passwordOpen}\n        user={user}\n      />\n      <DiscardChangesDialog\n        changes={changes}\n        confirmLabel={\n          leaving?.kind === \"sign-out\" ? \"Discard and Sign Out\" : undefined\n        }\n        onDiscard={() => {\n          if (leaving?.kind === \"tab\") openTab(leaving.tab)\n          else signOut()\n          setLeaving(undefined)\n        }}\n        onKeepEditing={() => setLeaving(undefined)}\n        open={leaving !== undefined}\n        subject=\"your profile\"\n      />\n    </WorkspaceLayout>\n  )\n}\n\nconst ALL_READY = { nodes: \"ready\", facilities: \"ready\" } as const\n\n/** What the user may do, by role type, read only: an administrator assigns roles. */\nfunction ProfileRoles() {\n  const [roleTab, setRoleTab] = useState<RoleTab>(ROLE_TABS[0])\n  const lookups = useMemo(\n    () => ({\n      roles: byId(MOCK_ROLES),\n      programs: byId(MOCK_PROGRAMS),\n      nodes: byId(MOCK_NODES),\n      facilities: byId(MOCK_FACILITIES),\n    }),\n    []\n  )\n  const savedKeys = useMemo(\n    () => new Set(MOCK_ASSIGNMENTS.map(assignmentKey)),\n    []\n  )\n  const counts = useMemo(\n    () => countByType(MOCK_ASSIGNMENTS, lookups.roles),\n    [lookups.roles]\n  )\n  const rows = useMemo(\n    () =>\n      toRoleRows(MOCK_ASSIGNMENTS, roleTab.type, {\n        lookups,\n        savedKeys,\n        homeFacilityId: MOCK_HOME_FACILITY_ID,\n      }),\n    [roleTab.type, lookups, savedKeys]\n  )\n\n  return (\n    <Tabs\n      onValueChange={(value) =>\n        setRoleTab(ROLE_TABS.find((item) => item.id === value) ?? ROLE_TABS[0])\n      }\n      value={roleTab.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 === roleTab.id && (\n            <RoleAssignmentsTable\n              // Keyed, so each tab starts its own search, sort and paging.\n              key={item.id}\n              rows={rows}\n              status={ALL_READY}\n              tab={item}\n            />\n          )}\n        </TabsContent>\n      ))}\n    </Tabs>\n  )\n}",
      "type": "registry:component",
      "target": "components/openlmis/profile-page/profile-page.tsx"
    },
    {
      "path": "registry/templates/openlmis/profile-page/page.tsx",
      "content": "import { ProfilePage } from \"@/components/openlmis/profile-page/profile-page\"\n\n// A Next.js App Router route; in any other React app, render ProfilePage from your own route.\nexport default function Page() {\n  return <ProfilePage />\n}",
      "type": "registry:page",
      "target": "app/profile-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": "737px"
  },
  "categories": [
    "profile"
  ],
  "type": "registry:page"
}
