Browse Source

endline fix

pull/1/head
wahyu 1 year ago
parent
commit
078924802a
  1. 198
      src/views/Master/ConfigAlert/DialogForm.js
  2. 344
      src/views/Master/ConfigAlert/index.js
  3. 918
      src/views/Master/MasterRoles/index.js

198
src/views/Master/ConfigAlert/DialogForm.js

@ -1,99 +1,99 @@
import React, { useEffect, useState } from 'react'
import { Modal, ModalHeader, ModalBody, ModalFooter } from 'reactstrap';
import { Button, Form, FormGroup, Label, Input, Col, Row } from 'reactstrap';
import { Select } from 'antd';
import moment from 'moment';
import 'antd/dist/antd.css';
const { Option } = Select
const DialogForm = ({openDialog, closeDialog, toggleDialog, typeDialog, dataEdit, dataMenu}) => {
const [id, setId] = useState(0)
const [name, setName] = useState('')
const [descripton, setDescription] = useState('')
const [status, setStatus] = useState('')
useEffect(()=> {
if(typeDialog==="Edit"){
console.log("data edit", dataEdit)
setId(dataEdit.id)
setName(dataEdit.nama)
setDescription(dataEdit.keterangan)
setStatus(dataEdit.status)
}else{
setId(0)
setName('')
setDescription('')
setStatus('')
}
},[dataEdit,openDialog])
const handleSave = () => {
let data = '';
if(typeDialog==="Save"){
data = {
nama:name,
keterangan:descripton,
status
}
closeDialog('save', data);
}else{
data = {
id,
nama:name,
keterangan:descripton,
status
}
closeDialog('edit', data);
}
}
const handleCancel = () => {
closeDialog('cancel', 'none')
setId(0)
setName('')
setDescription('')
setStatus('')
}
const renderForm = () => {
return(
<Form>
<FormGroup>
<Label className="capitalize">Nama Alert</Label>
<Input type="text" value={name} onChange={(e)=> setName(e.target.value)} placeholder={`Waspang tidak sesuai target..`}/>
</FormGroup>
<FormGroup>
<Label className="capitalize">Keterangan</Label>
<Input type="text" value={descripton} onChange={(e)=> setDescription(e.target.value)} placeholder={`Rencana vs actual tidak sesuai..`} />
</FormGroup>
<FormGroup>
<Label className="capitalize">Status</Label>
<Input type="text" value={status} onChange={(e)=> setStatus(e.target.value)} placeholder={`Warning..`} />
</FormGroup>
</Form>
)
}
return (
<Modal size="lg" isOpen={openDialog} toggle={toggleDialog}>
<ModalHeader className="capitalize" toggle={closeDialog}>{typeDialog=="Save" ? `Tambah` : "Edit"} Config Alert</ModalHeader>
<ModalBody>
{renderForm()}
</ModalBody>
<ModalFooter>
<Button color="primary" onClick={() => handleSave()}>{typeDialog}</Button>{' '}
<Button className="capitalize" color="secondary" onClick={() => handleCancel()}>Batal</Button>
</ModalFooter>
</Modal>
)
}
export default DialogForm;
import React, { useEffect, useState } from 'react'
import { Modal, ModalHeader, ModalBody, ModalFooter } from 'reactstrap';
import { Button, Form, FormGroup, Label, Input, Col, Row } from 'reactstrap';
import { Select } from 'antd';
import moment from 'moment';
import 'antd/dist/antd.css';
const { Option } = Select
const DialogForm = ({openDialog, closeDialog, toggleDialog, typeDialog, dataEdit, dataMenu}) => {
const [id, setId] = useState(0)
const [name, setName] = useState('')
const [descripton, setDescription] = useState('')
const [status, setStatus] = useState('')
useEffect(()=> {
if(typeDialog==="Edit"){
console.log("data edit", dataEdit)
setId(dataEdit.id)
setName(dataEdit.nama)
setDescription(dataEdit.keterangan)
setStatus(dataEdit.status)
}else{
setId(0)
setName('')
setDescription('')
setStatus('')
}
},[dataEdit,openDialog])
const handleSave = () => {
let data = '';
if(typeDialog==="Save"){
data = {
nama:name,
keterangan:descripton,
status
}
closeDialog('save', data);
}else{
data = {
id,
nama:name,
keterangan:descripton,
status
}
closeDialog('edit', data);
}
}
const handleCancel = () => {
closeDialog('cancel', 'none')
setId(0)
setName('')
setDescription('')
setStatus('')
}
const renderForm = () => {
return(
<Form>
<FormGroup>
<Label className="capitalize">Nama Alert</Label>
<Input type="text" value={name} onChange={(e)=> setName(e.target.value)} placeholder={`Waspang tidak sesuai target..`}/>
</FormGroup>
<FormGroup>
<Label className="capitalize">Keterangan</Label>
<Input type="text" value={descripton} onChange={(e)=> setDescription(e.target.value)} placeholder={`Rencana vs actual tidak sesuai..`} />
</FormGroup>
<FormGroup>
<Label className="capitalize">Status</Label>
<Input type="text" value={status} onChange={(e)=> setStatus(e.target.value)} placeholder={`Warning..`} />
</FormGroup>
</Form>
)
}
return (
<Modal size="lg" isOpen={openDialog} toggle={toggleDialog}>
<ModalHeader className="capitalize" toggle={closeDialog}>{typeDialog=="Save" ? `Tambah` : "Edit"} Config Alert</ModalHeader>
<ModalBody>
{renderForm()}
</ModalBody>
<ModalFooter>
<Button color="primary" onClick={() => handleSave()}>{typeDialog}</Button>{' '}
<Button className="capitalize" color="secondary" onClick={() => handleCancel()}>Batal</Button>
</ModalFooter>
</Modal>
)
}
export default DialogForm;

