updated build

This commit is contained in:
2025-11-29 16:57:17 +03:00
parent d22fc017df
commit 0394d42d02
28 changed files with 1502 additions and 551 deletions

View File

@@ -1,5 +1,6 @@
"use client"
import { useFieldArray, useForm } from "react-hook-form"
import { useState, useEffect } from "react"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { userAddSchema, type UserAdd } from "./schema"
import { Form, FormField, FormItem, FormLabel, FormControl, FormMessage } from "@/components/ui/form"
@@ -9,6 +10,7 @@ import { Checkbox } from "@/components/ui/checkbox"
import { Separator } from "@/components/ui/separator"
import { useAddUserMutation } from "./queries"
import { DateTimePicker } from "@/components/ui/date-time-picker"
import PageAddUserSelections from "../selections/addPage"
const UserForm = ({ refetchTable }: { refetchTable: () => void }) => {
const form = useForm<UserAdd>({
@@ -22,258 +24,174 @@ const UserForm = ({ refetchTable }: { refetchTable: () => void }) => {
rePassword: "",
tag: "",
email: "",
phone: "",
collectionTokens: {
default: "",
tokens: [],
},
phone: ""
},
})
const { control, handleSubmit } = form
const [defaultSelection, setDefaultSelection] = useState<string>("")
const [selectedBuildIDS, setSelectedBuildIDS] = useState<string[]>([])
const [selectedCompanyIDS, setSelectedCompanyIDS] = useState<string[]>([])
const { fields, append, remove } = useFieldArray({ control, name: "collectionTokens.tokens" })
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))
const removeBuildID = (id: string) => setSelectedBuildIDS((prev) => prev.filter((item) => item !== id))
const removeCompanyID = (id: string) => setSelectedCompanyIDS((prev) => prev.filter((item) => item !== id))
const { handleSubmit } = form
const mutation = useAddUserMutation();
function onSubmit(values: UserAdd) { mutation.mutate(values as any); setTimeout(() => refetchTable(), 400) }
function onSubmit(values: UserAdd) { mutation.mutate({ data: values as any, selectedBuildIDS, selectedCompanyIDS, defaultSelection, refetchTable }); }
return (
<Form {...form}>
<form onSubmit={handleSubmit(onSubmit)} className="space-y-6 p-4">
{/* BASIC INFO */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<FormField
control={form.control}
name="email"
render={({ field }) => (
<FormItem>
<FormLabel>Email</FormLabel>
<FormControl>
<Input placeholder="user@example.com" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="phone"
render={({ field }) => (
<FormItem>
<FormLabel>Phone</FormLabel>
<FormControl>
<Input placeholder="+901234567" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
{/* 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"
render={({ field }) => (
<FormItem>
<FormLabel>Tag</FormLabel>
<FormControl>
<Input placeholder="User tag..." {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
{/* DATES */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<FormField
control={form.control}
name="expiryStarts"
render={({ field }) => (
<FormItem>
<FormLabel>Expiry Starts</FormLabel>
<FormControl>
<DateTimePicker {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="expiryEnds"
render={({ field }) => (
<FormItem>
<FormLabel>Expiry Ends</FormLabel>
<FormControl>
<DateTimePicker {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
{/* SWITCHES */}
<div className="flex items-center gap-6">
<FormField
control={form.control}
name="isConfirmed"
render={({ field }) => (
<FormItem className="flex items-center gap-2">
<FormControl>
<Checkbox
checked={field.value}
onCheckedChange={field.onChange}
/>
</FormControl>
<FormLabel className="mt-0!">Confirmed</FormLabel>
</FormItem>
)}
/>
<FormField
control={form.control}
name="isNotificationSend"
render={({ field }) => (
<FormItem className="flex items-center gap-2">
<FormControl>
<Checkbox
checked={field.value}
onCheckedChange={field.onChange}
/>
</FormControl>
<FormLabel className="mt-0!">Send Notification</FormLabel>
</FormItem>
)}
/>
</div>
<Separator />
{/* COLLECTION TOKENS */}
<FormField
control={form.control}
name="collectionTokens.default"
render={({ field }) => (
<FormItem>
<FormLabel>Default Token</FormLabel>
<FormControl>
<Input placeholder="Default token..." {...field} />
</FormControl>
</FormItem>
)}
/>
<div className="space-y-3">
<div className="flex justify-between items-center">
<FormLabel>Tokens</FormLabel>
<Button
type="button"
variant="outline"
size="sm"
onClick={() => append({ prefix: "", token: "" })}
>
+ Add Token
</Button>
<div>
<PageAddUserSelections
selectedCompanyIDS={selectedCompanyIDS} selectedBuildingIDS={selectedBuildIDS} appendCompanyID={appendCompanyID} appendBuildingID={appendBuildID}
removeCompanyID={removeCompanyID} removeBuildingID={removeBuildID} defaultSelection={defaultSelection} setDefaultSelection={setDefaultSelection}
/>
<Form {...form}>
<form onSubmit={handleSubmit(onSubmit)} className="space-y-6 p-4">
{/* BASIC INFO */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<FormField
control={form.control}
name="email"
render={({ field }) => (
<FormItem>
<FormLabel>Email</FormLabel>
<FormControl>
<Input placeholder="user@example.com" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="phone"
render={({ field }) => (
<FormItem>
<FormLabel>Phone</FormLabel>
<FormControl>
<Input placeholder="+901234567" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
{fields.length === 0 && (
<p className="text-sm text-muted-foreground">No tokens added.</p>
)}
{/* 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>
)}
/>
{fields.map((fieldItem, i) => (
<div
key={fieldItem.id}
className="grid grid-cols-12 gap-2 items-end"
>
<div className="col-span-4">
<FormField
control={form.control}
name={`collectionTokens.tokens.${i}.prefix`}
render={({ field }) => (
<FormItem>
<FormLabel>Prefix</FormLabel>
<FormControl>
<Input placeholder="prefix" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
<div className="col-span-6">
<FormField
control={form.control}
name={`collectionTokens.tokens.${i}.token`}
render={({ field }) => (
<FormItem>
<FormLabel>Token</FormLabel>
<FormControl>
<Input placeholder="token" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
<Button
type="button"
variant="destructive"
size="icon"
className="col-span-2 h-10"
onClick={() => remove(i)}
>
</Button>
<FormField
control={form.control}
name="tag"
render={({ field }) => (
<FormItem>
<FormLabel>Tag</FormLabel>
<FormControl>
<Input placeholder="User tag..." {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
{/* SWITCHES */}
<div className="flex items-center gap-6">
<FormField
control={form.control}
name="isConfirmed"
render={({ field }) => (
<FormItem className="flex items-center gap-2">
<FormControl>
<Checkbox
checked={field.value}
onCheckedChange={field.onChange}
/>
</FormControl>
<FormLabel className="mt-0!">Confirmed</FormLabel>
</FormItem>
)}
/>
<FormField
control={form.control}
name="isNotificationSend"
render={({ field }) => (
<FormItem className="flex items-center gap-2">
<FormControl>
<Checkbox
checked={field.value}
onCheckedChange={field.onChange}
/>
</FormControl>
<FormLabel className="mt-0!">Send Notification</FormLabel>
</FormItem>
)}
/>
</div>
))}
</div>
</div>
<Separator />
{/* DATES */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<FormField
control={form.control}
name="expiryStarts"
render={({ field }) => (
<FormItem>
<FormLabel>Expiry Starts</FormLabel>
<FormControl>
<DateTimePicker {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="expiryEnds"
render={({ field }) => (
<FormItem>
<FormLabel>Expiry Ends</FormLabel>
<FormControl>
<DateTimePicker {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
<Button type="submit" className="w-full">
Create User
</Button>
</form>
</Form>
<Separator />
<Button type="submit" className="w-full">Create User</Button>
</form>
</Form>
</div>
)
}

View File

@@ -3,21 +3,29 @@ import { useMutation } from '@tanstack/react-query'
import { UserAdd } from './types'
import { toISOIfNotZ } from '@/lib/utils'
const fetchGraphQlUsersAdd = async (record: UserAdd): Promise<{ data: UserAdd | null; status: number }> => {
console.log('Fetching test data from local API');
const fetchGraphQlUsersAdd = async (
record: UserAdd,
selectedBuildIDS: string[],
selectedCompanyIDS: string[],
defaultSelection: string,
refetchTable: () => void
): Promise<{ data: UserAdd | null; status: number }> => {
record.expiryStarts = toISOIfNotZ(record.expiryStarts);
record.expiryEnds = toISOIfNotZ(record.expiryEnds);
try {
const res = await fetch('/api/users/add', { method: 'POST', cache: 'no-store', credentials: "include", body: JSON.stringify(record) });
const res = await fetch('/api/users/add', { method: 'POST', cache: 'no-store', credentials: "include", body: JSON.stringify({ ...record, selectedBuildIDS, selectedCompanyIDS, defaultSelection }) });
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();
refetchTable();
return { data: data.data, status: res.status }
} catch (error) { console.error('Error fetching test data:', error); throw error }
};
export function useAddUserMutation() {
return useMutation({
mutationFn: (data: UserAdd) => fetchGraphQlUsersAdd(data),
mutationFn: (
{ data, selectedBuildIDS, selectedCompanyIDS, defaultSelection, refetchTable }: { data: UserAdd, selectedBuildIDS: string[], selectedCompanyIDS: string[], defaultSelection: string, refetchTable: () => void }
) => fetchGraphQlUsersAdd(data, selectedBuildIDS, selectedCompanyIDS, defaultSelection, refetchTable),
onSuccess: () => { console.log("User created successfully") },
onError: (error) => { console.error("Create user failed:", error) },
})

View File

@@ -1,14 +1,5 @@
import { z } from "zod"
export const tokenSchema = z.object({
prefix: z.string().min(1, "Prefix is required"),
token: z.string().min(1, "Token is required"),
})
export const collectionTokensSchema = z.object({
default: z.string().optional(),
tokens: z.array(tokenSchema)
})
export const userAddSchema = z.object({
expiryStarts: z.string().optional(),
@@ -23,7 +14,6 @@ export const userAddSchema = z.object({
email: z.string().email(),
phone: z.string().min(5),
collectionTokens: collectionTokensSchema,
})
export type UserAdd = z.infer<typeof userAddSchema>

View File

@@ -17,7 +17,6 @@ interface UserAdd {
tag: string;
email: string;
phone: string;
collectionTokens: CollectionTokens;
}