mirror of
https://github.com/ichsankurnia/hats-app.git
synced 2026-12-05 10:56:28 +00:00
ffcf3c6e58
This commit reorganizes client and project-assignment screens into dedicated grid/list components, adds a shared layout toggle via the URL query string, and updates task pages to render the selected view consistently. It also moves shared client form logic into a client folder, improves status badge formatting, extends LazyImage with custom image classes, and updates the illustration assets and Lucide dependency used in the task UI.
274 lines
14 KiB
TypeScript
274 lines
14 KiB
TypeScript
import { useCallback, useRef, useState, type FC } from 'react';
|
|
import {
|
|
AlertDialog, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle
|
|
} from "@/components/ui/alert-dialog"
|
|
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage, } from "@/components/ui/form";
|
|
import * as Yup from 'yup'
|
|
import { yupResolver } from '@hookform/resolvers/yup';
|
|
import { IClient } from '../../types';
|
|
import { useForm } from 'react-hook-form';
|
|
import { toast } from 'sonner';
|
|
import { Button } from '@/components/ui/button';
|
|
import { ImageIcon, Loader2, UploadIcon } from 'lucide-react';
|
|
import { Input } from '@/components/ui/input';
|
|
import { useRouter } from 'next/navigation';
|
|
import Dropzone from 'react-dropzone';
|
|
import { LazyImage } from '@/components/ui/lazy-image';
|
|
import { Label } from '@/components/ui/label';
|
|
import { serverApiCall } from '@/lib/server-api';
|
|
import { Textarea } from '@/components/ui/textarea';
|
|
|
|
const validationSchema = Yup.object().shape({
|
|
name: Yup.string().required(),
|
|
// end_user_id: Yup.number().required(),
|
|
description: Yup.string().optional().default(''),
|
|
});
|
|
|
|
type FormDataType = Yup.InferType<typeof validationSchema>;
|
|
|
|
type Props = {
|
|
data?: IClient
|
|
isRedirectToDetail?: boolean
|
|
onCancel?: VoidFunction
|
|
onSuccess?: VoidFunction;
|
|
};
|
|
|
|
const FormClient: FC<Props> = ({ data, onSuccess, onCancel, isRedirectToDetail }) => {
|
|
const [isLoading, setIsLoading] = useState(false)
|
|
const [currentFile, setCurrentFile] = useState<any | undefined>(undefined);
|
|
|
|
|
|
const existFile = data?.photo || null
|
|
const dropzoneRef = useRef<any>(null);
|
|
const maxSizeMB = 5
|
|
|
|
const openDialog = () => {
|
|
if (dropzoneRef.current) {
|
|
dropzoneRef.current.open();
|
|
}
|
|
};
|
|
|
|
const onDrop = useCallback((acceptedFiles: any[]) => {
|
|
acceptedFiles.forEach(async (file: any) => {
|
|
const reader = new FileReader();
|
|
|
|
reader.onabort = () => console.log('file reading was aborted');
|
|
reader.onerror = () => console.log('file reading has failed');
|
|
reader.onload = async () => {
|
|
// Do whatever you want with the file contents
|
|
const binaryStr = reader.result;
|
|
|
|
console.log(file)
|
|
setCurrentFile({ file: file, base64: binaryStr?.toString() });
|
|
};
|
|
reader.readAsDataURL(file);
|
|
});
|
|
}, []);
|
|
|
|
const router = useRouter()
|
|
|
|
const form = useForm<FormDataType>({
|
|
resolver: yupResolver(validationSchema),
|
|
defaultValues: {
|
|
"name": data?.name || '',
|
|
// "end_user_id": data?.end_user_id || undefined,
|
|
"description": data?.description || '',
|
|
},
|
|
});
|
|
|
|
const handleUploadFile = async () => {
|
|
setIsLoading(true)
|
|
const toastId = toast.loading('Uploading image...');
|
|
let fullPathImage = ''
|
|
|
|
try {
|
|
const resPresignUrl: any = await serverApiCall('POST', '/s3', {
|
|
"filename": currentFile?.file?.name,
|
|
"type": currentFile?.file?.type,
|
|
"bucket": "hats-client"
|
|
})
|
|
|
|
console.log({ resPresignUrl })
|
|
|
|
if (resPresignUrl.success) {
|
|
fullPathImage = `${process.env.NEXT_PUBLIC_S3_IMAGE_URL}/${resPresignUrl?.data?.data?.path_url}`
|
|
const presignedUrl = resPresignUrl?.data?.data?.upload_url
|
|
|
|
const uploadResponse = await fetch(presignedUrl, {
|
|
method: 'PUT',
|
|
body: currentFile?.file, // Send the raw file directly
|
|
headers: {
|
|
'Content-Type': currentFile?.file?.type,
|
|
},
|
|
});
|
|
|
|
if (!uploadResponse.ok) {
|
|
throw new Error("Failed to upload image to storage 😢");
|
|
}
|
|
} else {
|
|
toast.error("Oops sorry, error has occurred 😢", {
|
|
description: `(${resPresignUrl.code}) ${resPresignUrl.message || "An unexpected error occurred while Getting Presigned URL. Please try again later."}`,
|
|
})
|
|
}
|
|
} catch (error: any) {
|
|
toast.error(`Failed uploading image.\n(${error?.response?.data?.code || error?.response?.status || '-'}) ${error?.response?.data?.message || error?.response?.statusText || error?.message}`);
|
|
} finally {
|
|
setIsLoading(false)
|
|
toast.dismiss(toastId)
|
|
}
|
|
|
|
return fullPathImage
|
|
}
|
|
|
|
const onSubmit = async (payload: FormDataType) => {
|
|
setIsLoading(true);
|
|
|
|
let newPayload: any = { ...payload }
|
|
|
|
if (currentFile?.file) {
|
|
const photoPath = await handleUploadFile()
|
|
newPayload['photo'] = photoPath
|
|
} else {
|
|
newPayload['photo'] = data?.photo
|
|
}
|
|
|
|
let res: any
|
|
if (data) {
|
|
res = await serverApiCall('PUT', `/client/${data.id}`, newPayload)
|
|
} else {
|
|
res = await serverApiCall('POST', '/client', newPayload)
|
|
}
|
|
|
|
setIsLoading(false)
|
|
if (res.success) {
|
|
toast.success('Client saved successfully')
|
|
if (isRedirectToDetail) {
|
|
router.push(`/task/client-detail/${res.data?.data?.id}`)
|
|
} else {
|
|
onSuccess!()
|
|
}
|
|
} else {
|
|
toast.error(`Fail to save client`, { description: `(${res.code || '-'}) ${res.message}` })
|
|
}
|
|
};
|
|
|
|
|
|
return (
|
|
<>
|
|
<AlertDialog open={true}>
|
|
<AlertDialogContent className='max-h-[90vh] overflow-y-auto overflow-x-hidden'>
|
|
<AlertDialogHeader>
|
|
<AlertDialogTitle>Client Information</AlertDialogTitle>
|
|
<AlertDialogDescription>
|
|
Enter the basic details of the client and their end user.
|
|
</AlertDialogDescription>
|
|
</AlertDialogHeader>
|
|
<Form {...form}>
|
|
<form onSubmit={form.handleSubmit(onSubmit)}>
|
|
<div className="grid grid-cols-1 gap-4 mb-6">
|
|
<FormField control={form.control} name='name'
|
|
render={({ field }) => (
|
|
<FormItem>
|
|
<FormLabel>Client Name <span className='text-red-600 font-bold'>*</span></FormLabel>
|
|
<FormControl>
|
|
<Input {...field} placeholder='e.g. PT Telkom Indonesia' />
|
|
</FormControl>
|
|
<FormMessage />
|
|
</FormItem>
|
|
)}
|
|
/>
|
|
{/* <FormField control={form.control} name='end_user_id'
|
|
render={({ field }) => (
|
|
<FormItem>
|
|
<FormLabel>End User <span className='text-red-600 font-bold'>*</span></FormLabel>
|
|
<FormControl>
|
|
<div className="flex gap-4">
|
|
<Combobox title='End User' options={endUserList && endUserList.length > 0 ? endUserList.map((item: any) => ({ label: item.name, value: item.id })) : []} value={field.value} setValue={field.onChange} className='flex-1' />
|
|
<Button type="button" variant="outline" size="icon" className="shrink-0" onClick={() => setShowEndUserForm(true)}>
|
|
<Plus className="w-4 h-4" />
|
|
</Button>
|
|
</div>
|
|
</FormControl>
|
|
<FormMessage />
|
|
</FormItem>
|
|
)}
|
|
/> */}
|
|
<FormField control={form.control} name='description'
|
|
render={({ field }) => (
|
|
<FormItem>
|
|
<FormLabel>Description</FormLabel>
|
|
<FormControl>
|
|
<Textarea {...field} placeholder='Describe a little about the client.' />
|
|
</FormControl>
|
|
<FormMessage />
|
|
</FormItem>
|
|
)}
|
|
/>
|
|
<div className="flex flex-col gap-2">
|
|
<Label>Add Client Image</Label>
|
|
{/* Drop area */}
|
|
<Dropzone ref={dropzoneRef} onDrop={onDrop} multiple={false} noClick noKeyboard
|
|
accept={{ 'image/*': ['.png', '.bmp', '.jpeg', '.jpg', '.webp'] }}
|
|
>
|
|
{/* @ts-ignore */}
|
|
{({ getRootProps, getInputProps, acceptedFiles }) => {
|
|
return (
|
|
<div {...getRootProps()}
|
|
className="border-input data-[dragging=true]:bg-accent/50 has-[input:focus]:border-ring has-[input:focus]:ring-ring/50 relative flex min-h-52 flex-col items-center overflow-hidden rounded-xl border border-dashed p-4 transition-colors not-data-files:justify-center has-[input:focus]:ring-[3px]"
|
|
>
|
|
<input {...getInputProps()} className="sr-only" aria-label="Upload image file" />
|
|
|
|
{currentFile?.base64 || existFile ? (
|
|
<div className="flex w-full flex-col gap-3">
|
|
<div className="flex items-center justify-between gap-2">
|
|
<h3 className="truncate text-sm font-medium">
|
|
Current Image
|
|
</h3>
|
|
<Button type='button' variant="outline" size="sm" onClick={openDialog}>
|
|
<UploadIcon className="-ms-0.5 size-3.5 opacity-60" aria-hidden="true" />
|
|
Change Image
|
|
</Button>
|
|
</div>
|
|
|
|
<div className="grid grid-cols-1 my-4">
|
|
<LazyImage src={currentFile?.base64 || existFile} alt='gambar-campaign' className="size-full rounded-[inherit] object-cover" />
|
|
</div>
|
|
</div>
|
|
) : (
|
|
<div className="flex flex-col items-center justify-center px-4 py-3 text-center">
|
|
<div className="bg-background mb-2 flex size-11 shrink-0 items-center justify-center rounded-full border" aria-hidden="true">
|
|
<ImageIcon className="size-4 opacity-60" />
|
|
</div>
|
|
<p className="mb-1.5 text-sm font-medium">Drop your files here</p>
|
|
<p className="text-muted-foreground text-xs">
|
|
SVG, PNG, JPG or GIF (max. {maxSizeMB}MB)
|
|
</p>
|
|
<Button type='button' variant="outline" className="mt-4" onClick={openDialog}>
|
|
<UploadIcon className="-ms-1 opacity-60" aria-hidden="true" />
|
|
Browse file
|
|
</Button>
|
|
</div>
|
|
)}
|
|
|
|
</div>
|
|
);
|
|
}}
|
|
</Dropzone>
|
|
</div>
|
|
</div>
|
|
<AlertDialogFooter>
|
|
<AlertDialogCancel onClick={onCancel} disabled={isLoading} type='button'>Cancel</AlertDialogCancel>
|
|
<Button type="submit" disabled={isLoading}>
|
|
{isLoading && <Loader2 className='animate-spin' />}
|
|
Save Client
|
|
</Button>
|
|
</AlertDialogFooter>
|
|
</form>
|
|
</Form>
|
|
</AlertDialogContent>
|
|
</AlertDialog>
|
|
</>
|
|
);
|
|
}
|
|
|
|
export default FormClient; |