Browse Source

change notification alert, clean code useState, clean payload

pull/2/head
wahyuun 1 year ago
parent
commit
4e9278d90f
  1. 732
      src/views/SimproV2/Divisi/index.js

732
src/views/SimproV2/Divisi/index.js

@ -1,369 +1,363 @@
import * as XLSX from 'xlsx'; import * as XLSX from 'xlsx';
import DialogForm from './DialogForm'; import DialogForm from './DialogForm';
import React, { useState, useEffect } from 'react'; import React, { useState, useEffect } from 'react';
import SweetAlert from 'react-bootstrap-sweetalert'; import SweetAlert from 'react-bootstrap-sweetalert';
import axios from "../../../const/interceptorApi" import axios from "../../../const/interceptorApi"
import { Card, CardBody, CardHeader, Col, Row, Input, Table } from 'reactstrap'; import { Card, CardBody, CardHeader, Col, Row, Input, Table } from 'reactstrap';
import { DIVISI_LIST, DIVISI_ADD, DIVISI_EDIT, DIVISI_DELETE, DIVISI_SEARCH } from '../../../const/ApiConst'; import { DIVISI_LIST, DIVISI_ADD, DIVISI_EDIT, DIVISI_DELETE, DIVISI_SEARCH } from '../../../const/ApiConst';
import { NotificationContainer, NotificationManager } from 'react-notifications'; import { NotificationContainer, NotificationManager } from 'react-notifications';
import { Pagination, Button, Tooltip } from 'antd'; import { Pagination, Button, Tooltip } from 'antd';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
const url = ""; const url = "";
const proyek_id = localStorage.getItem('proyek_id'); const proyek_id = localStorage.getItem('proyek_id');
const role_id = localStorage.getItem('role_id'); const role_id = localStorage.getItem('role_id');
const format = "DD-MM-YYYY"; const format = "DD-MM-YYYY";
const token = window.localStorage.getItem('token'); const token = window.localStorage.getItem('token');
const config = { const config = {
headers: headers:
{ {
Authorization: `Bearer ${token}`, Authorization: `Bearer ${token}`,
"Content-type": `application/json` "Content-type": `application/json`
} }
}; };
const column = [ const column = [
{ name: "Nama" }, { name: "Nama" },
{ name: "Deskripsi" }, { name: "Deskripsi" },
] ]
const ProjectType = ({ params }) => { const ProjectType = ({ params }) => {
const token = localStorage.getItem("token") const token = localStorage.getItem("token")
const HEADER = { const HEADER = {
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
"Authorization": `Bearer ${token}` "Authorization": `Bearer ${token}`
} }
} }
const pageName = params.name; const pageName = params.name;
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 [totalPage, setTotalPage] = useState(0) const [totalPage, setTotalPage] = useState(0)
const [typeDialog, setTypeDialog] = useState('Save') const [typeDialog, setTypeDialog] = useState('Save')
const [dataDivisions, setDataDivisions] = useState([]) const [dataDivisions, setDataDivisions] = useState([])
const { t } = useTranslation() const { t } = useTranslation()
useEffect(() => { useEffect(() => {
getListDivision() getDataProjectType();
}, []) }, [currentPage, rowsPerPage, search])
useEffect(() => { useEffect(() => {
getDataProjectType() const cekData = dataExport || []
}, [currentPage, rowsPerPage, search]) if (cekData.length > 0) {
exportExcel()
useEffect(() => { }
const cekData = dataExport || [] }, [dataExport])
if (cekData.length > 0) {
exportExcel() const getListDivision = async () => {
} const listDivions = await axios
}, [dataExport]) .get(DIVISI_LIST, HEADER)
.then(res => res)
const getListDivision = async () => { .catch((error) => error.response);
const listDivions = await axios
.get(DIVISI_LIST, HEADER) if (listDivions && listDivions.data && listDivions.data.code == 200) {
.then(res => res) let arr = []
.catch((error) => error.response); for (const v in listDivions.data.data) {
arr.push(listDivions.data.data[v])
if (listDivions && listDivions.data && listDivions.data.code == 200) { }
let arr = [] setDataDivisions(arr);
for (const v in listDivions.data.data) { } else {
arr.push(listDivions.data.data[v]) NotificationManager.error('Gagal Mengambil Data!!', 'Failed');
} }
setDataDivisions(arr); }
} else { const getDataProjectType = async () => {
NotificationManager.error('Gagal Mengambil Data!!', 'Failed'); let start = 0;
} if (currentPage !== 1 && currentPage > 1) {
} start = currentPage * rowsPerPage - rowsPerPage;
const getDataProjectType = async () => { }
let start = 0; const payload = {
if (currentPage !== 1 && currentPage > 1) { columns: [
start = (currentPage * rowsPerPage) - rowsPerPage {
} name: "name",
const payload = { logic_operator: "ilike",
"columns": [ value: search,
{ operator: "AND"
"name": "name", }
"logic_operator": "ilike", ],
"value": search, "orders": {
"operator": "AND" "ascending": true,
} "columns": [
], 'id'
"orders": { ]
"ascending": true, },
"columns": [ "paging": {
'id' "length": rowsPerPage,
] "start": start
}, }
"paging": { }
"length": rowsPerPage, const result = await axios
"start": start .post(DIVISI_SEARCH, payload, HEADER)
} .then(res => res)
} .catch((error) => error.response);
const result = await axios
.post(DIVISI_SEARCH, payload, HEADER) if (result && result.data && result.data.code == 200) {
.then(res => res) let dataRes = result.data.data || [];
.catch((error) => error.response); setDatatable(dataRes);
setTotalPage(result.data.totalRecord);
if (result && result.data && result.data.code == 200) { } else {
result.data.data.map((res) => { NotificationManager.error('Gagal Mengambil Data!!', 'Failed');
res.key = res.id.toString() }
}); }
setDatatable(result.data.data); const handleExportExcel = async () => {
setTotalPage(result.data.totalRecord); let start = 0;
} else {
NotificationManager.error('Gagal Mengambil Data!!', 'Failed'); if (currentPage !== 1 && currentPage > 1) {
} start = (currentPage * rowsPerPage) - rowsPerPage
} }
const handleExportExcel = async () => {
let start = 0; const payload = {
"columns": [
if (currentPage !== 1 && currentPage > 1) { {
start = (currentPage * rowsPerPage) - rowsPerPage "name": "name",
} "logic_operator": "like",
"value": search,
const payload = { "operator": "AND"
"columns": [ }
{ ],
"name": "name", "orders": {
"logic_operator": "like", "ascending": true,
"value": search, "columns": [
"operator": "AND" 'id'
} ]
], },
"orders": { "paging": {
"ascending": true, "length": rowsPerPage,
"columns": [ "start": start
'id' }
] }
},
"paging": { const result = await axios
"length": rowsPerPage, .post(DIVISI_SEARCH, payload, HEADER)
"start": start .then(res => res)
} .catch((error) => error.response);
} if (result && result.data && result.data.code == 200) {
let resData = result.data.data;
const result = await axios const excelData = [];
.post(DIVISI_SEARCH, payload, HEADER) resData.map((val, index) => {
.then(res => res) let dataRow = {
.catch((error) => error.response); "Nama Divisi": val.name,
if (result && result.data && result.data.code == 200) { "Deskripsi": val.description,
let resData = result.data.data; }
const excelData = []; excelData.push(dataRow)
resData.map((val, index) => { })
let dataRow = { await setDataExport(excelData)
"Nama Divisi": val.name, } else {
"Deskripsi": val.description, 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 handleSearch = e => {
XLSX.utils.book_append_sheet(wb, ws, `Data ${pageName}`); const value = e.target.value
XLSX.writeFile(wb, fileName); setSearch(value);
setDataExport([]) setCurrentPage(1)
} };
const handleSearch = e => { const handleOpenDialog = (type) => {
const value = e.target.value setOpenDialog(true)
setSearch(value); setTypeDialog(type)
setCurrentPage(1) }
};
const handleEdit = (data) => {
const handleOpenDialog = (type) => { setDataEdit(data)
setOpenDialog(true) handleOpenDialog('Edit');
setTypeDialog(type) }
}
const handleDelete = async (id) => {
const handleEdit = (data) => { await setAlertDelete(true)
setDataEdit(data) await setIdDelete(id)
handleOpenDialog('Edit'); }
}
const handleCloseDialog = (type, data) => {
const handleDelete = async (id) => { if (type === "save") {
await setAlertDelete(true) saveProjectType(data);
await setIdDelete(id) } else if (type === "edit") {
} editMaterialR(data);
}
const handleCloseDialog = (type, data) => { setDataEdit([])
if (type === "save") { setOpenDialog(false)
saveProjectType(data); }
} else if (type === "edit") {
editMaterialR(data); const saveProjectType = async (data) => {
} const formData = data
setDataEdit([]) const result = await axios.post(DIVISI_ADD, formData, HEADER)
setOpenDialog(false) .then(res => res)
} .catch((error) => error.response);
if (result && result.data && result.data.code === 200) {
const saveProjectType = async (data) => { getDataProjectType()
const formData = data NotificationManager.success(`Data berhasil ditambahkan`, 'Success!!');
const result = await axios.post(DIVISI_ADD, formData, HEADER) } else {
.then(res => res) NotificationManager.error(`Data gagal ditambahkan`, 'Failed!!');
.catch((error) => error.response); }
if (result && result.data && result.data.code === 200) { }
getDataProjectType()
NotificationManager.success(`Data berhasil ditambah`, 'Success!!'); const editMaterialR = async (data) => {
} else { let urlEdit = DIVISI_EDIT(data.id)
NotificationManager.error(`${result.data.message}`, 'Failed!!'); const formData = data
} const result = await axios.put(urlEdit, formData, HEADER)
} .then(res => res)
.catch((error) => error.response);
const editMaterialR = async (data) => { if (result && result.data && result.data.code === 200) {
let urlEdit = DIVISI_EDIT(data.id) getDataProjectType();
const formData = data NotificationManager.success(`Data berhasil diubah`, 'Success!!');
const result = await axios.put(urlEdit, formData, HEADER) } else {
.then(res => res) NotificationManager.error(`Data gagal diubah`, `Failed!!`);
.catch((error) => error.response); }
if (result && result.data && result.data.code === 200) { }
getDataProjectType();
NotificationManager.success(`Data berhasil diedit`, 'Success!!'); const toggleAddDialog = () => {
} else { setOpenDialog(!openDialog)
NotificationManager.error(`Data gagal di edit`, `Failed!!`); }
}
} const onConfirmDelete = async () => {
let url = DIVISI_DELETE(idDelete);
const toggleAddDialog = () => { const result = await axios.delete(url, config)
setOpenDialog(!openDialog) .then(res => res)
} .catch((error) => error.response);
const onConfirmDelete = async () => { if (result && result.data && result.data.code === 200) {
let url = DIVISI_DELETE(idDelete); getDataProjectType()
const result = await axios.delete(url, config) setIdDelete(0)
.then(res => res) setAlertDelete(false)
.catch((error) => error.response); NotificationManager.success(`Data berhasil dihapus!`, 'Success!!');
} else {
if (result && result.data && result.data.code === 200) { setIdDelete(0)
getDataProjectType() setAlertDelete(false)
setIdDelete(0) NotificationManager.error(`Data gagal dihapus!}`, 'Failed!!');
setAlertDelete(false) }
NotificationManager.success(`Data berhasil dihapus!`, 'Success!!'); }
} else {
setIdDelete(0) const cancelDelete = () => {
setAlertDelete(false) setAlertDelete(false)
NotificationManager.error(`Data gagal dihapus!}`, 'Failed!!'); setIdDelete(0)
} }
}
const onShowSizeChange = (current, pageSize) => {
const cancelDelete = () => { setRowsPerPage(pageSize)
setAlertDelete(false) }
setIdDelete(0)
} const onPagination = (current, pageSize) => {
setCurrentPage(current)
const onShowSizeChange = (current, pageSize) => { }
setRowsPerPage(pageSize)
} const dataNotAvailable = () => {
if (dataTable.length === 0) {
const onPagination = (current, pageSize) => { return (
setCurrentPage(current) <tr>
} <td align="center" colSpan="3">{t('noData')}</td>
</tr>
const dataNotAvailable = () => { )
if (dataTable.length === 0) { }
return ( }
<tr>
<td align="center" colSpan="3">{t('noData')}</td> return (
</tr> <div>
) <NotificationContainer />
} <SweetAlert
} 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} dataParent={allDataMenu}
closeDialog={handleCloseDialog} dataDivisions={dataDivisions}
toggleDialog={() => toggleAddDialog} />
typeDialog={typeDialog} <Card>
dataEdit={dataEdit} <CardHeader style={{ display: "flex", justifyContent: "space-between" }}>
clickOpenModal={clickOpenModal} <h4 className="capitalize">{pageName}</h4>
dataParent={allDataMenu} <Row>
dataDivisions={dataDivisions} <Col>
/> <Input onChange={handleSearch} value={search} type="text" name="search" id="search" placeholder={t('searchDivision')} />
<Card> </Col>
<CardHeader style={{ display: "flex", justifyContent: "space-between" }}> <Col>
<h4 className="capitalize">{pageName}</h4> <Tooltip title={t('divisionAdd')}>
<Row> <Button style={{ background: "#4caf50", color: "#fff" }} 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('searchDivision')} /> <Tooltip title={t('exportExcel')}>
</Col> <Button style={{ marginLeft: "5px" }} onClick={() => handleExportExcel()}><i className="fa fa-print"></i></Button>
<Col> </Tooltip>
<Tooltip title={t('divisionAdd')}> </Col>
<Button style={{ background: "#4caf50", color: "#fff" }} onClick={() => handleOpenDialog('Save')}><i className="fa fa-plus"></i></Button> </Row>
</Tooltip> </CardHeader>
<Tooltip title={t('exportExcel')}> <CardBody>
<Button style={{ marginLeft: "5px" }} onClick={() => handleExportExcel()}><i className="fa fa-print"></i></Button> <Table responsive striped hover>
</Tooltip> <thead>
</Col> <tr>
</Row> <th>Aksi</th>
</CardHeader> {column.map((i, index) => {
<CardBody> return (
<Table responsive striped hover> <th key={index} scope="row">{i.name}</th>
<thead> )
<tr> })}
<th>Aksi</th> </tr>
{column.map((i, index) => { </thead>
return ( <tbody>
<th key={index} scope="row">{i.name}</th> {dataNotAvailable()}
) {dataTable.map((n, index) => {
})} return (
</tr> <tr key={n.id}>
</thead> <td className='nowrap'>
<tbody> <Tooltip title={t('delete')}>
{dataNotAvailable()} <i id="TooltipDelete" className="fa fa-trash" style={{ color: 'red', marginRight: 10, cursor: "pointer" }} onClick={() => handleDelete(n.id)}></i>
{dataTable.map((n, index) => { </Tooltip>
return ( <Tooltip title={t('edit')}>
<tr key={n.id}> <i id="TooltipEdit" className="fa fa-edit" style={{ color: 'green', cursor: "pointer" }} onClick={() => handleEdit(n)}></i>
<td className='nowrap'> </Tooltip>
<Tooltip title={t('delete')}> </td>
<i id="TooltipDelete" className="fa fa-trash" style={{ color: 'red', marginRight: 10, cursor: "pointer" }} onClick={() => handleDelete(n.id)}></i> <td>{n.name}</td>
</Tooltip> <td>{n.description}</td>
<Tooltip title={t('edit')}> </tr>
<i id="TooltipEdit" className="fa fa-edit" style={{ color: 'green', cursor: "pointer" }} onClick={() => handleEdit(n)}></i> )
</Tooltip> })}
</td> </tbody>
<td>{n.name}</td> </Table>
<td>{n.description}</td> </CardBody>
</tr> </Card>
) </div>
})} )
</tbody> }
</Table>
</CardBody> export default ProjectType;
</Card>
</div>
)
}
export default ProjectType;

Loading…
Cancel
Save