528 lines
22 KiB
TypeScript
528 lines
22 KiB
TypeScript
import { useState, useMemo } from "react";
|
|
import { Link } from "react-router-dom";
|
|
import { useTranslation } from "react-i18next";
|
|
import * as VisuallyHidden from "@radix-ui/react-visually-hidden";
|
|
import { Pencil, CheckCircle2, UserRound, X, Shield, KeyRound, Building2 } from "lucide-react";
|
|
import { Button } from "@/components/ui/button";
|
|
import { Skeleton } from "@/components/ui/skeleton";
|
|
import {
|
|
AlertDialog,
|
|
AlertDialogContent,
|
|
AlertDialogDescription,
|
|
AlertDialogFooter,
|
|
AlertDialogHeader,
|
|
AlertDialogTitle,
|
|
} from "@/components/ui/alert-dialog";
|
|
import { BentoGrid, BentoCard, InfoRow } from "@/components/viewPageComponents";
|
|
import { FormInput } from "@/components/formInput";
|
|
import { AvatarUpload } from "@/components/avatarUpload";
|
|
import { FormActions } from "@/components/formActions";
|
|
import { InfiniteSelect, type InfiniteSelectOption } from "@/components/infiniteSelect";
|
|
import { useAuthStore } from "@/app/store/authStore";
|
|
import { useProfile, useUpdateProfile } from "@/features/auth/hooks/useLogin";
|
|
import { useInfiniteRoles } from "@/features/roles/hooks/useRoles";
|
|
import { useInfinitePermissions } from "@/features/permissions/hooks/usePermissions";
|
|
import { useInfiniteBranches } from "@/features/shared/hooks/useSharedBranchUsers";
|
|
import { useInfiniteStaff } from "@/features/operators/hooks/useOperators";
|
|
import { useAssignRoleToUser, useAssignPermissionToRole, useAssignBranchToUser } from "@/features/shared/hooks/useSharedUserAssignments";
|
|
import type { LocalizedText } from "@/features/branches/api/branchesApi";
|
|
import { formatFromApiDate } from "@/lib/utils/dateUtils";
|
|
type AssignDialogKind = "role" | "permission" | "branch";
|
|
|
|
export default function ProfilePage() {
|
|
const { t, i18n } = useTranslation();
|
|
const { data: profileQueryData, isLoading } = useProfile();
|
|
const authUser = useAuthStore((s) => s.user);
|
|
const user = profileQueryData ?? authUser;
|
|
|
|
const updateProfileMutation = useUpdateProfile();
|
|
|
|
const [isEditing, setIsEditing] = useState(false);
|
|
const [assignDialog, setAssignDialog] = useState<AssignDialogKind | null>(null);
|
|
|
|
const lang = (i18n.language === "ru" ? "ru" : i18n.language === "en" ? "en" : "tm") as keyof LocalizedText;
|
|
|
|
const branches = user?.branches ?? [];
|
|
const permissions = user?.permissions ?? [];
|
|
const isAdmin = authUser?.role?.code === "admin";
|
|
|
|
// ── Form State for Editing ──
|
|
const [formData, setFormData] = useState({
|
|
name: "",
|
|
firstName: "",
|
|
lastName: "",
|
|
phone: "",
|
|
avatar: "",
|
|
});
|
|
|
|
const [errors, setErrors] = useState<Record<string, string>>({});
|
|
|
|
const startEditing = () => {
|
|
if (!user) return;
|
|
setFormData({
|
|
name: user.name ?? "",
|
|
firstName: user.firstName ?? "",
|
|
lastName: user.lastName ?? "",
|
|
phone: user.phone ?? "",
|
|
avatar: user.avatar ?? "",
|
|
});
|
|
setErrors({});
|
|
setIsEditing(true);
|
|
};
|
|
|
|
const handleFieldChange = (field: keyof typeof formData, value: string) => {
|
|
setFormData((prev) => ({ ...prev, [field]: value }));
|
|
if (errors[field]) {
|
|
setErrors((prev) => {
|
|
const next = { ...prev };
|
|
delete next[field];
|
|
return next;
|
|
});
|
|
}
|
|
};
|
|
|
|
const handleSave = async () => {
|
|
if (!formData.name.trim()) {
|
|
setErrors({ name: t("common.errors.required", "Meýdança hökmany doldurylmaly") });
|
|
return;
|
|
}
|
|
|
|
try {
|
|
await updateProfileMutation.mutateAsync({
|
|
name: formData.name.trim(),
|
|
firstName: formData.firstName.trim() || undefined,
|
|
lastName: formData.lastName.trim() || undefined,
|
|
phone: formData.phone.trim() || undefined,
|
|
avatar: formData.avatar || undefined,
|
|
});
|
|
setIsEditing(false);
|
|
} catch {
|
|
// Error is handled in useUpdateProfile onError toast
|
|
}
|
|
};
|
|
|
|
// ── Loading state ──
|
|
if (isLoading && !user) {
|
|
return (
|
|
<div className="p-6 space-y-4">
|
|
<Skeleton className="h-7 w-64" />
|
|
<div className="bg-card border border-border rounded-xl overflow-hidden p-6 space-y-4">
|
|
{Array.from({ length: 5 }).map((_, i) => (
|
|
<div key={i} className="grid grid-cols-[220px_1fr] items-center py-2.5 px-4 border-b border-border last:border-0">
|
|
<Skeleton className="h-4 w-24" />
|
|
<Skeleton className="h-4 w-40" />
|
|
</div>
|
|
))}
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
if (!user) {
|
|
return null;
|
|
}
|
|
|
|
return (
|
|
<div className="space-y-6">
|
|
{/* ── Profile hero ─────────────────────────────────────────────────── */}
|
|
{!isEditing ? (
|
|
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 bg-card border border-border rounded-xl p-5">
|
|
<div className="flex items-center gap-4 min-w-0">
|
|
{user.avatar ? (
|
|
<img
|
|
src={user.avatar}
|
|
alt="avatar"
|
|
className="w-16 h-16 rounded-full border border-border bg-muted/40 object-cover shrink-0 shadow-sm"
|
|
/>
|
|
) : (
|
|
<div className="w-16 h-16 rounded-full border border-border bg-muted/40 flex items-center justify-center shrink-0 shadow-sm">
|
|
<UserRound size={28} className="text-muted-foreground/60" />
|
|
</div>
|
|
)}
|
|
<div className="min-w-0">
|
|
<div className="flex items-center gap-2 flex-wrap">
|
|
<h1 className="text-lg font-bold text-foreground truncate">
|
|
{[user.firstName, user.lastName].filter(Boolean).join(" ") || user.name}
|
|
</h1>
|
|
<span className="inline-flex items-center gap-1 text-xs font-medium text-emerald-600 bg-emerald-500/10 px-2 py-0.5 rounded-full shrink-0">
|
|
<CheckCircle2 size={12} />
|
|
{t("common.active", "Işjeň")}
|
|
</span>
|
|
</div>
|
|
<p className="text-sm text-muted-foreground mt-0.5 truncate">
|
|
@{user.name}
|
|
{user.phone ? ` · ${user.phone}` : ""}
|
|
</p>
|
|
</div>
|
|
</div>
|
|
<Button variant="outline" size="sm" className="gap-2 shrink-0" onClick={startEditing}>
|
|
<Pencil size={15} />
|
|
{t("common.edit", "Üýtgetmek")}
|
|
</Button>
|
|
</div>
|
|
) : (
|
|
<div className="flex items-center justify-between">
|
|
<h1 className="text-xl font-bold text-foreground leading-tight">{t("profile.editTitle", "Profili üýtgetmek")}</h1>
|
|
<Button
|
|
variant="ghost"
|
|
size="sm"
|
|
className="gap-2 text-muted-foreground hover:text-foreground"
|
|
onClick={() => setIsEditing(false)}
|
|
disabled={updateProfileMutation.isPending}
|
|
>
|
|
<X size={15} />
|
|
{t("common.cancel", "Yza")}
|
|
</Button>
|
|
</div>
|
|
)}
|
|
|
|
{/* ── Main content ─────────────────────────────────────────────────── */}
|
|
{!isEditing ? (
|
|
<>
|
|
<BentoGrid cols={2}>
|
|
<BentoCard title={t("profile.sections.account", "Hasap maglumatlary")}>
|
|
<InfoRow label={t("common.id", "ID")} value={user.id} />
|
|
<InfoRow label={t("users.fields.username", "Ulanyjy ady")} value={user.name} />
|
|
<InfoRow label={t("users.fields.createdAt", "Döredilen wagty")} value={formatFromApiDate(user.createdAt) || "—"} />
|
|
{user.email && <InfoRow label={t("users.fields.email", "E-poçta")} value={user.email} />}
|
|
</BentoCard>
|
|
|
|
<BentoCard title={t("profile.sections.contact", "Habarlaşmak maglumatlary")}>
|
|
<InfoRow label={t("users.fields.firstName", "At ady")} value={user.firstName ?? "—"} />
|
|
<InfoRow label={t("users.fields.lastName", "Familiýasy")} value={user.lastName ?? "—"} />
|
|
<InfoRow label={t("users.fields.phone", "Telefon belgisi")} value={user.phone ?? "—"} />
|
|
</BentoCard>
|
|
</BentoGrid>
|
|
|
|
<BentoGrid cols={2}>
|
|
<BentoCard title={t("profile.sections.org", "Guramaçylyk maglumatlary")}>
|
|
<InfoRow label={t("users.fields.role", "Roly")}>
|
|
{user.role ? (
|
|
<Link
|
|
to={`/settings/users/roles/${user.role.id}`}
|
|
className="inline-flex items-center gap-1 text-xs border border-border rounded-md px-2 py-1 hover:bg-muted transition-colors"
|
|
>
|
|
<Shield size={12} />
|
|
{user.role.name}
|
|
</Link>
|
|
) : (
|
|
<span className="text-sm text-muted-foreground">—</span>
|
|
)}
|
|
</InfoRow>
|
|
|
|
<InfoRow label={t("users.sections.branches", "Şahamçalar")}>
|
|
{branches.length > 0 ? (
|
|
<div className="flex flex-wrap gap-1.5">
|
|
{branches.map((b) => (
|
|
<Link
|
|
key={b.id}
|
|
to={`/settings/location/branches/${b.id}`}
|
|
className="inline-flex items-center gap-1 text-xs border border-border rounded-md px-2 py-1 hover:bg-muted transition-colors"
|
|
>
|
|
<Building2 size={11} className="text-muted-foreground" />
|
|
<span className="text-foreground font-medium">
|
|
{b.name?.[lang] || b.name?.tm || b.name?.en || b.name?.ru || b.uniqueCode || b.id}
|
|
</span>
|
|
</Link>
|
|
))}
|
|
</div>
|
|
) : (
|
|
<span className="text-sm text-muted-foreground">—</span>
|
|
)}
|
|
</InfoRow>
|
|
|
|
<InfoRow label={t("users.sections.permissions", "Rugsatlar")}>
|
|
{permissions.length > 0 ? (
|
|
<div className="flex flex-wrap gap-1.5">
|
|
{permissions.map((p) => (
|
|
<Link
|
|
key={p.id}
|
|
to={`/settings/users/permissions/${p.id}`}
|
|
className="inline-flex items-center gap-1 text-xs border border-border rounded-md px-2 py-1 hover:bg-muted transition-colors"
|
|
>
|
|
<KeyRound size={11} className="text-muted-foreground" />
|
|
<span className="text-foreground font-medium">{p.name || p.code || p.id}</span>
|
|
</Link>
|
|
))}
|
|
</div>
|
|
) : (
|
|
<span className="text-sm text-muted-foreground">—</span>
|
|
)}
|
|
</InfoRow>
|
|
</BentoCard>
|
|
|
|
{isAdmin && (
|
|
<BentoCard title={t("profile.sections.actions", "Amallar")}>
|
|
<div className="flex flex-wrap gap-2 px-4 py-3">
|
|
<Button variant="outline" size="sm" className="gap-1.5" onClick={() => setAssignDialog("role")}>
|
|
<Shield size={14} />
|
|
{t("profile.actions.assignRole", "Rol birikdiriň")}
|
|
</Button>
|
|
<Button variant="outline" size="sm" className="gap-1.5" onClick={() => setAssignDialog("permission")}>
|
|
<KeyRound size={14} />
|
|
{t("profile.actions.assignPermission", "Rugsat birikdiriň")}
|
|
</Button>
|
|
<Button variant="outline" size="sm" className="gap-1.5" onClick={() => setAssignDialog("branch")}>
|
|
<Building2 size={14} />
|
|
{t("profile.actions.assignBranch", "Şahamça birikdiriň")}
|
|
</Button>
|
|
</div>
|
|
</BentoCard>
|
|
)}
|
|
</BentoGrid>
|
|
</>
|
|
) : (
|
|
<div className="w-full">
|
|
<BentoCard title={t("profile.editTitle", "Profili üýtgetmek")}>
|
|
<div className="space-y-4 p-2">
|
|
<AvatarUpload
|
|
label={t("users.fields.avatar", "Awatar")}
|
|
value={formData.avatar}
|
|
onChange={(url) => handleFieldChange("avatar", url)}
|
|
disabled={updateProfileMutation.isPending}
|
|
/>
|
|
|
|
<FormInput
|
|
type="text"
|
|
label={t("users.fields.name", "Ulanyjy ady")}
|
|
value={formData.name}
|
|
onChange={(v) => handleFieldChange("name", v)}
|
|
error={errors.name}
|
|
required
|
|
disabled={updateProfileMutation.isPending}
|
|
/>
|
|
|
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
|
<FormInput
|
|
type="text"
|
|
label={t("users.fields.firstName", "At ady")}
|
|
value={formData.firstName}
|
|
onChange={(v) => handleFieldChange("firstName", v)}
|
|
disabled={updateProfileMutation.isPending}
|
|
/>
|
|
|
|
<FormInput
|
|
type="text"
|
|
label={t("users.fields.lastName", "Familiýasy")}
|
|
value={formData.lastName}
|
|
onChange={(v) => handleFieldChange("lastName", v)}
|
|
disabled={updateProfileMutation.isPending}
|
|
/>
|
|
</div>
|
|
|
|
<FormInput
|
|
type="text"
|
|
label={t("users.fields.phone", "Telefon belgisi")}
|
|
value={formData.phone}
|
|
onChange={(v) => handleFieldChange("phone", v)}
|
|
disabled={updateProfileMutation.isPending}
|
|
/>
|
|
|
|
<div className="pt-4 border-t border-border">
|
|
<FormActions
|
|
onSubmit={handleSave}
|
|
onCancel={() => setIsEditing(false)}
|
|
isPending={updateProfileMutation.isPending}
|
|
submitLabel={t("common.save", "Ýatda sakla")}
|
|
/>
|
|
</div>
|
|
</div>
|
|
</BentoCard>
|
|
</div>
|
|
)}
|
|
|
|
{/* ── Assign dialog (staff user + role/permission/branch) ─────────────── */}
|
|
{assignDialog && <AssignDialog kind={assignDialog} onClose={() => setAssignDialog(null)} />}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
// ─── Assign dialog ────────────────────────────────────────────────────────────
|
|
|
|
const ASSIGN_DIALOG_TITLES: Record<AssignDialogKind, string> = {
|
|
role: "profile.actions.assignRole",
|
|
permission: "profile.actions.assignPermission",
|
|
branch: "profile.actions.assignBranch",
|
|
};
|
|
|
|
const ASSIGN_DIALOG_FIELD_LABELS: Record<AssignDialogKind, string> = {
|
|
role: "users.fields.role",
|
|
permission: "users.sections.permissions",
|
|
branch: "users.sections.branches",
|
|
};
|
|
|
|
/**
|
|
* Dialog for assigning a role / branch to a staff user, or assigning a permission to a role.
|
|
*/
|
|
function AssignDialog({ kind, onClose }: { kind: AssignDialogKind; onClose: () => void }) {
|
|
const { t, i18n } = useTranslation();
|
|
const lang = (i18n.language === "ru" ? "ru" : i18n.language === "en" ? "en" : "tm") as keyof LocalizedText;
|
|
|
|
const isPermission = kind === "permission";
|
|
|
|
const [targetSearch, setTargetSearch] = useState("");
|
|
const [targetValue, setTargetValue] = useState("");
|
|
const [resourceSearch, setResourceSearch] = useState("");
|
|
const [resourceValue, setResourceValue] = useState("");
|
|
const [error, setError] = useState<string | undefined>();
|
|
|
|
// Target query: Staff users when assigning role/branch to a user; Roles when assigning permission to a role.
|
|
const staffQuery = useInfiniteStaff(targetSearch);
|
|
const targetRolesQuery = useInfiniteRoles(targetSearch, isPermission);
|
|
|
|
// Resource query:
|
|
const rolesQuery = useInfiniteRoles(resourceSearch, kind === "role");
|
|
const permissionsQuery = useInfinitePermissions(resourceSearch, kind === "permission");
|
|
const branchesQuery = useInfiniteBranches(resourceSearch, kind === "branch");
|
|
|
|
const roleMutation = useAssignRoleToUser();
|
|
const permissionMutation = useAssignPermissionToRole();
|
|
const branchMutation = useAssignBranchToUser();
|
|
const isPending = roleMutation.isPending || permissionMutation.isPending || branchMutation.isPending;
|
|
|
|
const staffOptions: InfiniteSelectOption[] = useMemo(
|
|
() =>
|
|
(staffQuery.data?.pages ?? [])
|
|
.flatMap((p) => p?.users ?? [])
|
|
.map((u) => ({
|
|
value: String(u.id),
|
|
label: [u.firstName, u.lastName].filter(Boolean).join(" ") || u.name || u.username || String(u.id),
|
|
})),
|
|
[staffQuery.data],
|
|
);
|
|
|
|
const targetRoleOptions: InfiniteSelectOption[] = useMemo(
|
|
() =>
|
|
(targetRolesQuery.data?.pages ?? [])
|
|
.flatMap((p) => p?.roles ?? [])
|
|
.map((r) => ({ value: String(r.id), label: r.name || r.code || String(r.id) })),
|
|
[targetRolesQuery.data],
|
|
);
|
|
|
|
const targetOptions = isPermission ? targetRoleOptions : staffOptions;
|
|
const targetLabel = isPermission ? t("users.fields.role", "Rol") : t("profile.assign.userLabel", "Ulanyjy (staff)");
|
|
const targetLoading = isPermission ? targetRolesQuery.isLoading : staffQuery.isLoading;
|
|
const targetLoadingMore = isPermission ? targetRolesQuery.isFetchingNextPage : staffQuery.isFetchingNextPage;
|
|
const targetHasNextPage = isPermission ? !!targetRolesQuery.hasNextPage : !!staffQuery.hasNextPage;
|
|
const loadMoreTargets = () => {
|
|
if (isPermission) targetRolesQuery.fetchNextPage();
|
|
else staffQuery.fetchNextPage();
|
|
};
|
|
|
|
const resourceOptions: InfiniteSelectOption[] = useMemo(() => {
|
|
if (kind === "role") {
|
|
return (rolesQuery.data?.pages ?? [])
|
|
.flatMap((p) => p?.roles ?? [])
|
|
.map((r) => ({ value: String(r.id), label: r.name || r.code || String(r.id) }));
|
|
}
|
|
if (kind === "permission") {
|
|
return (permissionsQuery.data?.pages ?? [])
|
|
.flatMap((p) => p?.permissions ?? [])
|
|
.map((perm) => ({ value: String(perm.id), label: perm.name || perm.code || String(perm.id) }));
|
|
}
|
|
return (branchesQuery.data?.pages ?? [])
|
|
.flatMap((p) => p?.branches ?? [])
|
|
.map((b) => ({
|
|
value: String(b.id),
|
|
label: b.name?.[lang] || b.name?.tm || b.name?.en || b.name?.ru || b.uniqueCode || String(b.id),
|
|
}));
|
|
}, [kind, rolesQuery.data, permissionsQuery.data, branchesQuery.data, lang]);
|
|
|
|
const resourceLoading =
|
|
kind === "role" ? rolesQuery.isLoading : kind === "permission" ? permissionsQuery.isLoading : branchesQuery.isLoading;
|
|
const resourceLoadingMore =
|
|
kind === "role"
|
|
? rolesQuery.isFetchingNextPage
|
|
: kind === "permission"
|
|
? permissionsQuery.isFetchingNextPage
|
|
: branchesQuery.isFetchingNextPage;
|
|
const resourceHasNextPage =
|
|
kind === "role" ? !!rolesQuery.hasNextPage : kind === "permission" ? !!permissionsQuery.hasNextPage : !!branchesQuery.hasNextPage;
|
|
const loadMoreResources = () => {
|
|
if (kind === "role") rolesQuery.fetchNextPage();
|
|
else if (kind === "permission") permissionsQuery.fetchNextPage();
|
|
else branchesQuery.fetchNextPage();
|
|
};
|
|
|
|
const handleSubmit = () => {
|
|
if (!targetValue || !resourceValue) {
|
|
setError(t("common.errors.required", "Meýdança hökmany doldurylmaly"));
|
|
return;
|
|
}
|
|
setError(undefined);
|
|
|
|
const firstId = Number(targetValue);
|
|
const secondId = Number(resourceValue);
|
|
const onSuccess = () => {
|
|
setTargetValue("");
|
|
setResourceValue("");
|
|
onClose();
|
|
};
|
|
|
|
if (kind === "role") roleMutation.mutate({ userId: firstId, roleId: secondId }, { onSuccess });
|
|
else if (kind === "permission") permissionMutation.mutate({ roleId: firstId, permissionId: secondId }, { onSuccess });
|
|
else branchMutation.mutate({ userId: firstId, branchId: secondId }, { onSuccess });
|
|
};
|
|
|
|
return (
|
|
<AlertDialog open onOpenChange={(open) => !open && onClose()}>
|
|
<AlertDialogContent className="max-w-md sm:max-w-md">
|
|
<AlertDialogHeader>
|
|
<AlertDialogTitle>{t(ASSIGN_DIALOG_TITLES[kind])}</AlertDialogTitle>
|
|
<VisuallyHidden.Root>
|
|
<AlertDialogDescription>{t(ASSIGN_DIALOG_TITLES[kind])}</AlertDialogDescription>
|
|
</VisuallyHidden.Root>
|
|
</AlertDialogHeader>
|
|
|
|
<div className="space-y-3">
|
|
<InfiniteSelect
|
|
required
|
|
label={targetLabel}
|
|
value={targetValue}
|
|
onChange={(v) => {
|
|
setTargetValue(v);
|
|
if (error) setError(undefined);
|
|
}}
|
|
options={targetOptions}
|
|
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
|
|
loading={targetLoading}
|
|
isLoadingMore={targetLoadingMore}
|
|
hasNextPage={targetHasNextPage}
|
|
onLoadMore={loadMoreTargets}
|
|
searchValue={targetSearch}
|
|
onSearchChange={setTargetSearch}
|
|
/>
|
|
|
|
<InfiniteSelect
|
|
required
|
|
label={t(ASSIGN_DIALOG_FIELD_LABELS[kind])}
|
|
value={resourceValue}
|
|
onChange={(v) => {
|
|
setResourceValue(v);
|
|
if (error) setError(undefined);
|
|
}}
|
|
error={error}
|
|
options={resourceOptions}
|
|
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
|
|
loading={resourceLoading}
|
|
isLoadingMore={resourceLoadingMore}
|
|
hasNextPage={resourceHasNextPage}
|
|
onLoadMore={loadMoreResources}
|
|
searchValue={resourceSearch}
|
|
onSearchChange={setResourceSearch}
|
|
/>
|
|
</div>
|
|
|
|
<AlertDialogFooter>
|
|
<Button variant="ghost" size="sm" onClick={onClose} disabled={isPending}>
|
|
{t("common.cancel", "Yza")}
|
|
</Button>
|
|
<Button size="sm" onClick={handleSubmit} disabled={!targetValue || !resourceValue || isPending}>
|
|
{t("common.save", "Ýatda sakla")}
|
|
</Button>
|
|
</AlertDialogFooter>
|
|
</AlertDialogContent>
|
|
</AlertDialog>
|
|
);
|
|
}
|