344
src/views/Master/ConfigAlert/index.js

@ -1,172 +1,172 @@
import Bell from '@iconify/icons-ion/notifications-outline';
import BellOff from '@iconify/icons-ion/notifications-off-outline';
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { CALERTUSER_SEARCH,CONFIGALERT_SEARCH,CALERTUSER_DELETE, CALERTUSER_ADD } from '../../../const/ApiConst.js';
import { Card as ACard,Row, Col, Switch } from 'antd';
import { Card, CardBody, CardHeader, Input } from 'reactstrap';
import { Icon } from '@iconify/react';
import { NotificationContainer, NotificationManager } from 'react-notifications';
const token = window.localStorage.getItem('token');
const userID = window.localStorage.getItem('user_id');
const Index = ({params}) => {
const [alertUser, setAlertUser] = useState([])
const [checked, setChecked] = useState({})
const [dataTable, setDatatable] = useState([])
const [onSetSwitch, setOnSetSwitch] = useState(false)
const pageName = params.name;
const config = {
headers:
{
Authorization : `Bearer ${token}`,
"Content-type" : `application/json`
}
};
useEffect(()=> {
getDataConfigAlert();
},[])
useEffect(() => {
getDataConfigAlertUser();
},[dataTable])
const getDataConfigAlert = async () => {
const payload = {
"paging": {"start": 0, "length": -1},
"columns": [
{"name": "nama", "logic_operator": "ilike", "value": "", "operator": "AND"}
],
"joins": [],
"orders": {"columns": ["id"], "ascending": false}
}
const result = await axios
.post(CONFIGALERT_SEARCH, payload, config)
.then(res => res)
.catch((error) => error.response);
if(result && result.data && result.data.code == 200){
let resData = result.data.data
let checkedAlert = {}
resData.map((val, index) => {
checkedAlert[val.id] = false
});
setChecked(checkedAlert);
setDatatable(resData);
}else{
NotificationManager.error('Gagal Mengambil Data!!', 'Failed');
}
}
const getDataConfigAlertUser = async () => {
const payload = {
"paging": {"start": 0, "length": -1},
"columns": [
{"name": "user_id", "logic_operator": "=", "value": localStorage.getItem('user_id'), "operator": "AND"}
],
"joins": [],
"orders": {"columns": ["id"], "ascending": false}
}
const result = await axios
.post(CALERTUSER_SEARCH, payload, config)
.then(res => res)
.catch((error) => error.response);
if(result && result.data && result.data.code == 200){
let resData = result.data.data
let configAlert = [];
resData.map((val, index) => {
configAlert.push(val.config_alert_id);
let indexRes = dataTable.findIndex(x => x.id === val.config_alert_id);
if(indexRes >= 0){
let id = dataTable[indexRes].id;
let tempChecked = checked;
tempChecked[id] = true;
setChecked(tempChecked);
}
});
window.localStorage.setItem('userConfigAlert', configAlert.join());
setOnSetSwitch(false)
setAlertUser(result.data.data);
}else{
NotificationManager.error('Gagal Mengambil Data!!', 'Failed');
}
}
const onChange = (checked, id) => {
setOnSetSwitch(true)
if(checked){
addConfigAlertUser(id);
}else{
setDeleteConfigAlertUser(id)
}
}
const addConfigAlertUser = async (id) => {
const formData = {
"user_id":parseInt(localStorage.getItem('user_id')),
"config_alert_id":id
}
const result = await axios.post(CALERTUSER_ADD, formData, config)
.then(res => res)
.catch((error) => error.response);
if(result && result.data && result.data.code===200){
getDataConfigAlertUser();
}
}
const setDeleteConfigAlertUser = async (id) => {
let indexCek = alertUser.findIndex(x => x.user_id === parseInt(localStorage.getItem('user_id')) && x.config_alert_id === id);
if(indexCek >= 0){
let idAlert = alertUser[indexCek].id
deleteConfigAlertUser(idAlert)
}
}
const deleteConfigAlertUser = async (id) => {
const url = CALERTUSER_DELETE(id)
const result = await axios.delete(url, config)
.then(res => res)
.catch((error) => error.response);
if (result && result.data && result.data.code === 200) {
getDataConfigAlert();
}
}
return (
<div>
<NotificationContainer />
<Card>
<CardHeader style={{ display: "flex", justifyContent: "space-between" }}>
<h4 className="capitalize">{pageName}</h4>
</CardHeader>
<CardBody>
<Row gutter={16}>
{dataTable.map((val, index) => (
<Col key={index} md={{span:5,offset:1}} xs={{span:11,offset:1}}>
<ACard style={{height:"100%"}} actions={[
<Switch checked={checked[val.id] ? true : false} onChange={(checked) => onChange(checked, val.id)} disabled={onSetSwitch} />,
]}>
<div style={{height:'100%',width:'100%',display:'flex',justifyContent:'center', alignItems:'center', textAlign:'center', flexDirection:'column'}}>
<i style={{marginBottom:"25px"}}><Icon icon={checked[val.id] ? Bell : BellOff} color="black" width="100" height="100" /></i>
<p style={{marginBottom:"0"}}>{val.nama}</p>
</div>
</ACard>
</Col>
))}
</Row>
</CardBody>
</Card>
</div>
)
}
export default Index;
import Bell from '@iconify/icons-ion/notifications-outline';
import BellOff from '@iconify/icons-ion/notifications-off-outline';
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { CALERTUSER_SEARCH,CONFIGALERT_SEARCH,CALERTUSER_DELETE, CALERTUSER_ADD } from '../../../const/ApiConst.js';
import { Card as ACard,Row, Col, Switch } from 'antd';
import { Card, CardBody, CardHeader, Input } from 'reactstrap';
import { Icon } from '@iconify/react';
import { NotificationContainer, NotificationManager } from 'react-notifications';
const token = window.localStorage.getItem('token');
const userID = window.localStorage.getItem('user_id');
const Index = ({params}) => {
const [alertUser, setAlertUser] = useState([])
const [checked, setChecked] = useState({})
const [dataTable, setDatatable] = useState([])
const [onSetSwitch, setOnSetSwitch] = useState(false)
const pageName = params.name;
const config = {
headers:
{
Authorization : `Bearer ${token}`,
"Content-type" : `application/json`
}
};
useEffect(()=> {
getDataConfigAlert();
},[])
useEffect(() => {
getDataConfigAlertUser();
},[dataTable])
const getDataConfigAlert = async () => {
const payload = {
"paging": {"start": 0, "length": -1},
"columns": [
{"name": "nama", "logic_operator": "ilike", "value": "", "operator": "AND"}
],
"joins": [],
"orders": {"columns": ["id"], "ascending": false}
}
const result = await axios
.post(CONFIGALERT_SEARCH, payload, config)
.then(res => res)
.catch((error) => error.response);
if(result && result.data && result.data.code == 200){
let resData = result.data.data
let checkedAlert = {}
resData.map((val, index) => {
checkedAlert[val.id] = false
});
setChecked(checkedAlert);
setDatatable(resData);
}else{
NotificationManager.error('Gagal Mengambil Data!!', 'Failed');
}
}
const getDataConfigAlertUser = async () => {
const payload = {
"paging": {"start": 0, "length": -1},
"columns": [
{"name": "user_id", "logic_operator": "=", "value": localStorage.getItem('user_id'), "operator": "AND"}
],
"joins": [],
"orders": {"columns": ["id"], "ascending": false}
}
const result = await axios
.post(CALERTUSER_SEARCH, payload, config)
.then(res => res)
.catch((error) => error.response);
if(result && result.data && result.data.code == 200){
let resData = result.data.data
let configAlert = [];
resData.map((val, index) => {
configAlert.push(val.config_alert_id);
let indexRes = dataTable.findIndex(x => x.id === val.config_alert_id);
if(indexRes >= 0){
let id = dataTable[indexRes].id;
let tempChecked = checked;
tempChecked[id] = true;
setChecked(tempChecked);
}
});
window.localStorage.setItem('userConfigAlert', configAlert.join());
setOnSetSwitch(false)
setAlertUser(result.data.data);
}else{
NotificationManager.error('Gagal Mengambil Data!!', 'Failed');
}
}
const onChange = (checked, id) => {
setOnSetSwitch(true)
if(checked){
addConfigAlertUser(id);
}else{
setDeleteConfigAlertUser(id)
}
}
const addConfigAlertUser = async (id) => {
const formData = {
"user_id":parseInt(localStorage.getItem('user_id')),
"config_alert_id":id
}
const result = await axios.post(CALERTUSER_ADD, formData, config)
.then(res => res)
.catch((error) => error.response);
if(result && result.data && result.data.code===200){
getDataConfigAlertUser();
}
}
const setDeleteConfigAlertUser = async (id) => {
let indexCek = alertUser.findIndex(x => x.user_id === parseInt(localStorage.getItem('user_id')) && x.config_alert_id === id);
if(indexCek >= 0){
let idAlert = alertUser[indexCek].id
deleteConfigAlertUser(idAlert)
}
}
const deleteConfigAlertUser = async (id) => {
const url = CALERTUSER_DELETE(id)
const result = await axios.delete(url, config)
.then(res => res)
.catch((error) => error.response);
if (result && result.data && result.data.code === 200) {
getDataConfigAlert();
}
}
return (
<div>
<NotificationContainer />
<Card>
<CardHeader style={{ display: "flex", justifyContent: "space-between" }}>
<h4 className="capitalize">{pageName}</h4>
</CardHeader>
<CardBody>
<Row gutter={16}>
{dataTable.map((val, index) => (
<Col key={index} md={{span:5,offset:1}} xs={{span:11,offset:1}}>
<ACard style={{height:"100%"}} actions={[
<Switch checked={checked[val.id] ? true : false} onChange={(checked) => onChange(checked, val.id)} disabled={onSetSwitch} />,
]}>
<div style={{height:'100%',width:'100%',display:'flex',justifyContent:'center', alignItems:'center', textAlign:'center', flexDirection:'column'}}>
<i style={{marginBottom:"25px"}}><Icon icon={checked[val.id] ? Bell : BellOff} color="black" width="100" height="100" /></i>
<p style={{marginBottom:"0"}}>{val.nama}</p>
</div>
</ACard>
</Col>
))}
</Row>
</CardBody>
</Card>
</div>
)
}
export default Index;

