updated living space added

This commit is contained in:
2025-12-04 15:46:24 +03:00
parent 56b42bb906
commit 53e1f1e4fc
70 changed files with 1128 additions and 824 deletions

View File

@@ -12,7 +12,7 @@ import { useUpdateUserMutation } from "@/pages/users/update/queries"
import { userUpdateSchema, type UserUpdate } from "@/pages/users/update/schema"
import PageAddUserSelections from "../selections/addPage"
const UserForm = ({ refetchTable, initData, selectedUuid }: { refetchTable: () => void, initData: UserUpdate, selectedUuid: string }) => {
const UserForm = ({ refetchTable, initData, selectedUuid }: { refetchTable: () => void, initData: any, selectedUuid: string }) => {
const form = useForm<UserUpdate>({
resolver: zodResolver(userUpdateSchema),
@@ -28,10 +28,10 @@ const UserForm = ({ refetchTable, initData, selectedUuid }: { refetchTable: () =
})
const { handleSubmit } = form
const [defaultSelection, setDefaultSelection] = useState<string>("")
const [selectedBuildIDS, setSelectedBuildIDS] = useState<string[]>([])
const [selectedCompanyIDS, setSelectedCompanyIDS] = useState<string[]>([])
const [defaultSelection, setDefaultSelection] = useState<string>(initData.collectionTokens.defaultSelection)
const [selectedBuildIDS, setSelectedBuildIDS] = useState<string[]>(initData.collectionTokens.selectedBuildIDS)
const [selectedCompanyIDS, setSelectedCompanyIDS] = useState<string[]>(initData.collectionTokens.selectedCompanyIDS)
const [personID, setPersonID] = useState<string>(initData.person)
const appendBuildID = (id: string) => setSelectedBuildIDS((prev) => (id && !selectedBuildIDS.includes(id) ? [...prev, id] : prev))
const appendCompanyID = (id: string) => setSelectedCompanyIDS((prev) => (id && !selectedCompanyIDS.includes(id) ? [...prev, id] : prev))
@@ -40,12 +40,12 @@ const UserForm = ({ refetchTable, initData, selectedUuid }: { refetchTable: () =
const removeCompanyID = (id: string) => setSelectedCompanyIDS((prev) => prev.filter((item) => item !== id))
const mutation = useUpdateUserMutation();
function onSubmit(values: UserUpdate) { mutation.mutate({ data: values as any || initData, uuid: selectedUuid, selectedBuildIDS, selectedCompanyIDS, defaultSelection, refetchTable }); setTimeout(() => refetchTable(), 400) }
function onSubmit(values: UserUpdate) { mutation.mutate({ data: values as any || initData, uuid: selectedUuid, selectedBuildIDS, selectedCompanyIDS, defaultSelection, personID, refetchTable }) }
return (
<div>
<PageAddUserSelections
selectedCompanyIDS={selectedCompanyIDS} selectedBuildingIDS={selectedBuildIDS} appendCompanyID={appendCompanyID} appendBuildingID={appendBuildID}
selectedCompanyIDS={selectedCompanyIDS} selectedBuildingIDS={selectedBuildIDS} appendCompanyID={appendCompanyID} appendBuildingID={appendBuildID} personID={personID} setPersonID={setPersonID}
removeCompanyID={removeCompanyID} removeBuildingID={removeBuildID} defaultSelection={defaultSelection} setDefaultSelection={setDefaultSelection}
/>
<Form {...form}>
@@ -82,33 +82,6 @@ const UserForm = ({ refetchTable, initData, selectedUuid }: { refetchTable: () =
{/* PASSWORD / TAG */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<FormField
control={form.control}
name="password"
render={({ field }) => (
<FormItem>
<FormLabel>Password</FormLabel>
<FormControl>
<Input type="password" placeholder="•••••••" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="rePassword"
render={({ field }) => (
<FormItem>
<FormLabel>Re-Password</FormLabel>
<FormControl>
<Input type="password" placeholder="•••••••" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="tag"
@@ -188,7 +161,7 @@ const UserForm = ({ refetchTable, initData, selectedUuid }: { refetchTable: () =
</div>
<Separator />
<Button type="submit" className="w-full">Create User</Button>
<Button type="submit" className="w-full">Update User</Button>
</form>
</Form>
</div>

View File

@@ -24,20 +24,10 @@ const PageUpdateUser = () => {
const { data, isLoading, error, refetch } = useGraphQlUsersList({ limit, skip: (page - 1) * limit, sort, filters: { ...filters, uuid } });
const initData = data?.data?.[0] || null;
if (!initData) {
return <>
<div>Selected User is either deleted or not found</div>
<Button onClick={() => router.push('/users')}>Back to Users</Button>
</>
}
if (!initData) { return <><div>Selected User is either deleted or not found</div><Button onClick={() => router.push('/users')}>Back to Users</Button></> }
return (
<>
<UserDataTableUpdate
data={data?.data || []} totalCount={data?.totalCount || 0} currentPage={page} pageSize={limit}
onPageChange={setPage} onPageSizeChange={setLimit} refetchTable={refetch}
/>
<UserDataTableUpdate data={data?.data || []} totalCount={data?.totalCount || 0} currentPage={page} pageSize={limit} onPageChange={setPage} onPageSizeChange={setLimit} refetchTable={refetch} />
<UserForm refetchTable={refetch} initData={initData} selectedUuid={uuid} />
</>
)

View File

@@ -1,13 +1,17 @@
'use client'
import { useMutation } from '@tanstack/react-query'
import { UserUpdate } from './types';
import { UserUpdate } from './schema';
import { toISOIfNotZ } from '@/lib/utils';
const fetchGraphQlUsersUpdate = async (record: UserUpdate, uuid: string, selectedBuildIDS: string[], selectedCompanyIDS: string[], defaultSelection: string, refetchTable: () => void): Promise<{ data: UserUpdate | null; status: number }> => {
const fetchGraphQlUsersUpdate = async (record: UserUpdate, uuid: string, selectedBuildIDS: string[], selectedCompanyIDS: string[], defaultSelection: string, personID: string, refetchTable: () => void): Promise<{ data: UserUpdate | null; status: number }> => {
console.log('Fetching test data from local API');
record.expiryStarts = record?.expiryStarts ? toISOIfNotZ(record.expiryStarts) : undefined;
record.expiryEnds = record?.expiryEnds ? toISOIfNotZ(record.expiryEnds) : undefined;
const payload = { ...record, person: personID, collectionTokens: { defaultSelection, selectedBuildIDS, selectedCompanyIDS } }
try {
const res = await fetch(`/api/users/update?uuid=${uuid || ''}`, { method: 'POST', cache: 'no-store', credentials: "include", body: JSON.stringify({ ...record, selectedBuildIDS, selectedCompanyIDS, defaultSelection }) });
const res = await fetch(`/api/users/update?uuid=${uuid || ''}`, { method: 'POST', cache: 'no-store', credentials: "include", body: JSON.stringify(payload) });
if (!res.ok) { const errorText = await res.text(); console.error('Test data API error:', errorText); throw new Error(`API error: ${res.status} ${res.statusText}`) }
const data = await res.json();
const data = await res.json(); refetchTable();
return { data: data.data, status: res.status }
} catch (error) { console.error('Error fetching test data:', error); throw error }
};
@@ -15,8 +19,8 @@ const fetchGraphQlUsersUpdate = async (record: UserUpdate, uuid: string, selecte
export function useUpdateUserMutation() {
return useMutation({
mutationFn: (
{ data, uuid, selectedBuildIDS, selectedCompanyIDS, defaultSelection, refetchTable }: { data: UserUpdate, uuid: string, selectedBuildIDS: string[], selectedCompanyIDS: string[], defaultSelection: string, refetchTable: () => void }
) => fetchGraphQlUsersUpdate(data, uuid, selectedBuildIDS, selectedCompanyIDS, defaultSelection, refetchTable),
{ data, uuid, selectedBuildIDS, selectedCompanyIDS, defaultSelection, personID, refetchTable }: { data: UserUpdate, uuid: string, selectedBuildIDS: string[], selectedCompanyIDS: string[], defaultSelection: string, personID: string, refetchTable: () => void }
) => fetchGraphQlUsersUpdate(data, uuid, selectedBuildIDS, selectedCompanyIDS, defaultSelection, personID, refetchTable),
onSuccess: () => { console.log("User updated successfully") },
onError: (error) => { console.error("Update user failed:", error) },
})

View File

@@ -8,8 +8,8 @@ export const userUpdateSchema = z.object({
isConfirmed: z.boolean(),
isNotificationSend: z.boolean(),
password: z.string().min(6),
rePassword: z.string().min(6),
// password: z.string().min(6),
// rePassword: z.string().min(6),
tag: z.string().optional(),
email: z.string().email(),
phone: z.string().min(5),

View File

@@ -24,7 +24,7 @@ export function DraggableRow({ row }: { row: Row<z.infer<typeof schema>> }) {
)
}
function getColumns(router: any, deleteHandler: (id: string) => void): ColumnDef<schemaType>[] {
function getColumns(deleteHandler: (id: string) => void): ColumnDef<schemaType>[] {
return [
{
accessorKey: "uuid",
@@ -32,48 +32,26 @@ function getColumns(router: any, deleteHandler: (id: string) => void): ColumnDef
cell: ({ getValue }) => (<div className="font-mono text-xs bg-muted px-2 py-1 rounded break-all">{String(getValue())}</div>),
},
{
accessorKey: "firstName",
header: "First Name",
accessorKey: "email",
header: "Email",
},
{
accessorKey: "surname",
header: "Surname",
accessorKey: "phone",
header: "Phone",
},
{
accessorKey: "middleName",
header: "Middle Name",
accessorKey: "tag",
header: "Tag",
},
{
accessorKey: "sexCode",
header: "Sex",
accessorKey: "isNotificationSend",
header: "Notificated?",
cell: ({ getValue }) => getValue() ? (<div className="text-green-600 font-medium">Yes</div>) : (<div className="text-red-600 font-medium">No</div>),
},
{
accessorKey: "personRef",
header: "Person Ref",
},
{
accessorKey: "personTag",
header: "Person Tag",
},
{
accessorKey: "fatherName",
header: "Father Name",
},
{
accessorKey: "motherName",
header: "Mother Name",
},
{
accessorKey: "countryCode",
header: "Country",
},
{
accessorKey: "nationalIdentityId",
header: "National ID",
},
{
accessorKey: "birthPlace",
header: "Birth Place",
accessorKey: "isEmailSend",
header: "Email Send?",
cell: ({ getValue }) => getValue() ? (<div className="text-green-600 font-medium">Yes</div>) : (<div className="text-red-600 font-medium">No</div>),
},
{
accessorKey: "active",
@@ -86,9 +64,9 @@ function getColumns(router: any, deleteHandler: (id: string) => void): ColumnDef
cell: ({ getValue }) => getValue() ? (<div className="text-green-600 font-medium">Yes</div>) : (<div className="text-red-600 font-medium">No</div>),
},
{
accessorKey: "birthDate",
header: "Birth Date",
cell: ({ getValue }) => dateToLocaleString(getValue() as string),
accessorKey: "deleted",
header: "Deleted",
cell: ({ getValue }) => getValue() ? (<div className="text-red-600 font-medium">Yes</div>) : (<div className="text-green-600 font-medium">No</div>),
},
{
accessorKey: "createdAt",
@@ -110,15 +88,36 @@ function getColumns(router: any, deleteHandler: (id: string) => void): ColumnDef
header: "Expiry Ends",
cell: ({ getValue }) => getValue() ? dateToLocaleString(getValue() as string) : "-",
},
{
accessorKey: "collectionTokens.tokens",
header: "Default Token",
cell: ({ row }) => {
const defaultToken = row.original.collectionTokens?.defaultSelection;
return defaultToken ? <div><div className="flex flex-col w-full"><span className="font-mono text-xs text-muted-foreground break-all">{defaultToken}</span></div></div> : <div>No Default Token</div>;
},
},
{
accessorKey: "collectionTokens.selectedBuildIDS",
header: "Selected Build IDS",
cell: ({ row }) => {
const selectedBuildIDS = row.original.collectionTokens?.selectedBuildIDS;
return selectedBuildIDS && <div><div className="flex flex-col w-full"><span className="font-mono text-xs text-muted-foreground break-all">{selectedBuildIDS.length}</span></div></div>;
},
},
{
accessorKey: "collectionTokens.selectedCompanyIDS",
header: "Selected Company IDS",
cell: ({ row }) => {
const selectedCompanyIDS = row.original.collectionTokens?.selectedCompanyIDS;
return selectedCompanyIDS && <div><div className="flex flex-col w-full"><span className="font-mono text-xs text-muted-foreground break-all">{selectedCompanyIDS.length}</span></div></div>;
},
},
{
id: "actions",
header: "Actions",
cell: ({ row }) => {
return (
<div>
<Button className="bg-amber-400 text-black border-amber-400" variant="outline" size="sm" onClick={() => { router.push(`/users/update?uuid=${row.original.uuid}`) }}>
<Pencil />
</Button>
<Button className="bg-red-700 text-white border-red-700 mx-4" variant="outline" size="sm" onClick={() => { deleteHandler(row.original.uuid || "") }}>
<Trash />
</Button>

View File

@@ -100,7 +100,7 @@ export function UserDataTableUpdate({
const dataIds = React.useMemo<UniqueIdentifier[]>(() => data?.map(({ _id }) => _id) || [], [data])
const deleteMutation = useDeleteUserMutation()
const deleteHandler = (id: string) => { deleteMutation.mutate({ uuid: id }); setTimeout(() => { refetchTable() }, 400) }
const deleteHandler = (id: string) => { deleteMutation.mutate({ uuid: id, refetchTable }) }
const columns = getColumns(router, deleteHandler);
const pagination = React.useMemo(() => ({ pageIndex: currentPage - 1, pageSize: pageSize, }), [currentPage, pageSize])
const totalPages = Math.ceil(totalCount / pageSize)

View File

@@ -2,46 +2,23 @@ import { z } from "zod";
export const schema = z.object({
_id: z.string(),
uuid: z.string().nullable().optional(),
expiryStarts: z.string().nullable().optional(),
expiryEnds: z.string().nullable().optional(),
isConfirmed: z.boolean().nullable().optional(),
deleted: z.boolean().nullable().optional(),
active: z.boolean().nullable().optional(),
crypUuId: z.string().nullable().optional(),
createdCredentialsToken: z.string().nullable().optional(),
updatedCredentialsToken: z.string().nullable().optional(),
confirmedCredentialsToken: z.string().nullable().optional(),
isNotificationSend: z.boolean().nullable().optional(),
isEmailSend: z.boolean().nullable().optional(),
refInt: z.number().nullable().optional(),
refId: z.string().nullable().optional(),
replicationId: z.number().nullable().optional(),
expiresAt: z.string().nullable().optional(),
resetToken: z.string().nullable().optional(),
password: z.string().nullable().optional(),
history: z.array(z.string()).optional(),
tag: z.string().nullable().optional(),
email: z.string().nullable().optional(),
phone: z.string().nullable().optional(),
collectionTokens: z
.object({
default: z.string().nullable().optional(),
tokens: z
.array(
z.object({
prefix: z.string(),
token: z.string(),
})
)
.optional(),
})
.nullable()
.optional(),
createdAt: z.string().nullable().optional(),
updatedAt: z.string().nullable().optional(),
uuid: z.string(),
expiryStarts: z.string(),
expiryEnds: z.string(),
isConfirmed: z.boolean(),
deleted: z.boolean(),
active: z.boolean(),
isNotificationSend: z.boolean(),
isEmailSend: z.boolean(),
expiresAt: z.string(),
tag: z.string(),
email: z.string(),
phone: z.string().optional(),
collectionTokens: z.object({
defaultSelection: z.string().nullable().optional(), selectedBuildIDS: z.array(z.string()).optional(), selectedCompanyIDS: z.array(z.string()).optional()
}).nullable().optional(),
createdAt: z.string(),
updatedAt: z.string(),
});
export type schemaType = z.infer<typeof schema>;