connect users section api, fixed some ui, added some lang support to missed words

This commit is contained in:
Jelaletdin12
2026-08-18 21:41:13 +05:00
parent 0e75c85fe1
commit 7bb37f9b43
24 changed files with 1871 additions and 1543 deletions

View File

@@ -8,6 +8,7 @@ import { InfiniteSelect, type InfiniteSelectOption, type InfiniteSelectProps } f
import { Checkbox } from "@/components/ui/checkbox";
import { Label } from "@/components/ui/label";
import { FormActions } from "@/components/formActions";
import { AvatarUpload } from "@/components/avatarUpload";
import { BentoGrid, BentoCard } from "@/components/bento";
import { useCreateUser, useUpdateUser } from "../hooks/useAllUsers";
import { useInfiniteRoles } from "@/features/roles/hooks/useRoles";
@@ -59,7 +60,7 @@ export function UserForm({ mode, initialData }: UserFormProps) {
const roleSelect: Omit<InfiniteSelectProps, "label" | "required" | "placeholder"> = useMemo(() => {
const opts: InfiniteSelectOption[] = (roleQuery.data?.pages ?? [])
.flatMap((p) => p.roles)
.map((r) => ({ value: r.name, label: r.name }));
.map((r) => ({ value: r.code, label: r.name }));
// Ensure the currently-selected role is present (edit mode), even if it
// lives beyond the pages loaded so far.
@@ -150,123 +151,115 @@ export function UserForm({ mode, initialData }: UserFormProps) {
<h1 className="text-xl font-semibold text-foreground">
{mode === "create" ? t("users.createTitle", "Ulanyjy dörediň") : t("users.editTitle", "Ulanyjy üýtgetmek")}
</h1>
<BentoGrid cols={2}>
<BentoCard>
<FormInput
type="text"
label={t("users.fields.username", "Ulanyjy ady")}
value={form.username}
onChange={(v) => setField("username", v)}
placeholder={t("users.fields.username", "Ulanyjy ady")}
error={errors.username}
disabled={isPending}
required
/>
<p className="text-xs text-muted-foreground -mt-3">{t("users.fields.usernameHint", "Unikal login ady")}</p>
{/* ── Identity ── */}
<BentoCard title={t("users.sections.identity", "Şahsy maglumat")}>
<div className="grid grid-cols-2 gap-3">
<FormInput
type="text"
label={t("users.fields.username", "Ulanyjy ady")}
value={form.username}
onChange={(v) => setField("username", v)}
placeholder={t("users.fields.username", "Ulanyjy ady")}
error={errors.username}
disabled={isPending}
required
/>
<FormInput
type="text"
label={t("users.fields.name", "Ady")}
value={form.name}
onChange={(v) => setField("name", v)}
placeholder={t("users.fields.name", "Ady")}
error={errors.name}
disabled={isPending}
required
/>
<FormInput
type="text"
label={t("users.fields.firstName", "Ady (at)")}
value={form.firstName}
onChange={(v) => setField("firstName", v)}
placeholder={t("users.fields.firstName", "Ady (at)")}
error={errors.firstName}
disabled={isPending}
/>
<FormInput
type="text"
label={t("users.fields.lastName", "Familiýasy")}
value={form.lastName}
onChange={(v) => setField("lastName", v)}
placeholder={t("users.fields.lastName", "Familiýasy")}
error={errors.lastName}
disabled={isPending}
/>
</div>
<div className="grid grid-cols-2 gap-3">
<FormInput
type="phone"
label={t("users.fields.phone", "Telefon")}
value={form.phone}
onChange={(v) => setField("phone", v)}
placeholder="62-38-49-56"
error={errors.phone}
disabled={isPending}
required
/>
<FormInput
type="email"
label={t("users.fields.email", "E-poçta")}
value={form.email}
onChange={(v) => setField("email", v)}
placeholder={t("users.fields.email", "E-poçta")}
error={errors.email}
disabled={isPending}
/>
<InfiniteSelect
label={t("users.fields.role", "Roly")}
value={form.role}
onChange={(v) => setField("role", v)}
placeholder={t("users.fields.role", "Roly")}
error={errors.role}
disabled={isPending}
required
{...roleSelect}
/>
{mode === "create" && (
<FormInput
type="password"
label={t("users.fields.password", "Açar sözi")}
value={form.password}
onChange={(v) => setField("password", v)}
placeholder={t("users.fields.password", "Açar sözi")}
error={errors.password}
disabled={isPending}
required
/>
)}
<div className="flex items-center gap-2 pt-1">
<Checkbox id="active" checked={form.active} onCheckedChange={(v) => setField("active", !!v)} disabled={isPending} />
<Label htmlFor="active" className="text-sm text-muted-foreground cursor-pointer">
{form.active ? t("common.active", "Işjeň") : t("common.inactive", "Işjeň däl")}
</Label>
</div>
</div>
</BentoCard>
{/* ── Avatar ── */}
<BentoCard>
<FormInput
type="text"
label={t("users.fields.name", "Ady")}
value={form.name}
onChange={(v) => setField("name", v)}
placeholder={t("users.fields.name", "Ady")}
error={errors.name}
disabled={isPending}
required
/>
<p className="text-xs text-muted-foreground -mt-3">{t("users.fields.nameHint", "Doly ady we familiýasy")}</p>
</BentoCard>
<BentoCard>
<FormInput
type="text"
label={t("users.fields.firstName", "Ady (at)")}
value={form.firstName}
onChange={(v) => setField("firstName", v)}
placeholder={t("users.fields.firstName", "Ady (at)")}
error={errors.firstName}
disabled={isPending}
/>
</BentoCard>
<BentoCard>
<FormInput
type="text"
label={t("users.fields.lastName", "Familiýasy")}
value={form.lastName}
onChange={(v) => setField("lastName", v)}
placeholder={t("users.fields.lastName", "Familiýasy")}
error={errors.lastName}
disabled={isPending}
/>
</BentoCard>
<BentoCard>
<FormInput
type="phone"
label={t("users.fields.phone", "Telefon")}
value={form.phone}
onChange={(v) => setField("phone", v)}
placeholder="62-38-49-56"
error={errors.phone}
disabled={isPending}
required
/>
<p className="text-xs text-muted-foreground -mt-3">{t("users.fields.phoneHint", "+993 bilen başlanýar")}</p>
</BentoCard>
<BentoCard>
<FormInput
type="email"
label={t("users.fields.email", "E-poçta")}
value={form.email}
onChange={(v) => setField("email", v)}
placeholder={t("users.fields.email", "E-poçta")}
error={errors.email}
disabled={isPending}
/>
<p className="text-xs text-muted-foreground -mt-3">{t("users.fields.emailHint", "Islege görä")}</p>
</BentoCard>
<BentoCard>
<InfiniteSelect
label={t("users.fields.role", "Roly")}
value={form.role}
onChange={(v) => setField("role", v)}
placeholder={t("users.fields.role", "Roly")}
error={errors.role}
disabled={isPending}
required
{...roleSelect}
/>
</BentoCard>
<BentoCard>
<FormInput
type="text"
label={t("users.fields.avatar", "Awatar URL")}
<AvatarUpload
label={t("users.fields.avatar", "Awatar")}
value={form.avatar}
onChange={(v) => setField("avatar", v)}
placeholder="https://..."
error={errors.avatar}
disabled={isPending}
/>
</BentoCard>
{mode === "create" && (
<BentoCard>
<FormInput
type="password"
label={t("users.fields.password", "Açar sözi")}
value={form.password}
onChange={(v) => setField("password", v)}
placeholder={t("users.fields.password", "Açar sözi")}
error={errors.password}
disabled={isPending}
required
/>
<p className="text-xs text-muted-foreground -mt-3">{t("users.fields.passwordHint", "Iň az 6 harp")}</p>
</BentoCard>
)}
<BentoCard>
<div className="space-y-1">
<p className="text-sm font-semibold text-muted-foreground">{t("users.fields.socialMedia", "Sosial media")}</p>
</div>
<div className="flex flex-col gap-3">
{/* ── Social media ── */}
<BentoCard title={t("users.fields.socialMedia", "Sosial media")} span="full">
<div className="grid grid-cols-3 gap-3">
<FormInput
type="text"
label={t("users.fields.facebook", "Facebook")}
@@ -296,30 +289,8 @@ export function UserForm({ mode, initialData }: UserFormProps) {
/>
</div>
</BentoCard>
<BentoCard>
<div className="space-y-1">
<p className="text-sm font-semibold text-muted-foreground">{t("users.fields.lightMode", "Light režimi")}</p>
</div>
<div className="flex items-center gap-2">
<Checkbox id="lightMode" checked={form.lightMode} onCheckedChange={(v) => setField("lightMode", !!v)} disabled={isPending} />
<Label htmlFor="lightMode" className="text-sm text-muted-foreground cursor-pointer">
{form.lightMode ? t("common.yes", "Hawa") : t("common.no", "Ýok")}
</Label>
</div>
</BentoCard>
<BentoCard>
<div className="space-y-1">
<p className="text-sm font-semibold text-muted-foreground">{t("users.fields.isActive", "Işjeň")}</p>
<p className="text-xs text-muted-foreground">{t("users.fields.isActiveHint", "Ulanyjynyň ulgama girip-bilmezligi")}</p>
</div>
<div className="flex items-center gap-2">
<Checkbox id="active" checked={form.active} onCheckedChange={(v) => setField("active", !!v)} disabled={isPending} />
<Label htmlFor="active" className="text-sm text-muted-foreground cursor-pointer">
{form.active ? t("common.active", "Işjeň") : t("common.inactive", "Işjeň däl")}
</Label>
</div>
</BentoCard>
</BentoGrid>
<FormActions
isPending={isPending}
onSubmit={handleSubmit}

View File

@@ -1,6 +1,9 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useNavigate } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import { useAuthStore } from "@/app/store/authStore";
import { extractErrorMessage } from "@/lib/api/client";
import { loginApi, getProfileApi, updateProfileApi, type LoginRequest, type UpdateProfileRequest } from "../api/authApi";
export function useLogin() {
@@ -41,12 +44,18 @@ export function useProfile() {
export function useUpdateProfile() {
const queryClient = useQueryClient();
const setUser = useAuthStore((s) => s.setUser);
const { t } = useTranslation();
return useMutation({
mutationFn: (data: UpdateProfileRequest) => updateProfileApi(data),
onSuccess: (updatedProfile) => {
setUser(updatedProfile);
queryClient.setQueryData(["auth", "profile"], updatedProfile);
queryClient.invalidateQueries({ queryKey: ["auth", "profile"] });
toast.success(t("profile.updateSuccess", "Profil üstünlikli täzelendi!"));
},
onError: (err) => {
toast.error(extractErrorMessage(err, t("profile.updateError", "Profil täzelenende ýalňyşlyk ýüze çykdy")));
},
});
}

View File

@@ -8,6 +8,7 @@ import { InfiniteSelect, type InfiniteSelectOption, type InfiniteSelectProps } f
import { Checkbox } from "@/components/ui/checkbox";
import { Label } from "@/components/ui/label";
import { FormActions } from "@/components/formActions";
import { AvatarUpload } from "@/components/avatarUpload";
import { BentoGrid, BentoCard } from "@/components/bento";
import { useCreateClient, useUpdateClient } from "../hooks/useClients";
import { useInfiniteRoles } from "@/features/roles/hooks/useRoles";
@@ -59,7 +60,7 @@ export function ClientForm({ mode, initialData }: ClientFormProps) {
const roleSelect: Omit<InfiniteSelectProps, "label" | "required" | "placeholder"> = useMemo(() => {
const opts: InfiniteSelectOption[] = (roleQuery.data?.pages ?? [])
.flatMap((p) => p.roles)
.map((r) => ({ value: r.name, label: r.name }));
.map((r) => ({ value: r.code, label: r.name }));
if (initialData) {
const current = initialData.role;
@@ -148,123 +149,115 @@ export function ClientForm({ mode, initialData }: ClientFormProps) {
<h1 className="text-xl font-semibold text-foreground">
{mode === "create" ? t("clients.createTitle", "Müşderi dörediň") : t("clients.editTitle", "Müşderi üýtgetmek")}
</h1>
<BentoGrid cols={2}>
<BentoCard>
<FormInput
type="text"
label={t("users.fields.username", "Ulanyjy ady")}
value={form.username}
onChange={(v) => setField("username", v)}
placeholder={t("users.fields.username", "Ulanyjy ady")}
error={errors.username}
disabled={isPending}
required
/>
<p className="text-xs text-muted-foreground -mt-3">{t("users.fields.usernameHint", "Unikal login ady")}</p>
{/* ── Identity ── */}
<BentoCard title={t("users.sections.identity", "Şahsy maglumat")}>
<div className="grid grid-cols-2 gap-3">
<FormInput
type="text"
label={t("users.fields.username", "Ulanyjy ady")}
value={form.username}
onChange={(v) => setField("username", v)}
placeholder={t("users.fields.username", "Ulanyjy ady")}
error={errors.username}
disabled={isPending}
required
/>
<FormInput
type="text"
label={t("users.fields.name", "Ady")}
value={form.name}
onChange={(v) => setField("name", v)}
placeholder={t("users.fields.name", "Ady")}
error={errors.name}
disabled={isPending}
required
/>
<FormInput
type="text"
label={t("users.fields.firstName", "Ady (at)")}
value={form.firstName}
onChange={(v) => setField("firstName", v)}
placeholder={t("users.fields.firstName", "Ady (at)")}
error={errors.firstName}
disabled={isPending}
/>
<FormInput
type="text"
label={t("users.fields.lastName", "Familiýasy")}
value={form.lastName}
onChange={(v) => setField("lastName", v)}
placeholder={t("users.fields.lastName", "Familiýasy")}
error={errors.lastName}
disabled={isPending}
/>
</div>
<div className="grid grid-cols-2 gap-3">
<FormInput
type="phone"
label={t("users.fields.phone", "Telefon")}
value={form.phone}
onChange={(v) => setField("phone", v)}
placeholder="62-38-49-56"
error={errors.phone}
disabled={isPending}
required
/>
<FormInput
type="email"
label={t("users.fields.email", "E-poçta")}
value={form.email}
onChange={(v) => setField("email", v)}
placeholder={t("users.fields.email", "E-poçta")}
error={errors.email}
disabled={isPending}
/>
<InfiniteSelect
label={t("users.fields.role", "Roly")}
value={form.role}
onChange={(v) => setField("role", v)}
placeholder={t("users.fields.role", "Roly")}
error={errors.role}
disabled={isPending}
required
{...roleSelect}
/>
{mode === "create" && (
<FormInput
type="password"
label={t("users.fields.password", "Açar sözi")}
value={form.password}
onChange={(v) => setField("password", v)}
placeholder={t("users.fields.password", "Açar sözi")}
error={errors.password}
disabled={isPending}
required
/>
)}
<div className="flex items-center gap-2 pt-1">
<Checkbox id="active" checked={form.active} onCheckedChange={(v) => setField("active", !!v)} disabled={isPending} />
<Label htmlFor="active" className="text-sm text-muted-foreground cursor-pointer">
{form.active ? t("common.active", "Işjeň") : t("common.inactive", "Işjeň däl")}
</Label>
</div>
</div>
</BentoCard>
{/* ── Avatar ── */}
<BentoCard>
<FormInput
type="text"
label={t("users.fields.name", "Ady")}
value={form.name}
onChange={(v) => setField("name", v)}
placeholder={t("users.fields.name", "Ady")}
error={errors.name}
disabled={isPending}
required
/>
<p className="text-xs text-muted-foreground -mt-3">{t("users.fields.nameHint", "Doly ady we familiýasy")}</p>
</BentoCard>
<BentoCard>
<FormInput
type="text"
label={t("users.fields.firstName", "Ady (at)")}
value={form.firstName}
onChange={(v) => setField("firstName", v)}
placeholder={t("users.fields.firstName", "Ady (at)")}
error={errors.firstName}
disabled={isPending}
/>
</BentoCard>
<BentoCard>
<FormInput
type="text"
label={t("users.fields.lastName", "Familiýasy")}
value={form.lastName}
onChange={(v) => setField("lastName", v)}
placeholder={t("users.fields.lastName", "Familiýasy")}
error={errors.lastName}
disabled={isPending}
/>
</BentoCard>
<BentoCard>
<FormInput
type="phone"
label={t("users.fields.phone", "Telefon")}
value={form.phone}
onChange={(v) => setField("phone", v)}
placeholder="62-38-49-56"
error={errors.phone}
disabled={isPending}
required
/>
<p className="text-xs text-muted-foreground -mt-3">{t("users.fields.phoneHint", "+993 bilen başlanýar")}</p>
</BentoCard>
<BentoCard>
<FormInput
type="email"
label={t("users.fields.email", "E-poçta")}
value={form.email}
onChange={(v) => setField("email", v)}
placeholder={t("users.fields.email", "E-poçta")}
error={errors.email}
disabled={isPending}
/>
<p className="text-xs text-muted-foreground -mt-3">{t("users.fields.emailHint", "Islege görä")}</p>
</BentoCard>
<BentoCard>
<InfiniteSelect
label={t("users.fields.role", "Roly")}
value={form.role}
onChange={(v) => setField("role", v)}
placeholder={t("users.fields.role", "Roly")}
error={errors.role}
disabled={isPending}
required
{...roleSelect}
/>
</BentoCard>
<BentoCard>
<FormInput
type="text"
label={t("users.fields.avatar", "Awatar URL")}
<AvatarUpload
label={t("users.fields.avatar", "Awatar")}
value={form.avatar}
onChange={(v) => setField("avatar", v)}
placeholder="https://..."
error={errors.avatar}
disabled={isPending}
/>
</BentoCard>
{mode === "create" && (
<BentoCard>
<FormInput
type="password"
label={t("users.fields.password", "Açar sözi")}
value={form.password}
onChange={(v) => setField("password", v)}
placeholder={t("users.fields.password", "Açar sözi")}
error={errors.password}
disabled={isPending}
required
/>
<p className="text-xs text-muted-foreground -mt-3">{t("users.fields.passwordHint", "Iň az 6 harp")}</p>
</BentoCard>
)}
<BentoCard>
<div className="space-y-1">
<p className="text-sm font-semibold text-muted-foreground">{t("users.fields.socialMedia", "Sosial media")}</p>
</div>
<div className="flex flex-col gap-3">
{/* ── Social media ── */}
<BentoCard title={t("users.fields.socialMedia", "Sosial media")} span="full">
<div className="grid grid-cols-3 gap-3">
<FormInput
type="text"
label={t("users.fields.facebook", "Facebook")}
@@ -294,30 +287,8 @@ export function ClientForm({ mode, initialData }: ClientFormProps) {
/>
</div>
</BentoCard>
<BentoCard>
<div className="space-y-1">
<p className="text-sm font-semibold text-muted-foreground">{t("users.fields.lightMode", "Light režimi")}</p>
</div>
<div className="flex items-center gap-2">
<Checkbox id="lightMode" checked={form.lightMode} onCheckedChange={(v) => setField("lightMode", !!v)} disabled={isPending} />
<Label htmlFor="lightMode" className="text-sm text-muted-foreground cursor-pointer">
{form.lightMode ? t("common.yes", "Hawa") : t("common.no", "Ýok")}
</Label>
</div>
</BentoCard>
<BentoCard>
<div className="space-y-1">
<p className="text-sm font-semibold text-muted-foreground">{t("users.fields.isActive", "Işjeň")}</p>
<p className="text-xs text-muted-foreground">{t("users.fields.isActiveHint", "Ulanyjynyň ulgama girip-bilmezligi")}</p>
</div>
<div className="flex items-center gap-2">
<Checkbox id="active" checked={form.active} onCheckedChange={(v) => setField("active", !!v)} disabled={isPending} />
<Label htmlFor="active" className="text-sm text-muted-foreground cursor-pointer">
{form.active ? t("common.active", "Işjeň") : t("common.inactive", "Işjeň däl")}
</Label>
</div>
</BentoCard>
</BentoGrid>
<FormActions
isPending={isPending}
onSubmit={handleSubmit}

View File

@@ -1,4 +1,5 @@
import apiClient from "@/lib/api/client";
import type { LocalizedText } from "@/features/branches/api/branchesApi";
// ─── Types ────────────────────────────────────────────────────────────────────
@@ -54,7 +55,8 @@ export interface OperatorPermission {
export interface OperatorBranch {
id: number;
name: string;
/** API returns a LocalizedText object {en, ru, tm}; guard both shapes */
name: LocalizedText | string;
region: string;
district: string;
uniqueCode: string;

View File

@@ -3,15 +3,20 @@ import { useNavigate } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { useQueryClient } from "@tanstack/react-query";
import { FormInput } from "@/components/formInput";
import { InfiniteSelect, type InfiniteSelectOption, type InfiniteSelectProps } from "@/components/infiniteSelect";
import { Checkbox } from "@/components/ui/checkbox";
import { Label } from "@/components/ui/label";
import { FormActions } from "@/components/formActions";
import { AvatarUpload } from "@/components/avatarUpload";
import { BentoGrid, BentoCard } from "@/components/bento";
import { useCreateOperator, useUpdateOperator } from "../hooks/useOperators";
import { useCreateOperator, useUpdateOperator, operatorKeys } from "../hooks/useOperators";
import { useInfiniteRoles } from "@/features/roles/hooks/useRoles";
import type { Operator } from "../api/operatorsApi";
import { useInfiniteBranches } from "@/features/shared/hooks/useSharedBranchUsers";
import { postBranchUser } from "@/features/shared/api/sharedApi";
import type { Operator, OperatorDetail } from "../api/operatorsApi";
import type { LocalizedText } from "@/features/branches/api/branchesApi";
import { operatorFormSchema, DEFAULT_FORM_VALUES, buildPayload, buildUpdatePayload } from "../schemas/operator.schema";
import type { OperatorFormData } from "../schemas/operator.schema";
@@ -19,7 +24,7 @@ import type { OperatorFormData } from "../schemas/operator.schema";
interface OperatorFormProps {
mode: "create" | "edit";
initialData?: Operator;
initialData?: OperatorDetail | Operator;
}
// ─── Helpers ──────────────────────────────────────────────────────────────────
@@ -35,6 +40,12 @@ function flattenErrors(errors: Record<string, { message?: string } | undefined>)
return result;
}
function resolveLocalizedName(name: LocalizedText | string | undefined | null, lang = "en"): string {
if (!name) return "";
if (typeof name === "string") return name;
return name[lang as keyof LocalizedText] ?? name.en ?? name.tm ?? name.ru ?? "";
}
// ─── OperatorForm ─────────────────────────────────────────────────────────────
export function OperatorForm({ mode, initialData }: OperatorFormProps) {
@@ -44,6 +55,7 @@ export function OperatorForm({ mode, initialData }: OperatorFormProps) {
[_t, i18n.language],
);
const navigate = useNavigate();
const queryClient = useQueryClient();
const createOperator = useCreateOperator();
const updateOperator = useUpdateOperator(initialData?.id ?? 0);
@@ -56,10 +68,24 @@ export function OperatorForm({ mode, initialData }: OperatorFormProps) {
const [roleSearch, setRoleSearch] = useState("");
const roleQuery = useInfiniteRoles(roleSearch);
// ── Branch infinite-scroll select ──
const attachedBranches = (initialData as OperatorDetail | undefined)?.branches ?? [];
const attachedBranch = attachedBranches[0];
const [selectedBranchId, setSelectedBranchId] = useState<string>(() => (attachedBranch ? String(attachedBranch.id) : ""));
useEffect(() => {
if (attachedBranch) {
setSelectedBranchId(String(attachedBranch.id));
}
}, [initialData, attachedBranch]);
const [branchSearch, setBranchSearch] = useState("");
const branchQuery = useInfiniteBranches(branchSearch);
const roleSelect: Omit<InfiniteSelectProps, "label" | "required" | "placeholder"> = useMemo(() => {
const opts: InfiniteSelectOption[] = (roleQuery.data?.pages ?? [])
.flatMap((p) => p.roles)
.map((r) => ({ value: r.name, label: r.name }));
.map((r) => ({ value: r.code, label: r.name }));
if (initialData) {
const current = initialData.role;
@@ -79,6 +105,36 @@ export function OperatorForm({ mode, initialData }: OperatorFormProps) {
};
}, [roleQuery, roleSearch, initialData]);
// ── Branch select props ──
const branchSelect: Omit<InfiniteSelectProps, "label" | "required" | "placeholder"> = useMemo(() => {
const lang = i18n.language ?? "en";
const opts: InfiniteSelectOption[] = (branchQuery.data?.pages ?? [])
.flatMap((p) => p.branches)
.map((b) => ({
value: String(b.id),
label: resolveLocalizedName(b.name, lang) || b.uniqueCode,
}));
// Make sure already attached branch is in options list so select displays its label properly
attachedBranches.forEach((b) => {
const bId = String(b.id);
if (!opts.some((o) => o.value === bId)) {
const label = resolveLocalizedName(b.name, lang) || b.uniqueCode || bId;
opts.unshift({ value: bId, label });
}
});
return {
options: opts,
loading: branchQuery.isLoading,
isLoadingMore: branchQuery.isFetchingNextPage,
hasNextPage: !!branchQuery.hasNextPage,
onLoadMore: () => branchQuery.fetchNextPage(),
searchValue: branchSearch,
onSearchChange: setBranchSearch,
};
}, [branchQuery, branchSearch, i18n.language, attachedBranches]);
const {
watch,
setValue,
@@ -134,11 +190,20 @@ export function OperatorForm({ mode, initialData }: OperatorFormProps) {
if (mode === "create") {
const payload = buildPayload(data);
await createOperator.mutateAsync(payload);
const createdUser = await createOperator.mutateAsync(payload);
if (selectedBranchId) {
await postBranchUser({ branchId: Number(selectedBranchId), userId: createdUser.id });
queryClient.invalidateQueries({ queryKey: operatorKeys.detail(createdUser.id) });
}
navigate("/operators");
} else {
const payload = buildUpdatePayload(data);
await updateOperator.mutateAsync(payload);
const initialBranchId = attachedBranch ? String(attachedBranch.id) : "";
if (selectedBranchId && selectedBranchId !== initialBranchId) {
await postBranchUser({ branchId: Number(selectedBranchId), userId: initialData!.id });
}
queryClient.invalidateQueries({ queryKey: operatorKeys.detail(initialData!.id) });
navigate(`/operators/${initialData!.id}`);
}
};
@@ -149,122 +214,121 @@ export function OperatorForm({ mode, initialData }: OperatorFormProps) {
{mode === "create" ? t("operators.createTitle", "Operator dörediň") : t("operators.editTitle", "Operator üýtgetmek")}
</h1>
<BentoGrid cols={2}>
<BentoCard>
<FormInput
type="text"
label={t("users.fields.username", "Ulanyjy ady")}
value={form.username}
onChange={(v) => setField("username", v)}
placeholder={t("users.fields.username", "Ulanyjy ady")}
error={errors.username}
disabled={isPending}
required
/>
<p className="text-xs text-muted-foreground -mt-3">{t("users.fields.usernameHint", "Unikal login ady")}</p>
{/* ── Identity ── */}
<BentoCard title={t("users.sections.identity", "Şahsy maglumat")}>
<div className="grid grid-cols-2 gap-3">
<FormInput
type="text"
label={t("users.fields.username", "Ulanyjy ady")}
value={form.username}
onChange={(v) => setField("username", v)}
placeholder={t("users.fields.username", "Ulanyjy ady")}
error={errors.username}
disabled={isPending}
required
/>
<FormInput
type="text"
label={t("users.fields.name", "Ady")}
value={form.name}
onChange={(v) => setField("name", v)}
placeholder={t("users.fields.name", "Ady")}
error={errors.name}
disabled={isPending}
required
/>
<FormInput
type="text"
label={t("users.fields.firstName", "Ady (at)")}
value={form.firstName}
onChange={(v) => setField("firstName", v)}
placeholder={t("users.fields.firstName", "Ady (at)")}
error={errors.firstName}
disabled={isPending}
/>
<FormInput
type="text"
label={t("users.fields.lastName", "Familiýasy")}
value={form.lastName}
onChange={(v) => setField("lastName", v)}
placeholder={t("users.fields.lastName", "Familiýasy")}
error={errors.lastName}
disabled={isPending}
/>
</div>
<div className="grid grid-cols-2 gap-3">
<FormInput
type="phone"
label={t("users.fields.phone", "Telefon")}
value={form.phone}
onChange={(v) => setField("phone", v)}
placeholder="62-38-49-56"
error={errors.phone}
disabled={isPending}
required
/>
<FormInput
type="email"
label={t("users.fields.email", "E-poçta")}
value={form.email}
onChange={(v) => setField("email", v)}
placeholder={t("users.fields.email", "E-poçta")}
error={errors.email}
disabled={isPending}
/>
<InfiniteSelect
label={t("users.fields.role", "Roly")}
value={form.role}
onChange={(v) => setField("role", v)}
placeholder={t("users.fields.role", "Roly")}
error={errors.role}
disabled={isPending}
required
{...roleSelect}
/>
<InfiniteSelect
label={t("users.fields.branch", "Şahamça")}
value={selectedBranchId}
onChange={(branchId) => setSelectedBranchId(branchId)}
placeholder={t("users.fields.branchPlaceholder", "Şahamça saýlaň")}
disabled={isPending}
{...branchSelect}
/>
{mode === "create" && (
<FormInput
type="password"
label={t("users.fields.password", "Açar sözi")}
value={form.password}
onChange={(v) => setField("password", v)}
placeholder={t("users.fields.password", "Açar sözi")}
error={errors.password}
disabled={isPending}
required
/>
)}
<div className="flex items-center gap-2 pt-1">
<Checkbox id="active" checked={form.active} onCheckedChange={(v) => setField("active", !!v)} disabled={isPending} />
<Label htmlFor="active" className="text-sm text-muted-foreground cursor-pointer">
{form.active ? t("common.active", "Işjeň") : t("common.inactive", "Işjeň däl")}
</Label>
</div>
</div>
</BentoCard>
{/* ── Avatar ── */}
<BentoCard>
<FormInput
type="text"
label={t("users.fields.name", "Ady")}
value={form.name}
onChange={(v) => setField("name", v)}
placeholder={t("users.fields.name", "Ady")}
error={errors.name}
disabled={isPending}
required
/>
<p className="text-xs text-muted-foreground -mt-3">{t("users.fields.nameHint", "Doly ady we familiýasy")}</p>
</BentoCard>
<BentoCard>
<FormInput
type="text"
label={t("users.fields.firstName", "Ady (at)")}
value={form.firstName}
onChange={(v) => setField("firstName", v)}
placeholder={t("users.fields.firstName", "Ady (at)")}
error={errors.firstName}
disabled={isPending}
/>
</BentoCard>
<BentoCard>
<FormInput
type="text"
label={t("users.fields.lastName", "Familiýasy")}
value={form.lastName}
onChange={(v) => setField("lastName", v)}
placeholder={t("users.fields.lastName", "Familiýasy")}
error={errors.lastName}
disabled={isPending}
/>
</BentoCard>
<BentoCard>
<FormInput
type="phone"
label={t("users.fields.phone", "Telefon")}
value={form.phone}
onChange={(v) => setField("phone", v)}
placeholder="62-38-49-56"
error={errors.phone}
disabled={isPending}
required
/>
<p className="text-xs text-muted-foreground -mt-3">{t("users.fields.phoneHint", "+993 bilen başlanýar")}</p>
</BentoCard>
<BentoCard>
<FormInput
type="email"
label={t("users.fields.email", "E-poçta")}
value={form.email}
onChange={(v) => setField("email", v)}
placeholder={t("users.fields.email", "E-poçta")}
error={errors.email}
disabled={isPending}
/>
<p className="text-xs text-muted-foreground -mt-3">{t("users.fields.emailHint", "Islege görä")}</p>
</BentoCard>
<BentoCard>
<InfiniteSelect
label={t("users.fields.role", "Roly")}
value={form.role}
onChange={(v) => setField("role", v)}
placeholder={t("users.fields.role", "Roly")}
error={errors.role}
disabled={isPending}
required
{...roleSelect}
/>
</BentoCard>
<BentoCard>
<FormInput
type="text"
label={t("users.fields.avatar", "Awatar URL")}
<AvatarUpload
label={t("users.fields.avatar", "Awatar")}
value={form.avatar}
onChange={(v) => setField("avatar", v)}
placeholder="https://..."
error={errors.avatar}
disabled={isPending}
/>
</BentoCard>
{mode === "create" && (
<BentoCard>
<FormInput
type="password"
label={t("users.fields.password", "Açar sözi")}
value={form.password}
onChange={(v) => setField("password", v)}
placeholder={t("users.fields.password", "Açar sözi")}
error={errors.password}
disabled={isPending}
required
/>
<p className="text-xs text-muted-foreground -mt-3">{t("users.fields.passwordHint", "Iň az 6 harp")}</p>
</BentoCard>
)}
<BentoCard>
<div className="space-y-1">
<p className="text-sm font-semibold text-muted-foreground">{t("users.fields.socialMedia", "Sosial media")}</p>
</div>
<div className="flex flex-col gap-3">
{/* ── Social media ── */}
<BentoCard title={t("users.fields.socialMedia", "Sosial media")} span="full">
<div className="grid grid-cols-3 gap-3">
<FormInput
type="text"
label={t("users.fields.facebook", "Facebook")}
@@ -294,30 +358,8 @@ export function OperatorForm({ mode, initialData }: OperatorFormProps) {
/>
</div>
</BentoCard>
<BentoCard>
<div className="space-y-1">
<p className="text-sm font-semibold text-muted-foreground">{t("users.fields.lightMode", "Light režimi")}</p>
</div>
<div className="flex items-center gap-2">
<Checkbox id="lightMode" checked={form.lightMode} onCheckedChange={(v) => setField("lightMode", !!v)} disabled={isPending} />
<Label htmlFor="lightMode" className="text-sm text-muted-foreground cursor-pointer">
{form.lightMode ? t("common.yes", "Hawa") : t("common.no", "Ýok")}
</Label>
</div>
</BentoCard>
<BentoCard>
<div className="space-y-1">
<p className="text-sm font-semibold text-muted-foreground">{t("users.fields.isActive", "Işjeň")}</p>
<p className="text-xs text-muted-foreground">{t("users.fields.isActiveHint", "Ulanyjynyň ulgama girip-bilmezligi")}</p>
</div>
<div className="flex items-center gap-2">
<Checkbox id="active" checked={form.active} onCheckedChange={(v) => setField("active", !!v)} disabled={isPending} />
<Label htmlFor="active" className="text-sm text-muted-foreground cursor-pointer">
{form.active ? t("common.active", "Işjeň") : t("common.inactive", "Işjeň däl")}
</Label>
</div>
</BentoCard>
</BentoGrid>
<FormActions
isPending={isPending}
onSubmit={handleSubmit}

View File

@@ -60,9 +60,9 @@ export function useUpdateOperator(id: number) {
return useMutation({
mutationFn: (payload: UpdateOperatorPayload) => operatorsApi.updateOperator(id, payload),
onSuccess: (updatedOperator) => {
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: operatorKeys.lists() });
queryClient.setQueryData(operatorKeys.detail(id), updatedOperator);
queryClient.invalidateQueries({ queryKey: operatorKeys.detail(id) });
toast.success(t("operators.updateSuccess", "Operator üstünlikli täzelendi"));
},
});

View File

@@ -0,0 +1,55 @@
import apiClient from "@/lib/api/client";
import { fetchBranches, type BranchListParams, type BranchListResponse } from "@/features/branches/api/branchesApi";
// ─── Types ────────────────────────────────────────────────────────────────────
export interface AddBranchUserPayload {
branchId: number;
userId: number;
}
// Re-export so shared hooks can import from one place
export type { BranchListParams, BranchListResponse };
// ─── File Upload ──────────────────────────────────────────────────────────────
/**
* Builds the public URL for an uploaded file.
* The backend stores files under `{apiOrigin}/file/{filename}`, while the
* API base URL itself ends with `/api/admin`.
*/
export function buildFileUrl(filename: string): string {
const apiBase = import.meta.env.VITE_API_BASE_URL || "/api/admin";
const origin = apiBase.replace(/\/api\/admin\/?$/, "");
return `${origin}/file/${filename}`;
}
/**
* POST /file — multipart image upload.
* Response envelope: { status, message, code, data: "....png" }.
* The axios response interceptor unwraps `data`, so this returns the filename.
*/
export async function postFile(file: File): Promise<string> {
const formData = new FormData();
formData.append("file", file);
const { data } = await apiClient.post<string>("/file", formData, {
headers: { "Content-Type": "multipart/form-data" },
});
return data;
}
// ─── API Functions ────────────────────────────────────────────────────────────
/**
* POST /branch-users
* Assigns a branch to a user. Used by operators, managers, etc.
*/
export async function postBranchUser(payload: AddBranchUserPayload): Promise<void> {
await apiClient.post("/branch-users", payload);
}
/**
* Proxy for branch list fetching — kept here so shared hooks
* don't import directly from the branches feature.
*/
export { fetchBranches };

View File

@@ -0,0 +1,56 @@
import { useMutation, useInfiniteQuery, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { useTranslation } from "react-i18next";
import { useDebouncedValue, normalizeSearch } from "@/hooks/useDebouncedSearch";
import { postBranchUser, fetchBranches, type AddBranchUserPayload } from "../api/sharedApi";
import { operatorKeys } from "@/features/operators/hooks/useOperators";
// ─── Query Keys ───────────────────────────────────────────────────────────────
export const sharedBranchKeys = {
all: ["shared-branches"] as const,
infinite: (search: string) => [...sharedBranchKeys.all, "infinite", search] as const,
};
// ─── useInfiniteBranches ──────────────────────────────────────────────────────
const BRANCH_PAGE_SIZE = 25;
/**
* Infinite-scroll branch list for searchable selects.
* staleTime = 5 min as required by PROJECT_STANDARDS rule 12.
*/
export function useInfiniteBranches(search = "") {
const debouncedSearch = useDebouncedValue(search);
const effectiveSearch = normalizeSearch(debouncedSearch);
return useInfiniteQuery({
queryKey: sharedBranchKeys.infinite(effectiveSearch),
initialPageParam: 1,
queryFn: ({ pageParam, signal }) => fetchBranches({ page: pageParam, limit: BRANCH_PAGE_SIZE, search: effectiveSearch }, signal),
getNextPageParam: (lastPage, allPages) => {
const loaded = allPages.reduce((sum, p) => sum + p.branches.length, 0);
return loaded < lastPage.count ? allPages.length + 1 : undefined;
},
staleTime: 5 * 60 * 1000, // 5 minutes
});
}
// ─── useAddBranchUser ─────────────────────────────────────────────────────────
/**
* POST /branch-users
* On success, invalidates the operator detail so the branches section refreshes.
*/
export function useAddBranchUser(operatorId: number) {
const queryClient = useQueryClient();
const { t } = useTranslation();
return useMutation({
mutationFn: (payload: AddBranchUserPayload) => postBranchUser(payload),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: operatorKeys.detail(operatorId) });
toast.success(t("operators.branchAssigned", "Şahamça birikdirildi"));
},
});
}