300 lines
		
	
	
		
			7.5 KiB
		
	
	
	
		
			TypeScript
		
	
	
	
			
		
		
	
	
			300 lines
		
	
	
		
			7.5 KiB
		
	
	
	
		
			TypeScript
		
	
	
	
import { useEffect, useState } from 'react'
 | 
						|
import { useForm } from '@mantine/form'
 | 
						|
import {
 | 
						|
  Modal,
 | 
						|
  Button,
 | 
						|
  TextInput,
 | 
						|
  Text,
 | 
						|
  Box,
 | 
						|
  Switch,
 | 
						|
  Checkbox,
 | 
						|
  FileInput,
 | 
						|
  TagsInput,
 | 
						|
  Group,
 | 
						|
} from '@mantine/core'
 | 
						|
 | 
						|
import { create, update } from '@/rtk/helpers/CRUD'
 | 
						|
import { createDocument, updateDocument } from '@/api/Admin'
 | 
						|
import { getHeaderInfo } from '@/rtk/helpers/tokenCreator'
 | 
						|
import { notifications } from '@mantine/notifications'
 | 
						|
 | 
						|
type MProps = {
 | 
						|
  opened: boolean
 | 
						|
  close: () => void
 | 
						|
  setAction: (arg0: any) => void
 | 
						|
  selectDataRow: any
 | 
						|
  setSelectDataRow: any
 | 
						|
  action: string
 | 
						|
  getAllData: () => void
 | 
						|
}
 | 
						|
 | 
						|
