Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React, { useEffect, useState, useRef } from 'react'
- import { getCookie } from 'cookies-next'
- import { useSelector, useDispatch } from 'react-redux'
- import { useRouter } from 'next/router'
- import Link from 'next/link'
- // utils
- import { getData, deleteFile, postData, putData, postFile } from '@/utils/fetch'
- import { checkFile } from '@/utils/checkFile'
- import { ItemActiveType } from '@/utils/interface/life-activity'
- // store
- import { IRootState } from '@/store'
- import { userLoginAzure, userLogout } from '@/store/azure-auth/actions'
- import cookieExpirationMiddleware from '@/middlewares/WithAuth'
- import * as yup from 'yup'
- import { yupResolver } from '@hookform/resolvers/yup'
- // component
- import { Fragment } from '@fullcalendar/core/preact'
- import showDialog from '@/utils/showDialog'
- import { showMessage } from '@/components/reuseable/ShowMessage'
- import { useForm } from 'react-hook-form'
- import TextInput from '@/components/reuseable/TextInput'
- import Swal from 'sweetalert2'
- import Spinner from '@/components/reuseable/Spinner'
- import RichTextEditor from '@/pages/components/RichTextEditor'
- import CustomInputFile from '@/components/reuseable/core/input-file'
- import CustomInputFile2 from '@/components/reuseable/core/input-file2'
- import { setPageTitle } from '@/store/themeConfigSlice'
- // props
- interface TopAgentProps {
- token: any
- name: any
- username: any
- itemActive: ItemActiveType
- }
- // schema
- const schema = yup.object({
- description: yup.string(),
- altText: yup.string(),
- linkImage: yup.string(),
- title: yup.string(),
- itemActivities: yup.array().of(
- yup.object().shape(
- {
- linkImage: yup.string(),
- altText: yup.string()
- }
- )
- )
- })
- function TopAgentInput({token, name, username, itemActive}: TopAgentProps): JSX.Element {
- const router = useRouter()
- const dispatch = useDispatch()
- // state token
- const {token: tokenBackup} = useSelector((state: IRootState) => state.azureAuth)
- // handle token
- useEffect(() => {
- if(token){
- dispatch(userLoginAzure(token, name, username))
- }
- },[])
- useEffect(() => {
- // session token
- const checkSession = async () => {
- try {
- await getData('/users', { page: 1, limit: 1 })
- } catch (error) {
- return false
- }
- }
- checkSession()
- // token expired
- const check = cookieExpirationMiddleware(token, tokenBackup)
- if(check){
- showMessage('Sesi telah berakhir, Silahkan masuk kembali', 'error')
- dispatch(userLogout())
- router.push('/auth/login-v2')
- }
- },[])
- // data by query
- const {query} = useRouter()
- // validation
- const {
- register,
- handleSubmit,
- formState: {errors}
- } = useForm({
- resolver: yupResolver(schema)
- })
- // form input
- const [form, setForm] = useState({
- description: query.description || '',
- altText: query.alt_text || '',
- linkImage: query.link_image,
- title: query.title || '',
- itemActivities:
- })
- const [imageForm, setImageForm] = useState({
- linkImage: itemActive?.link_image,
- altText: itemActive?.alt_text || ''
- })
- const inputFileRef = useRef<any>()
- const inputFileRef1 = useRef<any>()
- const inputFileRef2 = useRef<any>()
- const inputFileRef3 = useRef<any>()
- const inputFileRef4 = useRef<any>()
- const inputFileRef5 = useRef<any>()
- const inputFileRef6 = useRef<any>()
- const inputFileRef7 = useRef<any>()
- const inputFileRef8 = useRef<any>()
- const inputFileRef9 = useRef<any>()
- const inputFileRef10 = useRef<any>()
- const [editorLoaded, setEditorLoaded] = useState(false)
- const [isUpload, setIsUpload] = useState<boolean>(false)
- const [isLoading, setIsLoading] = useState<boolean>(false)
- // handleInput
- const handleChangeForm = (ev: any) => {
- const {name, value} = ev.target
- if(name === 'description'){
- const description = value
- setForm({
- ...form,
- [name]: description
- })
- }else{
- setForm({
- ...form,
- [name]: value
- })
- }
- }
- const handleChangeForm2 = (ev: any) => {
- const {value} = ev.target
- const newValue = {}
- setImageForm({
- ...imageForm,
- altText: value
- })
- }
- // handle cover
- async function performPost(files: any){
- if (files.length > 0) {
- const check = checkFile(files[0], 'image');
- try {
- if (check) {
- setIsUpload(true);
- if (form.linkImage) {
- await deleteFile({ paths: [form.linkImage] });
- }
- const extension = files[0].type.split('/')[1];
- const original_filename = files[0].name.split(' ').join('_').toString().toLowerCase();
- const { data } = await postFile({ files: files[0], extension, original_filename });
- setForm((prev) => ({
- ...prev,
- linkImage: data.data.files.filepath,
- }));
- // setImage([...newActive])
- setIsUpload(false);
- }
- } catch (error: any) {
- await new Promise((resolve) => setTimeout(resolve, 1000));
- await performPost(files);
- }
- }
- }
- const handlePostFile = async (ev: any) => {
- const {files} = ev.target
- try {
- setIsLoading(true)
- await performPost(files)
- setIsLoading(false)
- } catch (error: any) {
- setIsLoading(false)
- }
- }
- // handle photo1
- async function performPost2(files: any, value: any){
- if (files.length > 0) {
- const check = checkFile(files[0], 'image');
- try {
- if (check) {
- setIsUpload(true);
- if (imageForm.linkImage) {
- await deleteFile({ paths: [imageForm.linkImage] });
- }
- const extension = files[0].type.split('/')[1];
- const original_filename = files[0].name.split(' ').join('_').toString().toLowerCase();
- const { data } = await postFile({ files: files[0], extension, original_filename });
- // const newActive: any = Array.from(files).map((file: any) => ({
- // linkImage: data.data.files.filepath,
- // altText: file.name
- // }))
- // const newActive: any = ({
- // linkImage: data.data.files.filepath,
- // altText: value
- // })
- setImageForm((prev) => ({
- ...prev,
- linkImage: newActive
- }));
- // setImage([...image, newActive])
- // setIsUpload(false);
- }
- } catch (error: any) {
- await new Promise((resolve) => setTimeout(resolve, 1000));
- await performPost(files);
- }
- }
- }
- const handlePostFile2 = async (ev: any) => {
- const {files, value} = ev.target
- try {
- setIsLoading(true)
- await performPost2(files, value)
- setIsLoading(false)
- } catch (error: any) {
- setIsLoading(false)
- }
- }
- useEffect(() => {
- dispatch(setPageTitle('Tambah dan Ubah Activity List'));
- setEditorLoaded(true);
- }, []);
- useEffect(() => {
- form.description === '<p><br></p>' && setForm({...form, description: ''})
- },[form.description])
- const submitForm = async () => {
- const requestBody = {
- description: form.description,
- linkImage: form.linkImage,
- altText: form.altText,
- title: form.title,
- // itemActivities: form.itemActivities
- itemActivities: [
- {
- linkImage: imageForm.linkImage,
- altText: imageForm.altText,
- }
- ]
- }
- if(!query.id){
- try {
- setIsLoading(true)
- await postData('/lifefriend-activity', requestBody)
- showDialog('Tambah Data', 'success')
- router.push('./')
- setIsLoading(false)
- } catch (error: any) {
- if(error.response.data.message){
- Swal.fire({
- html: `<div class="wrap-dialog-content">
- <svg width="42" height="42" viewBox="0 0 42 42" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M42 4.23L37.77 0L21 16.77L4.23 0L0 4.23L16.77 21L0 37.77L4.23 42L21 25.23L37.77 42L42 37.77L25.23 21L42 4.23Z" fill="#E30008"/></svg><h3 class="title-dialog-action">Simpan data gagal, Judul sudah tersedia!</h3></div>`,
- imageWidth: 42,
- imageHeight: 42,
- confirmButtonText: 'OK!',
- confirmButtonColor: ' #ED1C24',
- })
- }else{
- showDialog('Tambah', 'failed')
- }
- setIsLoading(false)
- }
- }else{
- try {
- setIsLoading(true)
- await putData(`/lifefriend-activity/${query.id}`, requestBody)
- showDialog('Edit data', 'success')
- router.push('./')
- setIsLoading(false)
- } catch (error: any) {
- showDialog('Edit Data', 'failed')
- setIsLoading(false)
- }
- }
- }
- console.log(form)
- console.log(image)
- console.log(imageForm)
- return (
- <Fragment>
- <div className='font-inter'>
- <div>
- <h5 className='title-banner text-lg dark:text-white'>
- {!query.id ? 'Tambah' : 'Edit '} Activity List
- </h5>
- <div className='subtitle-banner'>
- ({!query.id ? 'Tambah' : 'Edit'} data activity list)
- </div>
- </div>
- <form onSubmit={handleSubmit(submitForm)}>
- <div className="wrapper-form-addBanner mt-6">
- <div className='input-banner mb-5'>
- <label htmlFor="title" className='font-semibold text-[#787A7D]'>
- <span className='text-[#ED1C24]'>*</span> Judul
- </label>
- <TextInput
- type='text'
- register={register}
- name='title'
- value={form.title}
- onChange={handleChangeForm}
- placeholder='Input Judul....'
- errors={errors}
- />
- </div>
- <div className="input-banner mb-5">
- <div className="mb-2 flex gap-1">
- <label htmlFor="description" className="font-semibold text-[#787A7D]">
- <span className="text-[#ED1C24]">*</span> Deskripsi
- </label>
- </div>
- <RichTextEditor name="description" form={form} setForm={setForm} editorLoaded={editorLoaded} />
- </div>
- <div className="input-banner mb-5">
- <label htmlFor="linkImage" className="font-semibold text-[#787A7D]">
- <span className="text-[#ED1C24]">*</span> Cover Image
- </label>
- <CustomInputFile inputFileRef={inputFileRef} isUpload={isUpload} form={form} fileName="linkImage" onChange={handlePostFile} />
- </div>
- <div className='input-banner mb-5'>
- <label htmlFor="altText" className='font-semibold text-[#787A7D]'>
- <span className='text-[#ED1C24]'>*</span> Alt Text Image
- </label>
- <TextInput
- type='text'
- register={register}
- name='altText'
- value={form.altText}
- onChange={handleChangeForm}
- placeholder='Input Bahasa....'
- errors={errors}
- />
- </div>
- </div>
- <div className="wrapper-form-addBanner mt-6">
- <div className='flex items-center justify-between rounded-md border-2 border-dashed p-3 gap-4 mb-3'>
- <div className="input-banner w-full">
- <label htmlFor="linkImage" className="font-semibold text-[#787A7D]">
- <span className="text-[#ED1C24]">*</span> Image 1
- </label>
- <CustomInputFile2 inputFileRef={inputFileRef1} isUpload={isUpload} form={imageForm} fileName="linkImage" onChange={handlePostFile2}/>
- </div>
- <div className='input-banner w-full'>
- <label htmlFor="itemActivities" className='font-semibold text-[#787A7D]'>
- <span className='text-[#ED1C24]'>*</span> Alt Text Image
- </label>
- <TextInput
- type='text'
- register={register}
- name='itemActivities'
- value={imageForm.altText}
- onChange={handlePostFile2}
- placeholder='Alt Gambar...'
- errors={errors}
- />
- </div>
- </div>
- {/* <div className='flex items-center justify-between rounded-md border-2 border-dashed p-3 gap-4 mb-3'>
- <div className="input-banner w-full">
- <label htmlFor="itemActivities2" className="font-semibold text-[#787A7D]">
- <span className="text-[#ED1C24]">*</span> Image 2
- </label>
- <CustomInputFile2 inputFileRef={inputFileRef2} isUpload={isUpload} form={imageForm} fileName="itemActivities2" onChange={handlePostFile2}/>
- </div>
- <div className='input-banner w-full'>
- <label htmlFor="altText" className='font-semibold text-[#787A7D]'>
- <span className='text-[#ED1C24]'>*</span> Alt Text Image
- </label>
- <TextInput
- type='text'
- register={register}
- name='altText'
- value={imageForm.altText}
- onChange={handleChangeForm2}
- placeholder='Alt Gambar...'
- errors={errors}
- />
- </div>
- </div>
- <div className='flex items-center justify-between rounded-md border-2 border-dashed p-3 gap-4 mb-3'>
- <div className="input-banner w-full">
- <label htmlFor="itemActivities" className="font-semibold text-[#787A7D]">
- <span className="text-[#ED1C24]">*</span> Image 3
- </label>
- <CustomInputFile2 inputFileRef={inputFileRef3} isUpload={isUpload} form={imageForm} fileName="itemActivities" onChange={handlePostFile2}/>
- </div>
- <div className='input-banner w-full'>
- <label htmlFor="altText" className='font-semibold text-[#787A7D]'>
- <span className='text-[#ED1C24]'>*</span> Alt Text Image
- </label>
- <TextInput
- type='text'
- register={register}
- name='altText'
- value={imageForm.altText}
- onChange={handleChangeForm2}
- placeholder='Alt Gambar...'
- errors={errors}
- />
- </div>
- </div>
- <div className='flex items-center justify-between rounded-md border-2 border-dashed p-3 gap-4 mb-3'>
- <div className="input-banner w-full">
- <label htmlFor="itemActivities" className="font-semibold text-[#787A7D]">
- <span className="text-[#ED1C24]">*</span> Image 4
- </label>
- <CustomInputFile2 inputFileRef={inputFileRef4} isUpload={isUpload} form={imageForm} fileName="itemActivities" onChange={handlePostFile2}/>
- </div>
- <div className='input-banner w-full'>
- <label htmlFor="altText" className='font-semibold text-[#787A7D]'>
- <span className='text-[#ED1C24]'>*</span> Alt Text Image
- </label>
- <TextInput
- type='text'
- register={register}
- name='altText'
- value={imageForm.altText}
- onChange={handleChangeForm2}
- placeholder='Alt Gambar...'
- errors={errors}
- />
- </div>
- </div>
- <div className='flex items-center justify-between rounded-md border-2 border-dashed p-3 gap-4 mb-3'>
- <div className="input-banner w-full">
- <label htmlFor="itemActivities" className="font-semibold text-[#787A7D]">
- <span className="text-[#ED1C24]">*</span> Image 5
- </label>
- <CustomInputFile2 inputFileRef={inputFileRef5} isUpload={isUpload} form={imageForm} fileName="itemActivities" onChange={handlePostFile2}/>
- </div>
- <div className='input-banner w-full'>
- <label htmlFor="altText" className='font-semibold text-[#787A7D]'>
- <span className='text-[#ED1C24]'>*</span> Alt Text Image
- </label>
- <TextInput
- type='text'
- register={register}
- name='altText'
- value={imageForm.altText}
- onChange={handleChangeForm2}
- placeholder='Alt Gambar...'
- errors={errors}
- />
- </div>
- </div>
- <div className='flex items-center justify-between rounded-md border-2 border-dashed p-3 gap-4 mb-3'>
- <div className="input-banner w-full">
- <label htmlFor="itemActivities" className="font-semibold text-[#787A7D]">
- <span className="text-[#ED1C24]">*</span> Image 6
- </label>
- <CustomInputFile2 inputFileRef={inputFileRef6} isUpload={isUpload} form={imageForm} fileName="itemActivities" onChange={handlePostFile2}/>
- </div>
- <div className='input-banner w-full'>
- <label htmlFor="altText" className='font-semibold text-[#787A7D]'>
- <span className='text-[#ED1C24]'>*</span> Alt Text Image
- </label>
- <TextInput
- type='text'
- register={register}
- name='altText'
- value={imageForm.altText}
- onChange={handleChangeForm2}
- placeholder='Alt Gambar...'
- errors={errors}
- />
- </div>
- </div>
- <div className='flex items-center justify-between rounded-md border-2 border-dashed p-3 gap-4 mb-3'>
- <div className="input-banner w-full">
- <label htmlFor="itemActivities" className="font-semibold text-[#787A7D]">
- <span className="text-[#ED1C24]">*</span> Image 7
- </label>
- <CustomInputFile2 inputFileRef={inputFileRef7} isUpload={isUpload} form={imageForm} fileName="itemActivities" onChange={handlePostFile2}/>
- </div>
- <div className='input-banner w-full'>
- <label htmlFor="altText" className='font-semibold text-[#787A7D]'>
- <span className='text-[#ED1C24]'>*</span> Alt Text Image
- </label>
- <TextInput
- type='text'
- register={register}
- name='altText'
- value={imageForm.altText}
- onChange={handleChangeForm2}
- placeholder='Alt Gambar...'
- errors={errors}
- />
- </div>
- </div>
- <div className='flex items-center justify-between rounded-md border-2 border-dashed p-3 gap-4 mb-3'>
- <div className="input-banner w-full">
- <label htmlFor="itemActivities" className="font-semibold text-[#787A7D]">
- <span className="text-[#ED1C24]">*</span> Image 8
- </label>
- <CustomInputFile2 inputFileRef={inputFileRef8} isUpload={isUpload} form={imageForm} fileName="itemActivities" onChange={handlePostFile2}/>
- </div>
- <div className='input-banner w-full'>
- <label htmlFor="altText" className='font-semibold text-[#787A7D]'>
- <span className='text-[#ED1C24]'>*</span> Alt Text Image
- </label>
- <TextInput
- type='text'
- register={register}
- name='altText'
- value={imageForm.altText}
- onChange={handleChangeForm2}
- placeholder='Alt Gambar...'
- errors={errors}
- />
- </div>
- </div>
- <div className='flex items-center justify-between rounded-md border-2 border-dashed p-3 gap-4 mb-3'>
- <div className="input-banner w-full">
- <label htmlFor="itemActivities" className="font-semibold text-[#787A7D]">
- <span className="text-[#ED1C24]">*</span> Image 9
- </label>
- <CustomInputFile2 inputFileRef={inputFileRef9} isUpload={isUpload} form={imageForm} fileName="itemActivities" onChange={handlePostFile2}/>
- </div>
- <div className='input-banner w-full'>
- <label htmlFor="altText" className='font-semibold text-[#787A7D]'>
- <span className='text-[#ED1C24]'>*</span> Alt Text Image
- </label>
- <TextInput
- type='text'
- register={register}
- name='altText'
- value={imageForm.altText}
- onChange={handleChangeForm2}
- placeholder='Alt Gambar...'
- errors={errors}
- />
- </div>
- </div>
- <div className='flex items-center justify-between rounded-md border-2 border-dashed p-3 gap-4'>
- <div className="input-banner w-full">
- <label htmlFor="itemActivities" className="font-semibold text-[#787A7D]">
- <span className="text-[#ED1C24]">*</span> Image 10
- </label>
- <CustomInputFile2 inputFileRef={inputFileRef10} isUpload={isUpload} form={imageForm} fileName="itemActivities" onChange={handlePostFile2}/>
- </div>
- <div className='input-banner w-full'>
- <label htmlFor="altText" className='font-semibold text-[#787A7D]'>
- <span className='text-[#ED1C24]'>*</span> Alt Text Image
- </label>
- <TextInput
- type='text'
- register={register}
- name='altText'
- value={imageForm.altText}
- onChange={handleChangeForm2}
- placeholder='Alt Gambar...'
- errors={errors}
- />
- </div>
- </div> */}
- </div>
- <div className="mt-5 flex justify-end">
- <div className="flex gap-4">
- <Link href="/join/partner/top-agent" className="btn-delete-item-banner flex items-center">
- Batal
- </Link>
- <button
- type="submit"
- className={`btn-add-item-banner flex items-center ${!form.description || !form.altText || !form.title || !imageForm.linkImage || !imageForm.altText || !form.linkImage || isLoading || isUpload ? 'btn-disabled ' : ''}`}
- disabled={!form.description || !form.altText || !form.title || !imageForm.linkImage || !imageForm.altText || !form.linkImage || isLoading || isUpload ? true : false}
- >
- {isLoading && <Spinner />}
- {query.id ? 'Ubah' : 'Simpan'}
- </button>
- </div>
- </div>
- </form>
- </div>
- </Fragment>
- )
- }
- export default TopAgentInput
- export async function getServerSideProps({req}:any) {
- const token = getCookie('access_token', {req})
- const name = getCookie('name', {req})
- const username = getCookie('username', {req})
- try {
- return {
- props: {
- token: token ? token : '',
- name: name ? name : '',
- username: username ? username : ''
- }
- }
- } catch (error: any) {
- return {
- props: { token: token ? token : '', username: username ? username : '', name: name ? name : '' },
- };
- }
- }
Add Comment
Please, Sign In to add comment