Browse Source

change alert notification

pull/2/head
wahyuun 1 year ago
parent
commit
476b872e35
  1. 748
      src/views/Master/MasterMenu/index.js

748
src/views/Master/MasterMenu/index.js

@ -1,377 +1,371 @@
import * as XLSX from 'xlsx'; import * as XLSX from 'xlsx';
import DialogForm from './DialogForm'; import DialogForm from './DialogForm';
import React, { useState, useEffect, useMemo } from 'react'; import React, { useState, useEffect, useMemo } from 'react';
import SweetAlert from 'react-bootstrap-sweetalert'; import SweetAlert from 'react-bootstrap-sweetalert';
import axios from 'axios'; import axios from 'axios';
import { Button } from 'reactstrap'; import { Button } from 'reactstrap';
import { Card, CardBody, CardHeader, Col, Row, Input } from 'reactstrap'; import { Card, CardBody, CardHeader, Col, Row, Input } from 'reactstrap';
import { MENU_ADD, MENU_SEARCH, MENU_EDIT, MENU_DELETE } from '../../../const/ApiConst.js'; import { MENU_ADD, MENU_SEARCH, MENU_EDIT, MENU_DELETE } from '../../../const/ApiConst.js';
import { NotificationContainer, NotificationManager } from 'react-notifications'; import { NotificationContainer, NotificationManager } from 'react-notifications';
import { Pagination, Tooltip, Table } from 'antd'; import { Pagination, Tooltip, Table } from 'antd';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
const token = window.localStorage.getItem('token'); const token = window.localStorage.getItem('token');
const column = [ const column = [
{ name: "Nama" }, { name: "Nama" },
{ name: "Url" }, { name: "Url" },
{ name: "Ikon" }, { name: "Ikon" },
{ name: "Alias" }, { name: "Alias" },
{ name: "Urutan" }, { name: "Urutan" },
{ name: "Parent" }, { name: "Parent" },
] ]
const Index = ({ params }) => { const Index = ({ params }) => {
const [alertDelete, setAlertDelete] = useState(false) const [alertDelete, setAlertDelete] = useState(false)
const [allDataMenu, setAllDataMenu] = useState([]) const [allDataMenu, setAllDataMenu] = useState([])
const [clickOpenModal, setClickOpenModal] = useState(false) const [clickOpenModal, setClickOpenModal] = useState(false)
const [currentPage, setCurrentPage] = useState(1) const [currentPage, setCurrentPage] = useState(1)
const [dataEdit, setDataEdit] = useState([]) const [dataEdit, setDataEdit] = useState([])
const [dataExport, setDataExport] = useState([]) const [dataExport, setDataExport] = useState([])
const [dataTable, setDatatable] = useState([]) const [dataTable, setDatatable] = useState([])
const [idDelete, setIdDelete] = useState(0) const [idDelete, setIdDelete] = useState(0)
const [openDialog, setOpenDialog] = useState(false) const [openDialog, setOpenDialog] = useState(false)
const [rowsPerPage, setRowsPerPage] = useState(10) const [rowsPerPage, setRowsPerPage] = useState(10)
const [search, setSearch] = useState('') const [search, setSearch] = useState('')
const [tooltipDelete, setTooltipDelete] = useState(false) const [tooltipDelete, setTooltipDelete] = useState(false)
const [tooltipEdit, setTooltipEdit] = useState(false) const [tooltipEdit, setTooltipEdit] = useState(false)
const [tooltipExport, setTooltipExport] = useState(false) const [tooltipExport, setTooltipExport] = useState(false)
const [tooltipTambah, setTooltipTambah] = useState(false) const [tooltipTambah, setTooltipTambah] = useState(false)
const [totalPage, setTotalPage] = useState(0) const [totalPage, setTotalPage] = useState(0)
const [typeDialog, setTypeDialog] = useState('Save') const [typeDialog, setTypeDialog] = useState('Save')
const { t } = useTranslation() const { t } = useTranslation()
const pageName = params.name; const pageName = params.name;
const config = { const config = {
headers: headers:
{ {
Authorization: `Bearer ${token}`, Authorization: `Bearer ${token}`,
"Content-type": `application/json` "Content-type": `application/json`
} }
}; };
useEffect(() => {
useEffect(() => { getDataMenu();
getDataMenu(); }, [search, currentPage, rowsPerPage])
getDataAllMenu();
}, []) useEffect(() => {
const cekData = dataExport || []
useEffect(() => { if (cekData.length > 0) {
getDataMenu(); exportExcel()
}, [search, currentPage, rowsPerPage]) }
}, [dataExport])
useEffect(() => {
const cekData = dataExport || [] const handleSearch = e => {
if (cekData.length > 0) { const value = e.target.value
exportExcel() setSearch(value);
} setCurrentPage(1)
}, [dataExport]) };
const handleSearch = e => { const getDataAllMenu = async () => {
const value = e.target.value const payload = {
setSearch(value); "paging": { "start": 0, "length": -1 },
setCurrentPage(1) "columns": [
}; { "name": "name", "logic_operator": "ilike", "value": "", "operator": "AND" }
],
const getDataAllMenu = async () => { "joins": [],
const payload = { "orders": { "columns": ["id"], "ascending": false }
"paging": { "start": 0, "length": -1 }, }
"columns": [ const result = await axios
{ "name": "name", "logic_operator": "ilike", "value": "", "operator": "AND" } .post(MENU_SEARCH, payload, config)
], .then(res => res)
"joins": [], .catch((error) => error.response);
"orders": { "columns": ["id"], "ascending": false }
} if (result && result.data && result.data.code == 200) {
const result = await axios setAllDataMenu(result.data.data);
.post(MENU_SEARCH, payload, config) } else {
.then(res => res) }
.catch((error) => error.response); }
if (result && result.data && result.data.code == 200) { const getDataMenu = async () => {
setAllDataMenu(result.data.data); let start = 0;
} else {
} if (currentPage !== 1 && currentPage > 1) {
} start = (currentPage * rowsPerPage) - rowsPerPage
}
const getDataMenu = async () => {
let start = 0; const payload = {
"paging": { "start": start, "length": rowsPerPage },
if (currentPage !== 1 && currentPage > 1) { "columns": [
start = (currentPage * rowsPerPage) - rowsPerPage { "name": "name", "logic_operator": "ilike", "value": search, "operator": "AND" }
} ],
"joins": [{
const payload = { "name": "m_menu",
"paging": { "start": start, "length": rowsPerPage }, "column_join": "parent_id",
"columns": [ "column_results": [
{ "name": "name", "logic_operator": "ilike", "value": search, "operator": "AND" } "name"
], ]
"joins": [{ }],
"name": "m_menu", "orders": { "columns": ["id"], "ascending": false }
"column_join": "parent_id", }
"column_results": [
"name" const result = await axios
] .post(MENU_SEARCH, payload, config)
}], .then(res => res)
"orders": { "columns": ["id"], "ascending": false } .catch((error) => error.response);
}
if (result && result.data && result.data.code == 200) {
const result = await axios setDatatable(result.data.data);
.post(MENU_SEARCH, payload, config) setTotalPage(result.data.totalRecord);
.then(res => res) } else {
.catch((error) => error.response); NotificationManager.error('Gagal Mengambil Data!!', 'Failed');
}
if (result && result.data && result.data.code == 200) { }
setDatatable(result.data.data);
setTotalPage(result.data.totalRecord); const handleOpenDialog = async (type) => {
} else { await setTypeDialog(type)
NotificationManager.error('Gagal Mengambil Data!!', 'Failed'); setOpenDialog(true)
} }
}
const handleCloseDialog = (type, data) => {
const handleOpenDialog = async (type) => { if (type === "save") {
await setTypeDialog(type) saveMenu(data);
setOpenDialog(true) } else if (type === "edit") {
} editMenu(data);
}
const handleCloseDialog = (type, data) => { setDataEdit([])
if (type === "save") { setOpenDialog(false)
saveMenu(data); }
} else if (type === "edit") {
editMenu(data); const toggleAddDialog = () => {
} setOpenDialog(!openDialog)
setDataEdit([]) }
setOpenDialog(false)
} const onConfirmDelete = async () => {
const url = MENU_DELETE(idDelete)
const toggleAddDialog = () => { const result = await axios.delete(url, config)
setOpenDialog(!openDialog) .then(res => res)
} .catch((error) => error.response);
if (result && result.data && result.data.code === 200) {
const onConfirmDelete = async () => { getDataMenu()
const url = MENU_DELETE(idDelete) setIdDelete(0)
const result = await axios.delete(url, config) setAlertDelete(false)
.then(res => res) NotificationManager.success(`Data menu berhasil dihapus`, 'Success!!');
.catch((error) => error.response); } else {
if (result && result.data && result.data.code === 200) { setIdDelete(0)
getDataMenu() setAlertDelete(false)
setIdDelete(0) NotificationManager.error(`Data menu gagal dihapus`, 'Failed!!');
setAlertDelete(false) }
NotificationManager.success(`Data menu berhasil dihapus`, 'Success!!'); }
} else {
setIdDelete(0) const saveMenu = async (data) => {
setAlertDelete(false) const formData = data
NotificationManager.error(`Data menu gagal dihapus`, 'Failed!!');
} const result = await axios.post(MENU_ADD, formData, config)
} .then(res => res)
.catch((error) => error.response);
const saveMenu = async (data) => {
const formData = data if (result && result.data && result.data.code === 200) {
getDataMenu();
const result = await axios.post(MENU_ADD, formData, config) getDataAllMenu();
.then(res => res) NotificationManager.success(`Data menu berhasil ditambahkan`, 'Success!!');
.catch((error) => error.response); } else {
NotificationManager.error(`Data menu gagal ditambahkan`, 'Failed!!');
if (result && result.data && result.data.code === 200) { }
getDataMenu();
getDataAllMenu(); }
NotificationManager.success(`Data menu berhasil ditambah`, 'Success!!');
} else { const editMenu = async (data) => {
NotificationManager.error(`${result.data.message}`, 'Failed!!'); const formData = data
} const url = MENU_EDIT(data.id)
const result = await axios.put(url, formData, config)
} .then(res => res)
.catch((error) => error.response);
const editMenu = async (data) => {
const formData = data if (result && result.data && result.data.code === 200) {
const url = MENU_EDIT(data.id) getDataMenu();
const result = await axios.put(url, formData, config) NotificationManager.success(`Data menu berhasil diubah`, 'Success!!');
.then(res => res) } else {
.catch((error) => error.response); NotificationManager.error(`Data menu gagal diubah`, `Failed!!`);
}
if (result && result.data && result.data.code === 200) { }
getDataMenu();
NotificationManager.success(`Data menu berhasil diedit`, 'Success!!'); const handleEdit = (data) => {
} else { setDataEdit(data)
NotificationManager.error(`Data menu gagal di edit`, `Failed!!`); handleOpenDialog('Edit');
} }
}
const handleDelete = async (id) => {
const handleEdit = (data) => { await setAlertDelete(true)
setDataEdit(data) await setIdDelete(id)
handleOpenDialog('Edit'); }
}
const onShowSizeChange = (current, pageSize) => {
const handleDelete = async (id) => { setRowsPerPage(pageSize)
await setAlertDelete(true) }
await setIdDelete(id)
} const onPagination = (current, pageSize) => {
setCurrentPage(current)
const onShowSizeChange = (current, pageSize) => { }
setRowsPerPage(pageSize)
} const toggle = (param) => {
if (param === "edit") {
const onPagination = (current, pageSize) => { setTooltipEdit(!tooltipEdit)
setCurrentPage(current) } else if (param === "delete") {
} setTooltipDelete(!tooltipDelete)
} else if (param === "tambah") {
const toggle = (param) => { setTooltipTambah(!tooltipTambah)
if (param === "edit") { } else if (param === "export") {
setTooltipEdit(!tooltipEdit) setTooltipExport(!tooltipExport)
} else if (param === "delete") { }
setTooltipDelete(!tooltipDelete) }
} else if (param === "tambah") {
setTooltipTambah(!tooltipTambah) const handleExportExcel = async () => {
} else if (param === "export") { const payload = {
setTooltipExport(!tooltipExport) "paging": { "start": 0, "length": -1 },
} "columns": [
} { "name": "name", "logic_operator": "ilike", "value": search, "operator": "AND" }
],
const handleExportExcel = async () => { "joins": [{
const payload = { "name": "m_menu",
"paging": { "start": 0, "length": -1 }, "column_join": "parent_id",
"columns": [ "column_results": [
{ "name": "name", "logic_operator": "ilike", "value": search, "operator": "AND" } "name"
], ]
"joins": [{ }],
"name": "m_menu", "orders": { "columns": ["id"], "ascending": false }
"column_join": "parent_id", }
"column_results": [
"name" const result = await axios
] .post(MENU_SEARCH, payload, config)
}], .then(res => res)
"orders": { "columns": ["id"], "ascending": false } .catch((error) => error.response);
}
if (result && result.data && result.data.code == 200) {
const result = await axios let resData = result.data.data;
.post(MENU_SEARCH, payload, config) const excelData = [];
.then(res => res) resData.map((val, index) => {
.catch((error) => error.response); let dataRow = {
"Nama": val.name,
if (result && result.data && result.data.code == 200) { "Url": val.url,
let resData = result.data.data; "Icon": val.icon,
const excelData = []; "Alias Name": val.alias_name,
resData.map((val, index) => { "Urutan": val.sequence,
let dataRow = { "Parent Name": val.join_first_name ? val.join_first_name : "-"
"Nama": val.name, }
"Url": val.url, excelData.push(dataRow)
"Icon": val.icon, })
"Alias Name": val.alias_name, await setDataExport(excelData);
"Urutan": val.sequence, } else {
"Parent Name": val.join_first_name ? val.join_first_name : "-" NotificationManager.error('Gagal Export Data!!', 'Failed');
} }
excelData.push(dataRow) }
})
await setDataExport(excelData); const exportExcel = () => {
} else { const dataExcel = dataExport || [];
NotificationManager.error('Gagal Export Data!!', 'Failed'); const fileName = `Data ${pageName}.xlsx`;
} const ws = XLSX.utils.json_to_sheet(dataExcel);
} const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, `Data ${pageName}`);
const exportExcel = () => { XLSX.writeFile(wb, fileName);
const dataExcel = dataExport || []; setDataExport([])
const fileName = `Data ${pageName}.xlsx`; }
const ws = XLSX.utils.json_to_sheet(dataExcel);
const wb = XLSX.utils.book_new(); const cancelDelete = () => {
XLSX.utils.book_append_sheet(wb, ws, `Data ${pageName}`); setAlertDelete(false)
XLSX.writeFile(wb, fileName); setIdDelete(0)
setDataExport([]) }
}
const renderTable = useMemo(() => {
const cancelDelete = () => { const columns = [
setAlertDelete(false) {
setIdDelete(0) title: t('action'),
} dataIndex: '',
key: 'x',
const renderTable = useMemo(() => { render: (text, record) => <>
const columns = [ <Tooltip title={t('delete')}>
{ <i id="TooltipDelete" className="fa fa-trash" style={{ color: 'red', marginRight: '10px', cursor: "pointer" }} onClick={() => handleDelete(text.id)}></i>
title: t('action'), </Tooltip>
dataIndex: '', <Tooltip title={t('edit')}>
key: 'x', <i id="TooltipEdit" className="fa fa-edit" style={{ color: 'green', cursor: "pointer" }} onClick={() => handleEdit(text)}></i>
render: (text, record) => <> </Tooltip>
<Tooltip title={t('delete')}> </>,
<i id="TooltipDelete" className="fa fa-trash" style={{ color: 'red', marginRight: '10px', cursor: "pointer" }} onClick={() => handleDelete(text.id)}></i> },
</Tooltip> { title: t('name'), dataIndex: 'name', key: 'name' },
<Tooltip title={t('edit')}> { title: 'Url', dataIndex: 'url', key: 'url' },
<i id="TooltipEdit" className="fa fa-edit" style={{ color: 'green', cursor: "pointer" }} onClick={() => handleEdit(text)}></i> { title: t('icon'), dataIndex: 'icon', key: 'icon' },
</Tooltip> { title: 'Alias', dataIndex: 'alias_name', key: 'alias_name' },
</>, { title: t('order'), dataIndex: 'sequence', key: 'sequence' },
}, { title: t('parentMenu'), dataIndex: 'join_first_name', key: 'join_first_name', render: (text, record) => (text ? text : "-") }
{ title: t('name'), dataIndex: 'name', key: 'name' }, ];
{ title: 'Url', dataIndex: 'url', key: 'url' }, return (
{ title: t('icon'), dataIndex: 'icon', key: 'icon' }, <Table
{ title: 'Alias', dataIndex: 'alias_name', key: 'alias_name' }, rowKey="id"
{ title: t('order'), dataIndex: 'sequence', key: 'sequence' }, size="small"
{ title: t('parentMenu'), dataIndex: 'join_first_name', key: 'join_first_name', render: (text, record) => (text ? text : "-") } columns={columns}
]; dataSource={dataTable}
return ( pagination={false}
<Table />
rowKey="id" )
size="small" }, [dataTable])
columns={columns}
dataSource={dataTable} return (
pagination={false} <div>
/> <NotificationContainer />
) <SweetAlert
}, [dataTable]) show={alertDelete}
warning
return ( showCancel
<div> confirmBtnText="Delete"
<NotificationContainer /> confirmBtnBsStyle="danger"
<SweetAlert title={t('deleteConfirm')}
show={alertDelete} onConfirm={onConfirmDelete}
warning onCancel={() => cancelDelete()}
showCancel focusCancelBtn
confirmBtnText="Delete" >
confirmBtnBsStyle="danger" {t('deleteMsg')}
title={t('deleteConfirm')} </SweetAlert>
onConfirm={onConfirmDelete} <DialogForm
onCancel={() => cancelDelete()} openDialog={openDialog}
focusCancelBtn closeDialog={handleCloseDialog}
> toggleDialog={() => toggleAddDialog}
{t('deleteMsg')} typeDialog={typeDialog}
</SweetAlert> dataEdit={dataEdit}
<DialogForm clickOpenModal={clickOpenModal}
openDialog={openDialog} dataMenu={allDataMenu}
closeDialog={handleCloseDialog} />
toggleDialog={() => toggleAddDialog} <Card>
typeDialog={typeDialog} <CardHeader style={{ display: "flex", justifyContent: "space-between" }}>
dataEdit={dataEdit} <h4 className="capitalize">{pageName}</h4>
clickOpenModal={clickOpenModal} <Row>
dataMenu={allDataMenu} <Col>
/> <Input onChange={handleSearch} value={search} type="text" name="search" id="search" placeholder={t('searchMenu')} />
<Card> </Col>
<CardHeader style={{ display: "flex", justifyContent: "space-between" }}> <Col>
<h4 className="capitalize">{pageName}</h4> <Tooltip title={t('menuAdd')}>
<Row> <Button id="TooltipTambah" color="success" onClick={() => handleOpenDialog('Save')}><i className="fa fa-plus"></i></Button>
<Col> </Tooltip>
<Input onChange={handleSearch} value={search} type="text" name="search" id="search" placeholder={t('searchMenu')} /> <Tooltip title={t('exportExcel')}>
</Col> <Button style={{ marginLeft: "5px" }} id="TooltipExport" color="primary" onClick={() => handleExportExcel()}><i className="fa fa-print"></i></Button>
<Col> </Tooltip>
<Tooltip title={t('menuAdd')}> </Col>
<Button id="TooltipTambah" color="success" onClick={() => handleOpenDialog('Save')}><i className="fa fa-plus"></i></Button> </Row>
</Tooltip> </CardHeader>
<Tooltip title={t('exportExcel')}> <CardBody>
<Button style={{ marginLeft: "5px" }} id="TooltipExport" color="primary" onClick={() => handleExportExcel()}><i className="fa fa-print"></i></Button> {renderTable}
</Tooltip> <Pagination
</Col> style={{ marginTop: "25px" }}
</Row> showSizeChanger
</CardHeader> onShowSizeChange={onShowSizeChange}
<CardBody> onChange={onPagination}
{renderTable} current={currentPage}
<Pagination pageSize={rowsPerPage}
style={{ marginTop: "25px" }} total={totalPage}
showSizeChanger pageSizeOptions={["10", "15", "20", "25", "30", "35", "40"]}
onShowSizeChange={onShowSizeChange} />
onChange={onPagination} </CardBody>
current={currentPage} </Card>
pageSize={rowsPerPage} </div>
total={totalPage} )
pageSizeOptions={["10", "15", "20", "25", "30", "35", "40"]} }
/>
</CardBody> export default Index;
</Card>
</div>
)
}
export default Index;

Loading…
Cancel
Save