const ModalAddEditDocument = ({
 | 
						|
  opened,
 | 
						|
  close,
 | 
						|
  setAction,
 | 
						|
  selectDataRow,
 | 
						|
  setSelectDataRow,
 | 
						|
  action,
 | 
						|
  getAllData,
 | 
						|
}: MProps) => {
 | 
						|
  const [loadingSubmit, setLoadingSubmit] = useState(false)
 | 
						|
 | 
						|
  const form = useForm({
 | 
						|
    initialValues: {
 | 
						|
      title: '',
 | 
						|
      type: true,
 | 
						|
      files: [] as File[],
 | 
						|
      uri: [],
 | 
						|
      is_active: true,
 | 
						|
    },
 | 
						|
  })
 | 
						|
 | 
						|
  useEffect(() => {
 | 
						|
    form.setValues({
 | 
						|
      title: selectDataRow?.title ?? '',
 | 
						|
      type: selectDataRow?.type ? selectDataRow?.type === 'file' : true,
 | 
						|
      files: [],
 | 
						|
      uri: selectDataRow?.uri?.split(',') ?? [],
 | 
						|
      is_active: selectDataRow?.is_active ?? true,
 | 
						|
    })
 | 
						|
  }, [selectDataRow])
 | 
						|
 | 
						|
  const handleCreate = async (data: any) => {
 | 
						|
    try {
 | 
						|
      setLoadingSubmit(true)
 | 
						|
 | 
						|
      let formdata = {}
 | 
						|
      const header = await getHeaderInfo()
 | 
						|
 | 
						|
      if (data.type) {
 | 
						|
        if (data.files.length < 1) {
 | 
						|
          notifications.show({
 | 
						|
            title: 'Error',
 | 
						|
            message: 'Upload at least 1 file',
 | 
						|
            color: 'red',
 | 
						|
          })
 | 
						|
 | 
						|
          return
 | 
						|
        }
 | 
						|
 | 
						|
        header.headers['Content-Type'] = 'multipart/form-data'
 | 
						|
        const tmpFormData = new FormData()
 | 
						|
 | 
						|
        tmpFormData.append('title', data.title)
 | 
						|
        tmpFormData.append('type', data.type ? 'file' : 'link')
 | 
						|
        tmpFormData.append('is_active', data.is_active ? '1' : '0')
 | 
						|
        for (let i = 0; i < data.files.length; i++) {
 | 
						|
          tmpFormData.append('files[]', data.files[i])
 | 
						|
        }
 | 
						|
 | 
						|
        formdata = tmpFormData
 | 
						|
      } else {
 | 
						|
        const { files, ...rest } = data
 | 
						|
        formdata = {
 | 
						|
          ...rest,
 | 
						|
          type: rest.type ? 'file' : 'link',
 | 
						|
        }
 | 
						|
      }
 | 
						|
 | 
						|
      const res = await create(createDocument, formdata, getAllData, header)
 | 
						|
      if (res === true) {
 | 
						|
        setAction('')
 | 
						|
        close()
 | 
						|
        form.reset()
 | 
						|
        setSelectDataRow({})
 | 
						|
      }
 | 
						|
    } catch (error: any) {
 | 
						|
      console.log(error)
 | 
						|
    } finally {
 | 
						|
      setLoadingSubmit(false)
 | 
						|
    }
 | 
						|
  }
 | 
						|
 | 
						|
  const handleUpdate = async (data: any) => {
 | 
						|
    try {
 | 
						|
      setLoadingSubmit(true)
 | 
						|
 | 
						|
      let formdata = {}
 | 
						|
      const header = await getHeaderInfo()
 | 
						|
 | 
						|
      if (data.type) {
 | 
						|
        if (data.files.length < 1 && data.uri.length < 1) {
 | 
						|
          notifications.show({
 | 
						|
            title: 'Error',
 | 
						|
            message: 'Upload at least 1 file',
 | 
						|
            color: 'red',
 | 
						|
          })
 | 
						|
 | 
						|
          return
 | 
						|
        }
 | 
						|
 | 
						|
        header.headers['Content-Type'] = 'multipart/form-data'
 | 
						|
        const tmpFormData = new FormData()
 | 
						|
 | 
						|
        tmpFormData.append('title', data.title)
 | 
						|
        tmpFormData.append('type', data.type ? 'file' : 'link')
 | 
						|
        tmpFormData.append('is_active', data.is_active ? '1' : '0')
 | 
						|
        for (let i = 0; i < data.files.length; i++) {
 | 
						|
          tmpFormData.append('files[]', data.files[i])
 | 
						|
        }
 | 
						|
 | 
						|
        data.uri.forEach((fileUri: string) => {
 | 
						|
          tmpFormData.append('existing_files[]', fileUri)
 | 
						|
        })
 | 
						|
 | 
						|
        formdata = tmpFormData
 | 
						|
      } else {
 | 
						|
        const { files, ...rest } = data
 | 
						|
        formdata = {
 | 
						|
          ...rest,
 | 
						|
          type: rest.type ? 'file' : 'link',
 | 
						|
        }
 | 
						|
      }
 | 
						|
 | 
						|
      const res = await update(
 | 
						|
        updateDocument + `?id=${selectDataRow?.id}`,
 | 
						|
        formdata,
 | 
						|
        getAllData,
 | 
						|
        header,
 | 
						|
      )
 | 
						|
      if (res === true) {
 | 
						|
        setAction('')
 | 
						|
        close()
 | 
						|
        form.reset()
 | 
						|
        setSelectDataRow({})
 | 
						|
      }
 | 
						|
    } catch (error: any) {
 | 
						|
      throw new Error(error)
 | 
						|
    } finally {
 | 
						|
      setLoadingSubmit(false)
 | 
						|
    }
 | 
						|
  }
 | 
						|
 | 
						|
  return (
 | 
						|
    <Modal
 | 
						|
      opened={opened}
 | 
						|
      onClose={() => {
 | 
						|
        setAction('')
 | 
						|
        close()
 | 
						|
        form.reset()
 | 
						|
        setSelectDataRow({})
 | 
						|
      }}
 | 
						|
      size="lg"
 | 
						|
      title={
 | 
						|
        <Text fw={700} fz={'lg'}>
 | 
						|
          {action === 'add' ? 'Add Document' : 'Update Document'}
 | 
						|
        </Text>
 | 
						|
      }
 | 
						|
    >
 | 
						|
      <form
 | 
						|
        onSubmit={form.onSubmit((values) => {
 | 
						|
          if (action === 'add') {
 | 
						|
            handleCreate(values)
 | 
						|
          } else {
 | 
						|
            handleUpdate(values)
 | 
						|
          }
 | 
						|
        })}
 | 
						|
      >
 | 
						|
        <TextInput
 | 
						|
          label="Title"
 | 
						|
          maxLength={255}
 | 
						|
          key={'title'}
 | 
						|
          mb={'md'}
 | 
						|
          {...form.getInputProps('title')}
 | 
						|
          disabled={loadingSubmit}
 | 
						|
          required
 | 
						|
        />
 | 
						|
 | 
						|
        {selectDataRow?.id ? (
 | 
						|
          ''
 | 
						|
        ) : (
 | 
						|
          <Switch
 | 
						|
            style={{ width: 'fit-content' }}
 | 
						|
            label={form.values.type ? 'Upload files' : 'Enter links'}
 | 
						|
            checked={form.values.type}
 | 
						|
            onChange={(event) =>
 | 
						|
              form.setFieldValue('type', event.currentTarget.checked)
 | 
						|
            }
 | 
						|
            mb={'md'}
 | 
						|
            disabled={loadingSubmit}
 | 
						|
          />
 | 
						|
        )}
 | 
						|
 | 
						|
        <Box mb={'md'}>
 | 
						|
          {form.values.type ? (
 | 
						|
            <Box>
 | 
						|
              <FileInput
 | 
						|
                accept=".doc,.docx,.xls,.xlsx,.pdf"
 | 
						|
                label="Upload Doc, Excel, PDF files"
 | 
						|
                multiple
 | 
						|
                mb="md"
 | 
						|
                value={form.values.files}
 | 
						|
                onChange={(files) => {
 | 
						|
                  form.setFieldValue('files', files || [])
 | 
						|
                }}
 | 
						|
                disabled={loadingSubmit}
 | 
						|
                required
 | 
						|
              />
 | 
						|
 | 
						|
              {selectDataRow?.uri && form.values.uri.length > 0 && (
 | 
						|
                <Box>
 | 
						|
                  <Text fw={500}>Existing Files:</Text>
 | 
						|
                  {form.values.uri.map((fileUri: string, index) => (
 | 
						|
                    <Group key={index} justify="space-between" mb="sm">
 | 
						|
                      <Text size="sm">
 | 
						|
                        {fileUri.replace('storage/uploads/', '')}
 | 
						|
                      </Text>
 | 
						|
                      <Button
 | 
						|
                        color="red"
 | 
						|
                        size="xs"
 | 
						|
                        ml="md"
 | 
						|
                        onClick={() =>
 | 
						|
                          form.setFieldValue(
 | 
						|
                            'uri',
 | 
						|
                            form.values.uri.filter((_, i) => i !== index),
 | 
						|
                          )
 | 
						|
                        }
 | 
						|
                      >
 | 
						|
                        Remove
 | 
						|
                      </Button>
 | 
						|
                    </Group>
 | 
						|
                  ))}
 | 
						|
                </Box>
 | 
						|
              )}
 | 
						|
            </Box>
 | 
						|
          ) : (
 | 
						|
            <Box>
 | 
						|
              <TagsInput
 | 
						|
                label="Enter uri"
 | 
						|
                key={'uri'}
 | 
						|
                mb={'md'}
 | 
						|
                {...form.getInputProps('uri')}
 | 
						|
                disabled={loadingSubmit}
 | 
						|
                required
 | 
						|
              />
 | 
						|
            </Box>
 | 
						|
          )}
 | 
						|
        </Box>
 | 
						|
 | 
						|
        <Checkbox
 | 
						|
          label="Is Active"
 | 
						|
          mb={'md'}
 | 
						|
          checked={form.values.is_active}
 | 
						|
          onChange={(event) =>
 | 
						|
            form.setFieldValue('is_active', event.currentTarget.checked)
 | 
						|
          }
 | 
						|
          disabled={loadingSubmit}
 | 
						|
        />
 | 
						|
 | 
						|
        <Box ta="center" mt="lg">
 | 
						|
          <Button color="green" type="submit" loading={loadingSubmit}>
 | 
						|
            {action === 'add' ? 'Create' : 'Update'}
 | 
						|
          </Button>
 | 
						|
        </Box>
 | 
						|
      </form>
 | 
						|
    </Modal>
 | 
						|
  )
 | 
						|
}
 | 
						|
 | 
						|
export default ModalAddEditDocument
 |