260322:1648 Correct Coresspondence / Doing RFA / Correct CI
CI Pipeline / build (push) Failing after 12m41s
Build and Deploy / deploy (push) Failing after 2m44s

This commit is contained in:
admin
2026-03-22 16:48:12 +07:00
parent e5deedb42e
commit 11984bfa29
683 changed files with 105251 additions and 29068 deletions
@@ -1,45 +1,30 @@
"use client";
'use client';
import { useForm, Controller } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogFooter,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import {
useCreateOrganization,
useUpdateOrganization,
} from "@/hooks/use-master-data";
import { useEffect } from "react";
import { Organization } from "@/types/organization";
import { useForm, Controller } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { useCreateOrganization, useUpdateOrganization } from '@/hooks/use-master-data';
import { useEffect } from 'react';
import { Organization } from '@/types/organization';
// Organization role types matching database
const ORGANIZATION_ROLES = [
{ value: "1", label: "Owner" },
{ value: "2", label: "Designer" },
{ value: "3", label: "Consultant" },
{ value: "4", label: "Contractor" },
{ value: "5", label: "Third Party" },
{ value: '1', label: 'Owner' },
{ value: '2', label: 'Designer' },
{ value: '3', label: 'Consultant' },
{ value: '4', label: 'Contractor' },
{ value: '5', label: 'Third Party' },
] as const;
const organizationSchema = z.object({
organizationCode: z.string().min(1, "Organization Code is required"),
organizationName: z.string().min(1, "Organization Name is required"),
organizationCode: z.string().min(1, 'Organization Code is required'),
organizationName: z.string().min(1, 'Organization Name is required'),
roleId: z.string().optional(),
isActive: z.boolean().optional(),
});
@@ -52,11 +37,7 @@ interface OrganizationDialogProps {
organization?: Organization | null;
}
export function OrganizationDialog({
open,
onOpenChange,
organization,
}: OrganizationDialogProps) {
export function OrganizationDialog({ open, onOpenChange, organization }: OrganizationDialogProps) {
const createOrg = useCreateOrganization();
const updateOrg = useUpdateOrganization();
@@ -71,9 +52,9 @@ export function OrganizationDialog({
} = useForm<OrganizationFormData>({
resolver: zodResolver(organizationSchema),
defaultValues: {
organizationCode: "",
organizationName: "",
roleId: "",
organizationCode: '',
organizationName: '',
roleId: '',
isActive: true,
},
});
@@ -83,14 +64,14 @@ export function OrganizationDialog({
reset({
organizationCode: organization.organizationCode,
organizationName: organization.organizationName,
roleId: organization.roleId?.toString() || "",
roleId: organization.roleId?.toString() || '',
isActive: organization.isActive,
});
} else {
reset({
organizationCode: "",
organizationName: "",
roleId: "",
organizationCode: '',
organizationName: '',
roleId: '',
isActive: true,
});
}
@@ -99,14 +80,11 @@ export function OrganizationDialog({
const onSubmit = (data: OrganizationFormData) => {
const submitData = {
...data,
roleId: data.roleId ? parseInt(data.roleId) : undefined,
roleId: data.roleId ? Number(data.roleId) : undefined,
};
if (organization) {
updateOrg.mutate(
{ uuid: organization.uuid, data: submitData },
{ onSuccess: () => onOpenChange(false) }
);
updateOrg.mutate({ uuid: organization.uuid, data: submitData }, { onSuccess: () => onOpenChange(false) });
} else {
createOrg.mutate(submitData, {
onSuccess: () => onOpenChange(false),
@@ -118,31 +96,19 @@ export function OrganizationDialog({
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent>
<DialogHeader>
<DialogTitle>
{organization ? "Edit Organization" : "New Organization"}
</DialogTitle>
<DialogTitle>{organization ? 'Edit Organization' : 'New Organization'}</DialogTitle>
</DialogHeader>
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label>Organization Code *</Label>
<Input
placeholder="e.g. OWNER"
{...register("organizationCode")}
/>
{errors.organizationCode && (
<p className="text-sm text-red-500">
{errors.organizationCode.message}
</p>
)}
<Input placeholder="e.g. OWNER" {...register('organizationCode')} />
{errors.organizationCode && <p className="text-sm text-red-500">{errors.organizationCode.message}</p>}
</div>
<div className="space-y-2">
<Label>Role</Label>
<Select
value={watch("roleId")}
onValueChange={(value) => setValue("roleId", value)}
>
<Select value={watch('roleId')} onValueChange={(value) => setValue('roleId', value)}>
<SelectTrigger>
<SelectValue placeholder="Select role" />
</SelectTrigger>
@@ -159,49 +125,28 @@ export function OrganizationDialog({
<div className="space-y-2">
<Label>Organization Name *</Label>
<Input
placeholder="e.g. Project Owner Co., Ltd."
{...register("organizationName")}
/>
{errors.organizationName && (
<p className="text-sm text-red-500">
{errors.organizationName.message}
</p>
)}
<Input placeholder="e.g. Project Owner Co., Ltd." {...register('organizationName')} />
{errors.organizationName && <p className="text-sm text-red-500">{errors.organizationName.message}</p>}
</div>
<div className="flex items-center justify-between rounded-lg border p-3 shadow-sm">
<div className="space-y-0.5">
<Label>Active Status</Label>
<p className="text-sm text-muted-foreground">
Enable or disable this organization
</p>
<p className="text-sm text-muted-foreground">Enable or disable this organization</p>
</div>
<Controller
control={control}
name="isActive"
render={({ field }) => (
<Switch
checked={field.value}
onCheckedChange={field.onChange}
/>
)}
render={({ field }) => <Switch checked={field.value} onCheckedChange={field.onChange} />}
/>
</div>
<DialogFooter>
<Button
type="button"
variant="outline"
onClick={() => onOpenChange(false)}
>
<Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
Cancel
</Button>
<Button
type="submit"
disabled={createOrg.isPending || updateOrg.isPending}
>
{organization ? "Save Changes" : "Create Organization"}
<Button type="submit" disabled={createOrg.isPending || updateOrg.isPending}>
{organization ? 'Save Changes' : 'Create Organization'}
</Button>
</DialogFooter>
</form>
@@ -1,34 +1,16 @@
"use client";
'use client';
import { useState } from "react";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import {
flexRender,
getCoreRowModel,
useReactTable,
ColumnDef,
} from "@tanstack/react-table";
import { Button } from "@/components/ui/button";
import { Plus, Pencil, Trash2, Loader2 } from "lucide-react";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogFooter,
} from "@/components/ui/dialog";
import { useForm } from "react-hook-form";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { useState } from 'react';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { flexRender, getCoreRowModel, useReactTable, ColumnDef } from '@tanstack/react-table';
import { Button } from '@/components/ui/button';
import { Plus, Pencil, Trash2, Loader2 } from 'lucide-react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog';
import { useForm } from 'react-hook-form';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { toast } from 'sonner';
import {
AlertDialog,
AlertDialogAction,
@@ -38,21 +20,15 @@ import {
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Checkbox } from "@/components/ui/checkbox";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
} from '@/components/ui/alert-dialog';
import { Checkbox } from '@/components/ui/checkbox';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
interface Field {
name: string;
label: string;
type: "text" | "number" | "checkbox" | "select" | "textarea";
type: 'text' | 'number' | 'checkbox' | 'select' | 'textarea';
required?: boolean;
options?: { label: string; value: string | number }[];
}
@@ -93,7 +69,11 @@ export function GenericCrudTable<T extends { id?: number; uuid?: string }>({
const [editingItem, setEditingId] = useState<number | null>(null);
const [itemToDelete, setItemToDelete] = useState<number | null>(null);
const { data: rawData, isLoading, refetch } = useQuery({
const {
data: rawData,
isLoading,
_refetch,
} = useQuery({
queryKey,
queryFn: fetchFn,
});
@@ -154,14 +134,10 @@ export function GenericCrudTable<T extends { id?: number; uuid?: string }>({
columns: [
...columns,
{
id: "actions",
id: 'actions',
cell: ({ row }) => (
<div className="flex justify-end gap-2">
<Button
variant="ghost"
size="icon"
onClick={() => handleEdit(row.original)}
>
<Button variant="ghost" size="icon" onClick={() => handleEdit(row.original)}>
<Pencil className="h-4 w-4" />
</Button>
<Button
@@ -183,7 +159,7 @@ export function GenericCrudTable<T extends { id?: number; uuid?: string }>({
setEditingId(null);
reset();
fields.forEach((f) => {
if (f.type === "checkbox") setValue(f.name, true);
if (f.type === 'checkbox') setValue(f.name, true);
});
setIsDialogOpen(true);
};
@@ -192,11 +168,11 @@ export function GenericCrudTable<T extends { id?: number; uuid?: string }>({
setEditingId(item.id as number);
reset(item as Record<string, unknown>);
// Ensure select values are strings for Shadcn Select
fields.forEach(f => {
const record = item as Record<string, unknown>;
if (f.type === 'select' && record[f.name]) {
setValue(f.name, String(record[f.name]));
}
fields.forEach((f) => {
const record = item as Record<string, unknown>;
if (f.type === 'select' && record[f.name]) {
setValue(f.name, String(record[f.name]));
}
});
setIsDialogOpen(true);
};
@@ -214,9 +190,7 @@ export function GenericCrudTable<T extends { id?: number; uuid?: string }>({
<div className="flex justify-between items-center">
<div>
<h2 className="text-2xl font-bold tracking-tight">{title}</h2>
{description && (
<p className="text-muted-foreground">{description}</p>
)}
{description && <p className="text-muted-foreground">{description}</p>}
</div>
<Button onClick={handleAdd}>
<Plus className="h-4 w-4 mr-2" /> Add {entityName}
@@ -232,12 +206,7 @@ export function GenericCrudTable<T extends { id?: number; uuid?: string }>({
<TableRow key={headerGroup.id}>
{headerGroup.headers.map((header) => (
<TableHead key={header.id}>
{header.isPlaceholder
? null
: flexRender(
header.column.columnDef.header,
header.getContext()
)}
{header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
</TableHead>
))}
</TableRow>
@@ -246,10 +215,7 @@ export function GenericCrudTable<T extends { id?: number; uuid?: string }>({
<TableBody>
{isLoading ? (
<TableRow>
<TableCell
colSpan={columns.length + 1}
className="h-24 text-center"
>
<TableCell colSpan={columns.length + 1} className="h-24 text-center">
<div className="flex items-center justify-center gap-2">
<Loader2 className="h-4 w-4 animate-spin" />
Loading...
@@ -258,10 +224,7 @@ export function GenericCrudTable<T extends { id?: number; uuid?: string }>({
</TableRow>
) : data.length === 0 ? (
<TableRow>
<TableCell
colSpan={columns.length + 1}
className="h-24 text-center text-muted-foreground"
>
<TableCell colSpan={columns.length + 1} className="h-24 text-center text-muted-foreground">
No data found.
</TableCell>
</TableRow>
@@ -269,12 +232,7 @@ export function GenericCrudTable<T extends { id?: number; uuid?: string }>({
table.getRowModel().rows.map((row) => (
<TableRow key={row.id}>
{row.getVisibleCells().map((cell) => (
<TableCell key={cell.id}>
{flexRender(
cell.column.columnDef.cell,
cell.getContext()
)}
</TableCell>
<TableCell key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</TableCell>
))}
</TableRow>
))
@@ -286,17 +244,15 @@ export function GenericCrudTable<T extends { id?: number; uuid?: string }>({
<Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle>
{editingItem ? `Edit ${entityName}` : `Add New ${entityName}`}
</DialogTitle>
<DialogTitle>{editingItem ? `Edit ${entityName}` : `Add New ${entityName}`}</DialogTitle>
</DialogHeader>
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4 py-4">
{fields.map((field) => (
<div key={field.name} className="space-y-2">
<Label htmlFor={field.name}>
{field.label} {field.required && "*"}
{field.label} {field.required && '*'}
</Label>
{field.type === "checkbox" ? (
{field.type === 'checkbox' ? (
<div className="flex items-center space-x-2">
<Checkbox
id={field.name}
@@ -310,11 +266,8 @@ export function GenericCrudTable<T extends { id?: number; uuid?: string }>({
Active
</label>
</div>
) : field.type === "select" ? (
<Select
value={String(watch(field.name) || "")}
onValueChange={(val) => setValue(field.name, val)}
>
) : field.type === 'select' ? (
<Select value={String(watch(field.name) || '')} onValueChange={(val) => setValue(field.name, val)}>
<SelectTrigger>
<SelectValue placeholder={`Select ${field.label}...`} />
</SelectTrigger>
@@ -326,57 +279,43 @@ export function GenericCrudTable<T extends { id?: number; uuid?: string }>({
))}
</SelectContent>
</Select>
) : field.type === "textarea" ? (
<Textarea
id={field.name}
{...register(field.name, { required: field.required })}
/>
) : field.type === 'textarea' ? (
<Textarea id={field.name} {...register(field.name, { required: field.required })} />
) : (
<Input
id={field.name}
type={field.type}
{...register(field.name, {
required: field.required,
valueAsNumber: field.type === "number",
valueAsNumber: field.type === 'number',
})}
/>
)}
{errors[field.name] && (
<p className="text-xs text-red-500 font-medium">
{field.label} is required
</p>
)}
{errors[field.name] && <p className="text-xs text-red-500 font-medium">{field.label} is required</p>}
</div>
))}
<DialogFooter>
<Button
type="button"
variant="outline"
onClick={() => setIsDialogOpen(false)}
>
<Button type="button" variant="outline" onClick={() => setIsDialogOpen(false)}>
Cancel
</Button>
<Button type="submit" disabled={createMutation.isPending || updateMutation.isPending}>
{(createMutation.isPending || updateMutation.isPending) && (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
)}
{editingItem ? "Save Changes" : `Add ${entityName}`}
{editingItem ? 'Save Changes' : `Add ${entityName}`}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
<AlertDialog
open={itemToDelete !== null}
onOpenChange={(open) => !open && setItemToDelete(null)}
>
<AlertDialog open={itemToDelete !== null} onOpenChange={(open) => !open && setItemToDelete(null)}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Are you sure?</AlertDialogTitle>
<AlertDialogDescription>
This action cannot be undone. This will permanently delete this{" "}
{entityName.toLowerCase()} and remove its data from our servers.
This action cannot be undone. This will permanently delete this {entityName.toLowerCase()} and remove its
data from our servers.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
@@ -385,7 +324,7 @@ export function GenericCrudTable<T extends { id?: number; uuid?: string }>({
onClick={() => itemToDelete && deleteMutation.mutate(itemToDelete)}
className="bg-red-600 hover:bg-red-700"
>
{deleteMutation.isPending ? "Deleting..." : "Delete"}
{deleteMutation.isPending ? 'Deleting...' : 'Delete'}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
@@ -1,20 +1,13 @@
"use client";
'use client';
import { useState } from "react";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import { Checkbox } from "@/components/ui/checkbox";
import { Button } from "@/components/ui/button";
import { RefreshCw, Save } from "lucide-react";
import { toast } from "sonner";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import apiClient from "@/lib/api/client";
import { useState } from 'react';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Checkbox } from '@/components/ui/checkbox';
import { Button } from '@/components/ui/button';
import { RefreshCw, Save } from 'lucide-react';
import { toast } from 'sonner';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import apiClient from '@/lib/api/client';
interface Role {
roleId: number;
@@ -28,7 +21,7 @@ interface Permission {
description: string;
}
interface RbacMatrixProps {
interface _RbacMatrixProps {
roles: Role[];
permissions: Permission[];
rolePermissions: Record<number, number[]>; // roleId -> permissionIds[]
@@ -42,7 +35,7 @@ const extractArrayData = <T,>(value: unknown): T[] => {
return current as T[];
}
if (!current || typeof current !== "object" || !("data" in current)) {
if (!current || typeof current !== 'object' || !('data' in current)) {
return [];
}
@@ -54,11 +47,11 @@ const extractArrayData = <T,>(value: unknown): T[] => {
const securityService = {
getRoles: async (): Promise<Role[]> => {
const response = await apiClient.get("/users/roles");
const response = await apiClient.get('/users/roles');
return extractArrayData<Role>(response.data);
},
getPermissions: async (): Promise<Permission[]> => {
const response = await apiClient.get("/users/permissions");
const response = await apiClient.get('/users/permissions');
return extractArrayData<Permission>(response.data);
},
updateRolePermissions: async (roleId: number, permissionIds: number[]) => {
@@ -73,12 +66,12 @@ export function RbacMatrix() {
const [pendingChanges, setPendingChanges] = useState<Record<number, number[]>>({});
const { data: roles = [], isLoading: rolesLoading } = useQuery<Role[]>({
queryKey: ["roles"],
queryKey: ['roles'],
queryFn: securityService.getRoles,
});
const { data: permissions = [], isLoading: permsLoading } = useQuery<Permission[]>({
queryKey: ["permissions"],
queryKey: ['permissions'],
queryFn: securityService.getPermissions,
});
@@ -92,16 +85,16 @@ export function RbacMatrix() {
const updateMutation = useMutation({
mutationFn: async (changes: Record<number, number[]>) => {
const promises = Object.entries(changes).map(([roleId, perms]) =>
securityService.updateRolePermissions(parseInt(roleId), perms)
securityService.updateRolePermissions(Number(roleId), perms)
);
return Promise.all(promises);
},
onSuccess: () => {
toast.success("Permissions updated successfully");
toast.success('Permissions updated successfully');
setPendingChanges({});
queryClient.invalidateQueries({ queryKey: ["roles"] });
queryClient.invalidateQueries({ queryKey: ['roles'] });
},
onError: () => toast.error("Failed to update permissions"),
onError: () => toast.error('Failed to update permissions'),
});
const handleToggle = (roleId: number, permId: number, currentPerms: number[]) => {
+192 -223
View File
@@ -1,65 +1,63 @@
"use client";
'use client';
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Checkbox } from "@/components/ui/checkbox";
import { useCreateUser, useUpdateUser, useRoles } from "@/hooks/use-users";
import { useOrganizations } from "@/hooks/use-master-data";
import { useEffect, useState } from "react";
import { User } from "@/types/user";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Eye, EyeOff } from "lucide-react";
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Checkbox } from '@/components/ui/checkbox';
import { useCreateUser, useUpdateUser, useRoles } from '@/hooks/use-users';
import { useOrganizations } from '@/hooks/use-master-data';
import { useEffect, useState } from 'react';
import { User } from '@/types/user';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Eye, EyeOff } from 'lucide-react';
const ALL_ORGANIZATIONS_VALUE = "all";
const ALL_ORGANIZATIONS_VALUE = 'all';
// Update schema to include confirmPassword
const userSchema = z.object({
username: z.string().min(3, "Username must be at least 3 characters"),
email: z.string().email("Invalid email address"),
firstName: z.string().min(1, "First name is required"),
lastName: z.string().min(1, "Last name is required"),
password: z.string().optional(),
confirmPassword: z.string().optional(),
isActive: z.boolean().optional(),
lineId: z.string().optional(),
primaryOrganizationId: z.string().optional(),
roleIds: z.array(z.number()).optional(),
}).refine((data) => {
// If password is provided (creating or resetting), confirmPassword must match
if (data.password && data.password !== data.confirmPassword) {
return false;
}
return true;
}, {
message: "Passwords do not match",
path: ["confirmPassword"],
}).refine((data) => {
// Password required for creation
// We can't easily check "isCreating" here without context, checking length if provided
if (data.password && data.password.length < 6) {
return false;
}
return true;
}, {
message: "Password must be at least 6 characters",
path: ["password"]
});
const userSchema = z
.object({
username: z.string().min(3, 'Username must be at least 3 characters'),
email: z.string().email('Invalid email address'),
firstName: z.string().min(1, 'First name is required'),
lastName: z.string().min(1, 'Last name is required'),
password: z.string().optional(),
confirmPassword: z.string().optional(),
isActive: z.boolean().optional(),
lineId: z.string().optional(),
primaryOrganizationId: z.string().optional(),
roleIds: z.array(z.number()).optional(),
})
.refine(
(data) => {
// If password is provided (creating or resetting), confirmPassword must match
if (data.password && data.password !== data.confirmPassword) {
return false;
}
return true;
},
{
message: 'Passwords do not match',
path: ['confirmPassword'],
}
)
.refine(
(data) => {
// Password required for creation
// We can't easily check "isCreating" here without context, checking length if provided
if (data.password && data.password.length < 6) {
return false;
}
return true;
},
{
message: 'Password must be at least 6 characters',
path: ['password'],
}
);
type UserFormData = z.infer<typeof userSchema>;
@@ -87,16 +85,16 @@ export function UserDialog({ open, onOpenChange, user }: UserDialogProps) {
} = useForm<UserFormData>({
resolver: zodResolver(userSchema),
defaultValues: {
username: "",
email: "",
firstName: "",
lastName: "",
username: '',
email: '',
firstName: '',
lastName: '',
isActive: true,
roleIds: [],
lineId: "",
lineId: '',
primaryOrganizationId: ALL_ORGANIZATIONS_VALUE,
password: "",
confirmPassword: ""
password: '',
confirmPassword: '',
},
});
@@ -108,24 +106,24 @@ export function UserDialog({ open, onOpenChange, user }: UserDialogProps) {
firstName: user.firstName,
lastName: user.lastName,
isActive: user.isActive,
lineId: user.lineId || "",
lineId: user.lineId || '',
primaryOrganizationId: user.primaryOrganizationId?.toString() || ALL_ORGANIZATIONS_VALUE,
roleIds: user.roles?.map((r: { roleId: number }) => r.roleId) || [],
password: "",
confirmPassword: ""
password: '',
confirmPassword: '',
});
} else {
reset({
username: "",
email: "",
firstName: "",
lastName: "",
username: '',
email: '',
firstName: '',
lastName: '',
isActive: true,
lineId: "",
lineId: '',
primaryOrganizationId: ALL_ORGANIZATIONS_VALUE,
roleIds: [],
password: "",
confirmPassword: ""
password: '',
confirmPassword: '',
});
}
// Also reset visibility
@@ -133,17 +131,17 @@ export function UserDialog({ open, onOpenChange, user }: UserDialogProps) {
setShowConfirmPassword(false);
}, [user, reset, open]);
const selectedRoleIds = watch("roleIds") || [];
const selectedRoleIds = watch('roleIds') || [];
const onSubmit = (data: UserFormData) => {
// Basic validation for create vs update
if (!user && !data.password) {
// This should be caught by schema ideally, but refined schema is tricky with conditional
// Force error via set error not possible easily here, rely on form state?
// Actually the refine check handles length check if provided, but for create it is mandatory.
// Let's rely on server side or manual check if schema misses it (zod optional() makes it pass if undefined)
// Adjusting schema to be strict string for create is hard with one schema.
// Let's trust Zod or add checks.
// This should be caught by schema ideally, but refined schema is tricky with conditional
// Force error via set error not possible easily here, rely on form state?
// Actually the refine check handles length check if provided, but for create it is mandatory.
// Let's rely on server side or manual check if schema misses it (zod optional() makes it pass if undefined)
// Adjusting schema to be strict string for create is hard with one schema.
// Let's trust Zod or add checks.
}
// Clean up data
@@ -155,27 +153,27 @@ export function UserDialog({ open, onOpenChange, user }: UserDialogProps) {
}
if (user) {
updateUser.mutate(
{ uuid: user.uuid, data: payload },
{ onSuccess: () => onOpenChange(false) }
);
updateUser.mutate({ uuid: user.uuid, data: payload }, { onSuccess: () => onOpenChange(false) });
} else {
// Create req: Password mandatory
if (!payload.password) return; // Should allow Zod to catch or show error
createUser.mutate({
username: payload.username,
email: payload.email,
firstName: payload.firstName,
lastName: payload.lastName,
password: payload.password,
isActive: payload.isActive ?? true,
lineId: payload.lineId,
primaryOrganizationId: payload.primaryOrganizationId,
roleIds: payload.roleIds ?? [],
}, {
onSuccess: () => onOpenChange(false),
});
createUser.mutate(
{
username: payload.username,
email: payload.email,
firstName: payload.firstName,
lastName: payload.lastName,
password: payload.password,
isActive: payload.isActive ?? true,
lineId: payload.lineId,
primaryOrganizationId: payload.primaryOrganizationId,
roleIds: payload.roleIds ?? [],
},
{
onSuccess: () => onOpenChange(false),
}
);
}
};
@@ -183,77 +181,61 @@ export function UserDialog({ open, onOpenChange, user }: UserDialogProps) {
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-2xl">
<DialogHeader>
<DialogTitle>{user ? "Edit User" : "Create New User"}</DialogTitle>
<DialogTitle>{user ? 'Edit User' : 'Create New User'}</DialogTitle>
</DialogHeader>
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
<div className="grid grid-cols-2 gap-4">
<div>
<Label>Username *</Label>
<Input
{...register("username")}
disabled={!!user}
autoComplete="off"
/>
{errors.username && (
<p className="text-sm text-red-500">{errors.username.message}</p>
)}
<Input {...register('username')} disabled={!!user} autoComplete="off" />
{errors.username && <p className="text-sm text-red-500">{errors.username.message}</p>}
</div>
<div>
<Label>Email *</Label>
<Input type="email" {...register("email")} autoComplete="off" />
{errors.email && (
<p className="text-sm text-red-500">{errors.email.message}</p>
)}
<Input type="email" {...register('email')} autoComplete="off" />
{errors.email && <p className="text-sm text-red-500">{errors.email.message}</p>}
</div>
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<Label>First Name *</Label>
<Input {...register("firstName")} autoComplete="off" />
{errors.firstName && (
<p className="text-sm text-red-500">{errors.firstName.message}</p>
)}
<Input {...register('firstName')} autoComplete="off" />
{errors.firstName && <p className="text-sm text-red-500">{errors.firstName.message}</p>}
</div>
<div>
<Label>Last Name *</Label>
<Input {...register("lastName")} autoComplete="off" />
{errors.lastName && (
<p className="text-sm text-red-500">{errors.lastName.message}</p>
)}
<Input {...register('lastName')} autoComplete="off" />
{errors.lastName && <p className="text-sm text-red-500">{errors.lastName.message}</p>}
</div>
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<Label>Line ID</Label>
<Input {...register("lineId")} autoComplete="off" />
<Input {...register('lineId')} autoComplete="off" />
</div>
<div>
<Label>Primary Organization</Label>
<Select
value={watch("primaryOrganizationId") || ALL_ORGANIZATIONS_VALUE}
onValueChange={(val) =>
setValue("primaryOrganizationId", val)
}
value={watch('primaryOrganizationId') || ALL_ORGANIZATIONS_VALUE}
onValueChange={(val) => setValue('primaryOrganizationId', val)}
>
<SelectTrigger>
<SelectValue placeholder="Select Organization" />
</SelectTrigger>
<SelectContent>
<SelectItem value={ALL_ORGANIZATIONS_VALUE}>All Organizations</SelectItem>
{Array.isArray(organizations) && organizations.map((org: { uuid: string; organizationCode: string; organizationName: string }) => (
<SelectItem
key={org.uuid}
value={org.uuid}
>
{org.organizationCode} - {org.organizationName}
</SelectItem>
))}
{Array.isArray(organizations) &&
organizations.map((org: { uuid: string; organizationCode: string; organizationName: string }) => (
<SelectItem key={org.uuid} value={org.uuid}>
{org.organizationCode} - {org.organizationName}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
@@ -261,91 +243,88 @@ export function UserDialog({ open, onOpenChange, user }: UserDialogProps) {
{/* Password Section - Show for Create, or Optional for Edit */}
<div className="space-y-4 border p-4 rounded-md">
<h3 className="text-sm font-medium">{user ? "Change Password (Optional)" : "Password Setup"}</h3>
<h3 className="text-sm font-medium">{user ? 'Change Password (Optional)' : 'Password Setup'}</h3>
<div className="grid grid-cols-2 gap-4">
<div className="grid grid-cols-2 gap-4">
<div className="relative">
<Label>Password {user ? '' : '*'}</Label>
<div className="relative">
<Label>Password {user ? "" : "*"}</Label>
<div className="relative">
<Input
type={showPassword ? "text" : "password"}
{...register("password")}
autoComplete="new-password"
/>
<Button
type="button"
variant="ghost"
size="icon"
className="absolute right-0 top-0 h-full px-3"
onClick={() => setShowPassword(!showPassword)}
>
{showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
</Button>
</div>
{errors.password && (
<p className="text-sm text-red-500">{errors.password.message}</p>
)}
<Input
type={showPassword ? 'text' : 'password'}
{...register('password')}
autoComplete="new-password"
/>
<Button
type="button"
variant="ghost"
size="icon"
className="absolute right-0 top-0 h-full px-3"
onClick={() => setShowPassword(!showPassword)}
>
{showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
</Button>
</div>
{errors.password && <p className="text-sm text-red-500">{errors.password.message}</p>}
</div>
<div className="relative">
<Label>Confirm Password {user ? "" : "*"}</Label>
<div className="relative">
<Input
type={showConfirmPassword ? "text" : "password"}
{...register("confirmPassword")}
autoComplete="new-password"
/>
<Button
type="button"
variant="ghost"
size="icon"
className="absolute right-0 top-0 h-full px-3"
onClick={() => setShowConfirmPassword(!showConfirmPassword)}
>
{showConfirmPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
</Button>
</div>
{errors.confirmPassword && (
<p className="text-sm text-red-500">{errors.confirmPassword.message}</p>
)}
<div className="relative">
<Label>Confirm Password {user ? '' : '*'}</Label>
<div className="relative">
<Input
type={showConfirmPassword ? 'text' : 'password'}
{...register('confirmPassword')}
autoComplete="new-password"
/>
<Button
type="button"
variant="ghost"
size="icon"
className="absolute right-0 top-0 h-full px-3"
onClick={() => setShowConfirmPassword(!showConfirmPassword)}
>
{showConfirmPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
</Button>
</div>
</div>
{errors.confirmPassword && <p className="text-sm text-red-500">{errors.confirmPassword.message}</p>}
</div>
</div>
</div>
<div>
<Label className="mb-3 block">Roles</Label>
<div className="space-y-2 border p-3 rounded-md max-h-[200px] overflow-y-auto">
{Array.isArray(roles) && roles.length === 0 && <p className="text-sm text-muted-foreground">Loading roles...</p>}
{Array.isArray(roles) && roles.map((role: { roleId: number; roleName: string; description?: string }) => (
<div key={role.roleId} className="flex items-start space-x-2">
<Checkbox
id={`role-${role.roleId}`}
checked={selectedRoleIds.includes(role.roleId)}
onCheckedChange={(checked) => {
const current = selectedRoleIds;
if (checked) {
setValue("roleIds", [...current, role.roleId]);
} else {
setValue(
"roleIds",
current.filter((id) => id !== role.roleId)
);
}
}}
/>
<div className="grid gap-1.5 leading-none">
<label
htmlFor={`role-${role.roleId}`}
className="text-sm font-medium leading-none cursor-pointer"
>
{role.roleName}
</label>
<p className="text-xs text-muted-foreground">
{role.description}
</p>
{Array.isArray(roles) && roles.length === 0 && (
<p className="text-sm text-muted-foreground">Loading roles...</p>
)}
{Array.isArray(roles) &&
roles.map((role: { roleId: number; roleName: string; description?: string }) => (
<div key={role.roleId} className="flex items-start space-x-2">
<Checkbox
id={`role-${role.roleId}`}
checked={selectedRoleIds.includes(role.roleId)}
onCheckedChange={(checked) => {
const current = selectedRoleIds;
if (checked) {
setValue('roleIds', [...current, role.roleId]);
} else {
setValue(
'roleIds',
current.filter((id) => id !== role.roleId)
);
}
}}
/>
<div className="grid gap-1.5 leading-none">
<label
htmlFor={`role-${role.roleId}`}
className="text-sm font-medium leading-none cursor-pointer"
>
{role.roleName}
</label>
<p className="text-xs text-muted-foreground">{role.description}</p>
</div>
</div>
</div>
))}
))}
</div>
</div>
@@ -353,31 +332,21 @@ export function UserDialog({ open, onOpenChange, user }: UserDialogProps) {
<div className="flex items-center space-x-2">
<Checkbox
id="is_active"
checked={watch("isActive")}
onCheckedChange={(chk) => setValue("isActive", chk === true)}
checked={watch('isActive')}
onCheckedChange={(chk) => setValue('isActive', chk === true)}
/>
<label
htmlFor="is_active"
className="text-sm font-medium leading-none cursor-pointer"
>
<label htmlFor="is_active" className="text-sm font-medium leading-none cursor-pointer">
Active User
</label>
</div>
)}
<div className="flex justify-end gap-3 pt-4">
<Button
type="button"
variant="outline"
onClick={() => onOpenChange(false)}
>
<Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
Cancel
</Button>
<Button
type="submit"
disabled={createUser.isPending || updateUser.isPending}
>
{user ? "Update User" : "Create User"}
<Button type="submit" disabled={createUser.isPending || updateUser.isPending}>
{user ? 'Update User' : 'Create User'}
</Button>
</div>
</form>