From be0f537dc4fe384eef09436833c6407e6482c16d Mon Sep 17 00:00:00 2001
From: Rafi Zadanly <zadanlyr@gmail.com>
Date: Thu, 9 Nov 2023 15:40:16 +0700
Subject: Initial commit

---
 src/modules/result/components/ImportModal.tsx | 62 +++++++++++++++++++++++++++
 1 file changed, 62 insertions(+)
 create mode 100644 src/modules/result/components/ImportModal.tsx

(limited to 'src/modules/result/components/ImportModal.tsx')

diff --git a/src/modules/result/components/ImportModal.tsx b/src/modules/result/components/ImportModal.tsx
new file mode 100644
index 0000000..85e4a97
--- /dev/null
+++ b/src/modules/result/components/ImportModal.tsx
@@ -0,0 +1,62 @@
+import toast from '@/common/libs/toast'
+import { Button, Modal, ModalBody, ModalContent, ModalHeader } from '@nextui-org/react'
+import { useMutation } from '@tanstack/react-query'
+import React, { ChangeEvent, FormEvent, useState } from 'react'
+
+type Props = {
+  modal: {
+    isOpen: boolean,
+    onOpenChange: () => void
+  }
+}
+
+const ImportModal = ({ modal }: Props) => {
+  const [file, setFile] = useState<File>()
+
+  const handleFileChange = (e: ChangeEvent<HTMLInputElement>) => {
+    if (e.target.files) setFile(e.target.files[0])
+  }
+
+  const importMutation = useMutation({
+    mutationKey: ['import-product'],
+    mutationFn: async () => {
+      if (!file) return
+      return await fetch('/api/product/import', {
+        method: 'POST',
+        body: file,
+        headers: { 'content-type': file.type, 'content-length': `${file.size}` }
+      })
+    },
+    onSuccess(data) {
+      if (data?.status === 200) {
+        toast('Berhasil import product')
+        setFile(undefined)
+      } else {
+        toast('Gagal import product')
+      }
+    },
+  })
+
+  const handleSubmit = (e: FormEvent<HTMLFormElement>) => {
+    e.preventDefault()
+    importMutation.mutate()
+  }
+
+  return (
+    <Modal isOpen={modal.isOpen} onOpenChange={modal.onOpenChange}>
+      <ModalContent>
+        <ModalHeader>Import Product</ModalHeader>
+        <ModalBody>
+          <form className='pb-6' onSubmit={handleSubmit}>
+            <input type='file' onChange={handleFileChange} accept='.xls, .xlsx' />
+            <Button type='submit' color='primary' className='mt-4 w-full' isDisabled={!file || importMutation.isPending}>
+              {importMutation.isPending ? 'Loading...' : 'Submit'}
+            </Button>
+          </form>
+        </ModalBody>
+      </ModalContent>
+    </Modal>
+  )
+}
+
+export default ImportModal
\ No newline at end of file
-- 
cgit v1.2.3

