Files
hats-app/app/(dashboard)/task/component/FormEndUser.tsx
T
Ichsan Kurniawan d4168b45f2 Tighten task actions and image uploads
Gate assignment and team actions by permissions, limit client and end-user images to 2 MB, and make the technical status end date optional. Also update status remark handling and rename the Task navigation label.
2026-11-18 18:19:38 +07:00

258 lines
13 KiB
TypeScript

import { useCallback, useEffect, 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 { IEndUser } 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 { serverApiCall } from '@/lib/server-api';
import { Textarea } from '@/components/ui/textarea';
import Dropzone from 'react-dropzone';
import { LazyImage } from '@/components/ui/lazy-image';
import { Label } from '@/components/ui/label';
const validationSchema = Yup.object().shape({
name: Yup.string().required(),
description: Yup.string().optional().default(''),
});
type FormDataType = Yup.InferType<typeof validationSchema>;
type Props = {
data?: IEndUser
onCancel?: VoidFunction
onSuccess?: VoidFunction;
};
const FormEndUser: FC<Props> = ({ data, onSuccess, onCancel }) => {
const [currentFile, setCurrentFile] = useState<any | undefined>(undefined);
const [isLoading, setIsLoading] = useState(false);
const existFile = data?.photo || null
const dropzoneRef = useRef<any>(null);
const maxSizeMB = 2
const maxSizeBytes = maxSizeMB * 1024 * 1024;
const openDialog = () => {
// Note that the ref is set async,
// so it might be null at some point
if (dropzoneRef.current) {
dropzoneRef.current.open();
}
};
const onDrop = useCallback((acceptedFiles: any[]) => {
acceptedFiles.forEach(async (file: any) => {
if (file.size > maxSizeBytes) {
toast.error('File size exceeds the limit', {
description: `Maximum allowed file size is ${maxSizeMB}MB.`,
});
return;
}
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 form = useForm<FormDataType>({
resolver: yupResolver(validationSchema),
defaultValues: {
"name": data?.name || '',
'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-end-user"
})
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."}`,
id: toastId
})
}
} 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}`, { id: toastId });
} finally {
toast.dismiss(toastId)
setIsLoading(false)
}
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', `/end-user/${data.id}`, newPayload)
} else {
res = await serverApiCall('POST', '/end-user', newPayload)
}
setIsLoading(false)
if (res.success) {
toast.success('End User saved successfully')
onSuccess!()
} else {
toast.error(`Fail to save end user`, { description: `(${res.code || '-'}) ${res.message}` })
}
};
return (
<>
<AlertDialog open={true}>
<AlertDialogContent className='max-h-[90vh] overflow-y-auto'>
<AlertDialogHeader>
<AlertDialogTitle>End User Information</AlertDialogTitle>
<AlertDialogDescription>
Enter the basic details of the 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>End User Name <span className='text-red-600 font-bold'>*</span></FormLabel>
<FormControl>
<Input {...field} placeholder='e.g. PT ASDP Indonesia Ferry' />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField control={form.control} name='description'
render={({ field }) => (
<FormItem>
<FormLabel>Description</FormLabel>
<FormControl>
<Textarea {...field} placeholder='Describe a little about the end user.' />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<div className="flex flex-col gap-2">
<Label>Add End User Image</Label>
{/* Drop area */}
<Dropzone ref={dropzoneRef} onDrop={onDrop} multiple={false} noClick noKeyboard
accept={{ 'image/*': ['.svg', '.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, WEBP, BMP 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 End User
</Button>
</AlertDialogFooter>
</form>
</Form>
</AlertDialogContent>
</AlertDialog>
</>
);
}
export default FormEndUser;