918
src/views/Master/MasterRoles/index.js

@ -1,459 +1,459 @@
import * as XLSX from 'xlsx';
import DialogForm from './DialogForm';
import DialogMenuRoles from './DialogMenuRoles';
import React, { Component, useMemo } from 'react';
import SweetAlert from 'react-bootstrap-sweetalert';
import axios from 'axios';
import { Button } from 'reactstrap';
import { Card, CardBody, CardHeader, Col, Row, Input } from 'reactstrap';
import { NotificationContainer, NotificationManager } from 'react-notifications';
import { Pagination, Tooltip, Table } from 'antd';
import { ROLE_ADD, ROLE_SEARCH, ROLE_EDIT, ROLE_DELETE, ROLEMENU_ADD, ROLEMENU_SEARCH, ROLEMENU_DELETE_ROLE } from '../../../const/ApiConst.js';
import { withTranslation } from 'react-i18next';
const token = window.localStorage.getItem('token');
const BASE_URL = "http://siopas.co.id/custom-php/api/geohr/";
const config = {
headers:
{
Authorization: `Bearer ${token}`,
"Content-type": `application/json`
}
};
const momentFormat = 'HH:mm';
const LENGTH_DATA = 10
class index extends Component {
constructor(props) {
super(props)
this.state = {
alertDelete: false,
alertNotDelete: false,
currentPage: 1,
dataEdit: null,
dataExport: [],
dataGs: [],
dataIdHo: [],
dataTable: [],
dialogMenuForm: false,
idDelete: 0,
idRoles: 0,
menuRoles: [],
openDialog: false,
page: 0,
rowsPerPage: LENGTH_DATA,
search: "",
tooltipDelete: false,
tooltipEdit: false,
tooltipExport: false,
tooltipImport: false,
tooltipMenu: false,
tooltipTambah: false,
totalPage: 0,
typeDialog: 'Save',
}
this.columns = [
{
title: this.props.t('action'),
dataIndex: '',
key: 'x',
className: 'nowrap',
render: (text, record) => <>
<Tooltip title={this.props.t('menuRoles')}>
<i className="cil-menu" style={{ color: 'green', marginRight: 10, cursor: "pointer" }} onClick={() => this.handleMenuRoles(text.id)}></i>
</Tooltip>
<Tooltip title={this.props.t('delete')}>
<i className="fa fa-trash" style={{ color: 'red', marginRight: 10, cursor: "pointer" }} onClick={() => this.handleDelete(text.id)}></i>
</Tooltip>
<Tooltip title={this.props.t('edit')}>
<i className="fa fa-edit" style={{ color: 'green', cursor: "pointer" }} onClick={() => this.handleEdit(text)}></i>
</Tooltip>
</>,
},
{ title: this.props.t('nameRole'), dataIndex: 'name', key: 'name', className: "nowrap" },
{ title: this.props.t('description'), dataIndex: 'description', key: 'description' },
]
}
async componentDidMount() {
this.getDataRoles();
}
async componentDidUpdate(prevProps, prevState) {
const { search } = this.state
if (search !== prevState.search) this.getDataRoles()
if (prevProps.dataExport !== this.props.dataExport && this.props.dataExport.length > 0) {
this.handleExportExcel();
}
}
handleSearch = e => {
const value = e.target.value
this.setState({ search: value, currentPage: 1 })
};
getDataRoles = async () => {
let start = 0;
if (this.state.currentPage !== 1 && this.state.currentPage > 1) {
start = (this.state.currentPage * this.state.rowsPerPage) - this.state.rowsPerPage
}
const formData = {
"paging": { "start": start, "length": this.state.rowsPerPage },
"columns": [
{ "name": "name", "logic_operator": "ilike", "value": this.state.search, "operator": "AND" }
],
"joins": [],
"orders": { "columns": ["id"], "ascending": false }
}
const result = await axios
.post(ROLE_SEARCH, formData, config)
.then(res => res)
.catch((error) => error.response);
if (result && result.data && result.data.code == 200) {
this.setState({ dataTable: result.data.data, totalPage: result.data.totalRecord });
} else {
NotificationManager.error('Gagal Mengambil Data!!', 'Failed');
}
}
handleOpenDialog = (type) => {
this.setState({ openDialog: true, typeDialog: type })
this.showChildDialog();
}
handleCloseDialog = (type, data) => {
if (type === "save") {
this.saveRole(data);
} else if (type === "edit") {
this.editRole(data);
}
this.setState({ openDialog: false })
}
handleOpenDialogMr = () => {
this.setState({ dialogMenuForm: true })
this.showMenuRolesDialog();
}
handleCloseDialogMr = (type, data) => {
if (type === "save") {
this.saveMenuRoles(data)
}
this.setState({ dialogMenuForm: false })
}
toggleAddDialog = () => {
this.setState({ openDialog: !this.state.openDialog })
}
onConfirmDelete = async () => {
const { idDelete } = this.state
const url = ROLE_DELETE(idDelete)
const result = await axios.delete(url, config)
.then(res => res)
.catch((error) => error.response);
if (result && result.data && result.data.code === 200) {
this.deleteCurrentRoleMenu(idDelete)
this.getDataRoles()
this.setState({ idDelete: 0, alertDelete: false })
NotificationManager.success(`Data role berhasil dihapus`, 'Success!!');
} else {
this.setState({ idDelete: 0, alertDelete: false })
NotificationManager.error(`Data role gagal dihapus`, 'Failed!!');
}
}
saveRole = async (data) => {
const formData = {
name: data.name,
description: data.description
}
const result = await axios.post(ROLE_ADD, formData, config)
.then(res => res)
.catch((error) => error.response);
if (result && result.data && result.data.code === 200) {
this.getDataRoles();
NotificationManager.success(`Data role berhasil ditambah`, 'Success!!');
} else {
NotificationManager.error(`${result.data.message}`, 'Failed!!');
}
}
editRole = async (data) => {
const formData = {
name: data.name,
description: data.description
}
const url = ROLE_EDIT(data.id)
const result = await axios.put(url, formData, config)
.then(res => res)
.catch((error) => error.response);
if (result && result.data && result.data.code === 200) {
this.getDataRoles();
NotificationManager.success(`Data role berhasil diedit`, 'Success!!');
} else {
NotificationManager.error(`Data role gagal di edit`, `Failed!!`);
}
}
handleEdit = (data) => {
this.setState({ dataEdit: data });
this.handleOpenDialog('Edit');
}
handleDelete = (id) => {
id == '1' ? this.setState({ alertNotDelete: true }) :
this.setState({ alertDelete: true, idDelete: id });
}
onShowSizeChange = (current, pageSize) => {
this.setState({ rowsPerPage: pageSize }, () => {
this.getDataRoles();
})
}
onPagination = (current, pageSize) => {
this.setState({ currentPage: current, page: (current - 1) * pageSize }, () => {
this.getDataRoles();
})
}
toggle = (param) => {
if (param === "edit") {
this.setState(prevState => ({ tooltipEdit: !prevState.tooltipEdit }))
} else if (param === "delete") {
this.setState(prevState => ({ tooltipDelete: !prevState.tooltipDelete }))
} else if (param === "menu") {
this.setState(prevState => ({ tooltipMenu: !prevState.tooltipMenu }))
} else if (param === "tambah") {
this.setState(prevState => ({ tooltipTambah: !prevState.tooltipTambah }))
} else if (param === "export") {
this.setState(prevState => ({ tooltipExport: !prevState.tooltipExport }))
}
}
dataNotAvailable = () => {
if (this.state.dataTable.length === 0) {
return (
<tr>
<td align="center" colSpan="3">{this.props.t('noData')}</td>
</tr>
)
}
}
handleMenuRoles = async (id) => {
const formData = {
"paging": { "start": 0, "length": -1 },
"columns": [
{ "name": "role_id", "logic_operator": "=", "value": `${id}`, "operator": "AND" }
],
"joins": [],
"orders": { "columns": ["id"], "ascending": false }
}
const result = await axios
.post(ROLEMENU_SEARCH, formData, config)
.then(res => res)
.catch((error) => error.response);
if (result && result.data && result.data.code == 200) {
this.setState({ menuRoles: result.data.data, idRoles: id }, () => {
this.handleOpenDialogMr();
});
} else {
}
}
saveMenuRoles = async (dataArray) => {
let payloadArray = dataArray || []
if (payloadArray.length > 0) {
await this.deleteCurrentRoleMenu(payloadArray[0].roles_id)
}
let promises = []
let result = []
dataArray.map((val, index) => {
if (val.checked === true) {
const formData = {
menu_id: val.menu_id,
role_id: val.roles_id
}
promises.push(axios.post(ROLEMENU_ADD, formData, config)
.then(res => result.push(res)))
}
})
await Promise.all(promises);
if (result) {
if (result.length > 0) {
if (result[0].data.code === 200) {
this.getDataRoles();
NotificationManager.success('Data roles berhasil ditambahkan!!', 'Success!!');
} else {
NotificationManager.error(`${result[0].data.message}`, 'Failed!!');
}
}
}
}
deleteCurrentRoleMenu = async (id) => {
let urlDel = ROLEMENU_DELETE_ROLE(id)
const result = await axios.delete(urlDel, config)
.then(res => res)
.catch((error) => error.response);
if (result && result.data && result.data.code === 200) {
return true
} else {
return false
}
}
handleExportExcel = async () => {
let start = 0;
let end = "ALL";
const formData = {
"paging": { "start": start, "length": this.state.rowsPerPage },
"columns": [
{ "name": "name", "logic_operator": "ilike", "value": this.state.search, "operator": "AND" }
],
"joins": [],
"orders": { "columns": ["id"], "ascending": false }
}
const result = await axios
.post(ROLE_SEARCH, formData, config)
.then(res => res)
.catch((error) => error.response);
if (result && result.data && result.statusText == "OK") {
const dataRes = result.data.data || [];
const dataExport = [];
dataRes.map((val, index) => {
let row = {
Nama: val.name,
Deskripsi: val.description
}
dataExport.push(row);
})
this.setState({ dataExport: dataExport }, () => {
this.exportExcel();
});
} else {
NotificationManager.error('Failed retreiving data!!', 'Failed');
}
}
exportExcel = () => {
const dataExcel = this.state.dataExport || [];
const fileName = "Data Roles.xlsx";
const ws = XLSX.utils.json_to_sheet(dataExcel);
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, 'Data Roles');
XLSX.writeFile(wb, fileName);
}
render() {
const { t } = this.props;
const { tooltipTambah, tooltipExport, dialogMenuForm, dataTable, openDialog, currentPage, rowsPerPage, totalPage, search, tooltipEdit, tooltipDelete, tooltipMenu } = this.state
let noSeq = 0;
return (
<div>
<NotificationContainer />
<SweetAlert
show={this.state.alertDelete}
warning
showCancel
confirmBtnText="Delete"
confirmBtnBsStyle="danger"
title={this.props.t('deleteConfirm')}
onConfirm={this.onConfirmDelete}
onCancel={() => this.setState({ alertDelete: false, idDelete: 0 })}
focusCancelBtn
>
{this.props.t('deleteMsg')}
</SweetAlert>
<SweetAlert
show={this.state.alertNotDelete}
warning
confirmBtnText="Can't Delete"
confirmBtnBsStyle="danger"
title="Data can't be delete!"
onConfirm={() => this.setState({ alertNotDelete: false })}
>
Data tipe roles tidak dapat di hapus!!
</SweetAlert>
<DialogForm
openDialog={openDialog}
closeDialog={this.handleCloseDialog}
toggleDialog={() => this.toggleAddDialog}
typeDialog={this.state.typeDialog}
dataEdit={this.state.dataEdit}
showDialog={showDialog => this.showChildDialog = showDialog}
dataHs={this.state.dataIdHo}
/>
<DialogMenuRoles
openDialog={dialogMenuForm}
closeDialog={this.handleCloseDialogMr}
idRoles={this.state.idRoles}
showDialog={showDialog => this.showMenuRolesDialog = showDialog}
menuRoles={this.state.menuRoles}
/>
<Card>
<CardHeader style={{ display: "flex", justifyContent: "space-between" }}>
<h4>{this.props.params.name}</h4>
<Row>
<Col>
<Input onChange={this.handleSearch} value={search} type="text" name="search" id="search" placeholder={this.props.t('searchRoles')} />
</Col>
<Col>
<Tooltip title={this.props.t('rolesAdd')}>
<Button id="TooltipTambah" color="success" onClick={() => this.handleOpenDialog('Save')}><i className="fa fa-plus"></i></Button>
</Tooltip>
<Tooltip title={this.props.t('exportExcel')}>
<Button style={{ marginLeft: "5px" }} id="TooltipExport" color="primary" onClick={() => this.handleExportExcel()}><i className="fa fa-print"></i></Button>
</Tooltip>
</Col>
</Row>
</CardHeader>
<CardBody>
<Table
rowKey="id"
size="small"
columns={this.columns}
dataSource={dataTable}
pagination={false}
bordered={false}
/>
<Pagination
style={{ marginTop: "25px" }}
showSizeChanger
onShowSizeChange={this.onShowSizeChange}
onChange={this.onPagination}
defaultCurrent={currentPage}
pageSize={rowsPerPage}
total={totalPage}
pageSizeOptions={["10", "15", "20", "25", "30", "35", "40"]}
/>
</CardBody>
</Card>
</div>
)
}
}
export default withTranslation()(index);
import * as XLSX from 'xlsx';
import DialogForm from './DialogForm';
import DialogMenuRoles from './DialogMenuRoles';
import React, { Component, useMemo } from 'react';
import SweetAlert from 'react-bootstrap-sweetalert';
import axios from 'axios';
import { Button } from 'reactstrap';
import { Card, CardBody, CardHeader, Col, Row, Input } from 'reactstrap';
import { NotificationContainer, NotificationManager } from 'react-notifications';
import { Pagination, Tooltip, Table } from 'antd';
import { ROLE_ADD, ROLE_SEARCH, ROLE_EDIT, ROLE_DELETE, ROLEMENU_ADD, ROLEMENU_SEARCH, ROLEMENU_DELETE_ROLE } from '../../../const/ApiConst.js';
import { withTranslation } from 'react-i18next';
const token = window.localStorage.getItem('token');
const BASE_URL = "http://siopas.co.id/custom-php/api/geohr/";
const config = {
headers:
{
Authorization: `Bearer ${token}`,
"Content-type": `application/json`
}
};
const momentFormat = 'HH:mm';
const LENGTH_DATA = 10
class index extends Component {
constructor(props) {
super(props)
this.state = {
alertDelete: false,
alertNotDelete: false,
currentPage: 1,
dataEdit: null,
dataExport: [],
dataGs: [],
dataIdHo: [],
dataTable: [],
dialogMenuForm: false,
idDelete: 0,
idRoles: 0,
menuRoles: [],
openDialog: false,
page: 0,
rowsPerPage: LENGTH_DATA,
search: "",
tooltipDelete: false,
tooltipEdit: false,
tooltipExport: false,
tooltipImport: false,
tooltipMenu: false,
tooltipTambah: false,
totalPage: 0,
typeDialog: 'Save',
}
this.columns = [
{
title: this.props.t('action'),
dataIndex: '',
key: 'x',
className: 'nowrap',
render: (text, record) => <>
<Tooltip title={this.props.t('menuRoles')}>
<i className="cil-menu" style={{ color: 'green', marginRight: 10, cursor: "pointer" }} onClick={() => this.handleMenuRoles(text.id)}></i>
</Tooltip>
<Tooltip title={this.props.t('delete')}>
<i className="fa fa-trash" style={{ color: 'red', marginRight: 10, cursor: "pointer" }} onClick={() => this.handleDelete(text.id)}></i>
</Tooltip>
<Tooltip title={this.props.t('edit')}>
<i className="fa fa-edit" style={{ color: 'green', cursor: "pointer" }} onClick={() => this.handleEdit(text)}></i>
</Tooltip>
</>,
},
{ title: this.props.t('nameRole'), dataIndex: 'name', key: 'name', className: "nowrap" },
{ title: this.props.t('description'), dataIndex: 'description', key: 'description' },
]
}
async componentDidMount() {
this.getDataRoles();
}
async componentDidUpdate(prevProps, prevState) {
const { search } = this.state
if (search !== prevState.search) this.getDataRoles()
if (prevProps.dataExport !== this.props.dataExport && this.props.dataExport.length > 0) {
this.handleExportExcel();
}
}
handleSearch = e => {
const value = e.target.value
this.setState({ search: value, currentPage: 1 })
};
getDataRoles = async () => {
let start = 0;
if (this.state.currentPage !== 1 && this.state.currentPage > 1) {
start = (this.state.currentPage * this.state.rowsPerPage) - this.state.rowsPerPage
}
const formData = {
"paging": { "start": start, "length": this.state.rowsPerPage },
"columns": [
{ "name": "name", "logic_operator": "ilike", "value": this.state.search, "operator": "AND" }
],
"joins": [],
"orders": { "columns": ["id"], "ascending": false }
}
const result = await axios
.post(ROLE_SEARCH, formData, config)
.then(res => res)
.catch((error) => error.response);
if (result && result.data && result.data.code == 200) {
this.setState({ dataTable: result.data.data, totalPage: result.data.totalRecord });
} else {
NotificationManager.error('Gagal Mengambil Data!!', 'Failed');
}
}
handleOpenDialog = (type) => {
this.setState({ openDialog: true, typeDialog: type })
this.showChildDialog();
}
handleCloseDialog = (type, data) => {
if (type === "save") {
this.saveRole(data);
} else if (type === "edit") {
this.editRole(data);
}
this.setState({ openDialog: false })
}
handleOpenDialogMr = () => {
this.setState({ dialogMenuForm: true })
this.showMenuRolesDialog();
}
handleCloseDialogMr = (type, data) => {
if (type === "save") {
this.saveMenuRoles(data)
}
this.setState({ dialogMenuForm: false })
}
toggleAddDialog = () => {
this.setState({ openDialog: !this.state.openDialog })
}
onConfirmDelete = async () => {
const { idDelete } = this.state
const url = ROLE_DELETE(idDelete)
const result = await axios.delete(url, config)
.then(res => res)
.catch((error) => error.response);
if (result && result.data && result.data.code === 200) {
this.deleteCurrentRoleMenu(idDelete)
this.getDataRoles()
this.setState({ idDelete: 0, alertDelete: false })
NotificationManager.success(`Data role berhasil dihapus`, 'Success!!');
} else {
this.setState({ idDelete: 0, alertDelete: false })
NotificationManager.error(`Data role gagal dihapus`, 'Failed!!');
}
}
saveRole = async (data) => {
const formData = {
name: data.name,
description: data.description
}
const result = await axios.post(ROLE_ADD, formData, config)
.then(res => res)
.catch((error) => error.response);
if (result && result.data && result.data.code === 200) {
this.getDataRoles();
NotificationManager.success(`Data role berhasil ditambah`, 'Success!!');
} else {
NotificationManager.error(`${result.data.message}`, 'Failed!!');
}
}
editRole = async (data) => {
const formData = {
name: data.name,
description: data.description
}
const url = ROLE_EDIT(data.id)
const result = await axios.put(url, formData, config)
.then(res => res)
.catch((error) => error.response);
if (result && result.data && result.data.code === 200) {
this.getDataRoles();
NotificationManager.success(`Data role berhasil diedit`, 'Success!!');
} else {
NotificationManager.error(`Data role gagal di edit`, `Failed!!`);
}
}
handleEdit = (data) => {
this.setState({ dataEdit: data });
this.handleOpenDialog('Edit');
}
handleDelete = (id) => {
id == '1' ? this.setState({ alertNotDelete: true }) :
this.setState({ alertDelete: true, idDelete: id });
}
onShowSizeChange = (current, pageSize) => {
this.setState({ rowsPerPage: pageSize }, () => {
this.getDataRoles();
})
}
onPagination = (current, pageSize) => {
this.setState({ currentPage: current, page: (current - 1) * pageSize }, () => {
this.getDataRoles();
})
}
toggle = (param) => {
if (param === "edit") {
this.setState(prevState => ({ tooltipEdit: !prevState.tooltipEdit }))
} else if (param === "delete") {
this.setState(prevState => ({ tooltipDelete: !prevState.tooltipDelete }))
} else if (param === "menu") {
this.setState(prevState => ({ tooltipMenu: !prevState.tooltipMenu }))
} else if (param === "tambah") {
this.setState(prevState => ({ tooltipTambah: !prevState.tooltipTambah }))
} else if (param === "export") {
this.setState(prevState => ({ tooltipExport: !prevState.tooltipExport }))
}
}
dataNotAvailable = () => {
if (this.state.dataTable.length === 0) {
return (
<tr>
<td align="center" colSpan="3">{this.props.t('noData')}</td>
</tr>
)
}
}
handleMenuRoles = async (id) => {
const formData = {
"paging": { "start": 0, "length": -1 },
"columns": [
{ "name": "role_id", "logic_operator": "=", "value": `${id}`, "operator": "AND" }
],
"joins": [],
"orders": { "columns": ["id"], "ascending": false }
}
const result = await axios
.post(ROLEMENU_SEARCH, formData, config)
.then(res => res)
.catch((error) => error.response);
if (result && result.data && result.data.code == 200) {
this.setState({ menuRoles: result.data.data, idRoles: id }, () => {
this.handleOpenDialogMr();
});
} else {
}
}
saveMenuRoles = async (dataArray) => {
let payloadArray = dataArray || []
if (payloadArray.length > 0) {
await this.deleteCurrentRoleMenu(payloadArray[0].roles_id)
}
let promises = []
let result = []
dataArray.map((val, index) => {
if (val.checked === true) {
const formData = {
menu_id: val.menu_id,
role_id: val.roles_id
}
promises.push(axios.post(ROLEMENU_ADD, formData, config)
.then(res => result.push(res)))
}
})
await Promise.all(promises);
if (result) {
if (result.length > 0) {
if (result[0].data.code === 200) {
this.getDataRoles();
NotificationManager.success('Data roles berhasil ditambahkan!!', 'Success!!');
} else {
NotificationManager.error(`${result[0].data.message}`, 'Failed!!');
}
}
}
}
deleteCurrentRoleMenu = async (id) => {
let urlDel = ROLEMENU_DELETE_ROLE(id)
const result = await axios.delete(urlDel, config)
.then(res => res)
.catch((error) => error.response);
if (result && result.data && result.data.code === 200) {
return true
} else {
return false
}
}
handleExportExcel = async () => {
let start = 0;
let end = "ALL";
const formData = {
"paging": { "start": start, "length": this.state.rowsPerPage },
"columns": [
{ "name": "name", "logic_operator": "ilike", "value": this.state.search, "operator": "AND" }
],
"joins": [],
"orders": { "columns": ["id"], "ascending": false }
}
const result = await axios
.post(ROLE_SEARCH, formData, config)
.then(res => res)
.catch((error) => error.response);
if (result && result.data && result.statusText == "OK") {
const dataRes = result.data.data || [];
const dataExport = [];
dataRes.map((val, index) => {
let row = {
Nama: val.name,
Deskripsi: val.description
}
dataExport.push(row);
})
this.setState({ dataExport: dataExport }, () => {
this.exportExcel();
});
} else {
NotificationManager.error('Failed retreiving data!!', 'Failed');
}
}
exportExcel = () => {
const dataExcel = this.state.dataExport || [];
const fileName = "Data Roles.xlsx";
const ws = XLSX.utils.json_to_sheet(dataExcel);
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, 'Data Roles');
XLSX.writeFile(wb, fileName);
}
render() {
const { t } = this.props;
const { tooltipTambah, tooltipExport, dialogMenuForm, dataTable, openDialog, currentPage, rowsPerPage, totalPage, search, tooltipEdit, tooltipDelete, tooltipMenu } = this.state
let noSeq = 0;
return (
<div>
<NotificationContainer />
<SweetAlert
show={this.state.alertDelete}
warning
showCancel
confirmBtnText="Delete"
confirmBtnBsStyle="danger"
title={this.props.t('deleteConfirm')}
onConfirm={this.onConfirmDelete}
onCancel={() => this.setState({ alertDelete: false, idDelete: 0 })}
focusCancelBtn
>
{this.props.t('deleteMsg')}
</SweetAlert>
<SweetAlert
show={this.state.alertNotDelete}
warning
confirmBtnText="Can't Delete"
confirmBtnBsStyle="danger"
title="Data can't be delete!"
onConfirm={() => this.setState({ alertNotDelete: false })}
>
Data tipe roles tidak dapat di hapus!!
</SweetAlert>
<DialogForm
openDialog={openDialog}
closeDialog={this.handleCloseDialog}
toggleDialog={() => this.toggleAddDialog}
typeDialog={this.state.typeDialog}
dataEdit={this.state.dataEdit}
showDialog={showDialog => this.showChildDialog = showDialog}
dataHs={this.state.dataIdHo}
/>
<DialogMenuRoles
openDialog={dialogMenuForm}
closeDialog={this.handleCloseDialogMr}
idRoles={this.state.idRoles}
showDialog={showDialog => this.showMenuRolesDialog = showDialog}
menuRoles={this.state.menuRoles}
/>
<Card>
<CardHeader style={{ display: "flex", justifyContent: "space-between" }}>
<h4>{this.props.params.name}</h4>
<Row>
<Col>
<Input onChange={this.handleSearch} value={search} type="text" name="search" id="search" placeholder={this.props.t('searchRoles')} />
</Col>
<Col>
<Tooltip title={this.props.t('rolesAdd')}>
<Button id="TooltipTambah" color="success" onClick={() => this.handleOpenDialog('Save')}><i className="fa fa-plus"></i></Button>
</Tooltip>
<Tooltip title={this.props.t('exportExcel')}>
<Button style={{ marginLeft: "5px" }} id="TooltipExport" color="primary" onClick={() => this.handleExportExcel()}><i className="fa fa-print"></i></Button>
</Tooltip>
</Col>
</Row>
</CardHeader>
<CardBody>
<Table
rowKey="id"
size="small"
columns={this.columns}
dataSource={dataTable}
pagination={false}
bordered={false}
/>
<Pagination
style={{ marginTop: "25px" }}
showSizeChanger
onShowSizeChange={this.onShowSizeChange}
onChange={this.onPagination}
defaultCurrent={currentPage}
pageSize={rowsPerPage}
total={totalPage}
pageSizeOptions={["10", "15", "20", "25", "30", "35", "40"]}
/>
</CardBody>
</Card>
</div>
)
}
}
export default withTranslation()(index);

Loading…
Cancel
Save