Browse Source

diskon and referral code page

pull/1/head
farhantock 10 months ago
parent
commit
01a9d444aa
  1. 190
      src/views/SimproV2/ReferralCode/DialogForm.js
  2. 372
      src/views/SimproV2/ReferralCode/index.js

190
src/views/SimproV2/ReferralCode/DialogForm.js

@ -0,0 +1,190 @@
import React, { useEffect, useState } from 'react'
import {
Modal, ModalHeader, ModalBody, ModalFooter,
Button, Form, FormGroup, Label, Input, Col, Row
} from 'reactstrap';
import { Select, DatePicker } from 'antd';
import 'antd/dist/antd.css';
import { useTranslation } from 'react-i18next';
import "rc-color-picker/assets/index.css";
import moment from 'moment';
import { formatNumber } from "../../../const/CustomFunc";
const { Option } = Select
const DialogForm = ({ openDialog, closeDialog, toggleDialog, typeDialog, dataEdit }) => {
const [id, setId] = useState(0)
const [code, setCode] = useState('')
const [amount, setAmount] = useState(0)
const [description, setDescription] = useState('')
const [exp, setExp] = useState('')
const [type, setType] = useState('')
const [allocation, setAllocation] = useState(0)
const { t } = useTranslation()
useEffect(() => {
console.log('dataEdit', dataEdit);
if (typeDialog === "Edit") {
setId(dataEdit.id)
setCode(dataEdit.code)
setAmount(dataEdit.amount)
setDescription(dataEdit.description)
setExp(dataEdit.exp)
setType(dataEdit.type)
} else {
handleClear()
}
}, [dataEdit, openDialog])
const validation = () => {
if (!code || code === "") {
alert("Code cannot be empty!");
return true;
}
}
const handleSave = () => {
let data = '';
const err = validation();
if (!err) {
if (typeDialog === "Save") {
data = {
code,
amount,
description,
exp,
type,
allocation
}
console.log('data', data);
closeDialog('save', data);
} else {
data = {
id,
code,
amount,
description,
exp,
type,
allocation
}
console.log('data', data);
closeDialog('edit', data);
}
handleClear()
}
}
const handleCancel = () => {
closeDialog('cancel', 'none')
handleClear()
}
const handleClear = () => {
setId(0)
setCode('')
setAmount('')
setDescription('')
setExp('')
}
const renderForm = () => {
return (
<Form>
<Row>
<Col md={12}>
<span style={{ color: "red" }}>*</span> Wajib diisi.
</Col>
</Row>
<Row>
<Col md={6}>
<FormGroup>
<Label className="capitalize">{t('code')} {t('discount')}<span style={{ color: "red" }}>*</span></Label>
<Input
type="text"
value={code}
onChange={(e) => setCode(e.target.value)}
placeholder={t('inputCode')}
/>
</FormGroup>
</Col>
<Col md={6}>
<FormGroup>
<Label className="capitalize">{t('amount')}<span style={{ color: "red" }}>*</span></Label>
<Input
type="text"
value={amount}
onChange={(e) => setAmount(e.target.value)}
placeholder={t('inputAmount')}
/>
</FormGroup>
</Col>
</Row>
<Row>
<Col md={6}>
<FormGroup>
<Label className="capitalize" style={{ fontWeight: "bold" }}>
{t('exp')}<span style={{ color: "red" }}>*</span>
</Label>
<DatePicker
format={"DD-MM-YYYY HH:mm"}
style={{ width: "100%" }}
value={exp ? moment(exp) : exp}
onChange={(date, dateString) => setExp(date)}
showTime={{ defaultValue: moment('00:00:00', 'HH:mm:ss') }}
/>
</FormGroup>
</Col>
<Col md={6}>
<FormGroup>
<Label className="capitalize">{t('allocation')}<span style={{ color: "red" }}>*</span></Label>
<Input
type="number"
value={allocation}
onChange={(e) => setAllocation(e.target.value)}
placeholder={t('input')}
/>
</FormGroup>
</Col>
<Col md={6}>
<FormGroup>
<Label className="capitalize">{t('type')}<span style={{ color: "red" }}>*</span></Label>
<Input
type="text"
value={type}
onChange={(e) => setType(e.target.value)}
placeholder={t('inputType')}
/>
</FormGroup>
</Col>
</Row>
<Row>
<Col md={12}>
<FormGroup>
<Label className="capitalize">{t('description')}</Label>
<Input row="4" type="textarea" value={description} onChange={(e) => setDescription(e.target.value)} placeholder={t('inputDescription')} />
</FormGroup>
</Col>
</Row>
</Form>
)
}
return (
<>
<Modal size="lg" isOpen={openDialog} toggle={toggleDialog}>
<ModalHeader className="capitalize" toggle={closeDialog}>{typeDialog == "Save" ? `Add` : "Edit"} {t('Demo')}</ModalHeader>
<ModalBody>
{renderForm()}
</ModalBody>
<ModalFooter>
<Button color="primary" onClick={() => handleSave()}>{typeDialog}</Button>{' '}
<Button className="capitalize" color="secondary" onClick={() => handleCancel()}>{t('cancel')}</Button>
</ModalFooter>
</Modal>
</>
)
}
export default DialogForm;

372
src/views/SimproV2/ReferralCode/index.js

@ -0,0 +1,372 @@
import * as XLSX from 'xlsx';
import DialogForm from './DialogForm';
import React, { useState, useEffect } from 'react';
import SweetAlert from 'react-bootstrap-sweetalert';
import axios from "../../../const/interceptorApi"
import { Card, CardBody, CardHeader, Col, Row, Input, Table } from 'reactstrap';
import { REFERRAL_CODE_EDIT, REFERRAL_CODE_SEARCH, REFERRAL_CODE_ADD, REFERRAL_CODE_DELETE } from '../../../const/ApiConst';
import { NotificationContainer, NotificationManager } from 'react-notifications';
import { Spin, Button, Tooltip } from 'antd';
import { useTranslation } from 'react-i18next';
import moment from 'moment';
import toRupiah from '@develoka/angka-rupiah-js';
const ProjectType = ({ params, ...props }) => {
let role_id = 0, user_id = 0, isLogin = false, token = '', company_id = 0, all_project = null, role_name = '', hierarchy = [], user_name = '';
if (props && props.role_id && props.user_id) {
role_id = props.role_id;
user_id = props.user_id;
token = props.token;
isLogin = props.isLogin;
company_id = props.company_id;
all_project = props.all_project;
role_name = props.role_name;
isLogin = props.isLogin;
hierarchy = props.hierarchy;
user_name = props.user_name;
}
const HEADER = {
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${token}`
}
}
const pageName = params.name;
const [alertDelete, setAlertDelete] = useState(false)
const [allDataMenu, setAllDataMenu] = useState([])
const [clickOpenModal, setClickOpenModal] = useState(false)
const [currentPage, setCurrentPage] = useState(1)
const [dataEdit, setDataEdit] = useState([])
const [dataExport, setDataExport] = useState([])
const [dataTable, setDatatable] = useState([])
const [idDelete, setIdDelete] = useState(0)
const [openDialog, setOpenDialog] = useState(false)
const [rowsPerPage, setRowsPerPage] = useState(10)
const [search, setSearch] = useState("")
const [totalPage, setTotalPage] = useState(0)
const [typeDialog, setTypeDialog] = useState('Save')
const [dataDemo, setDataDemo] = useState([])
const [listCompany, setListCompany] = useState([])
const [loading, setLoading] = useState(true);
const { t } = useTranslation()
const column = [
{ name: t('code') },
{ name: t('type') },
{ name: t('amount') },
{ name: t('exp') },
{ name: t('allocation') },
{ name: t('description') },
].filter(column => column && column.name);
useEffect(() => {
getReferralCode();
}, [currentPage, rowsPerPage, search])
useEffect(() => {
const cekData = dataExport || []
if (cekData.length > 0) {
exportExcel()
}
}, [dataExport])
const getReferralCode = async () => {
let start = 0;
if (currentPage !== 1 && currentPage > 1) {
start = currentPage * rowsPerPage - rowsPerPage;
}
const payload = {
group_column: {
"operator": "AND",
"group_operator": "OR",
"where": [
{
"name": "name",
"logic_operator": "~*",
"value": search,
}
]
},
columns: [],
"orders": {
"ascending": true,
"columns": [
'id'
]
},
"paging": {
"length": rowsPerPage,
"start": start
},
'joins': []
}
const result = await axios
.post(REFERRAL_CODE_SEARCH, payload, HEADER)
.then(res => res)
.catch((error) => error.response);
if (result && result.data && result.data.code == 200) {
setDatatable(result.data.data);
setTotalPage(result.data.totalRecord);
setLoading(false)
} else {
NotificationManager.error('Gagal Mengambil Data!!', 'Failed');
setLoading(false)
}
}
const handleExportExcel = async () => {
let start = 0;
if (currentPage !== 1 && currentPage > 1) {
start = (currentPage * rowsPerPage) - rowsPerPage
}
const payload = {
group_column: {
"operator": "AND",
"group_operator": "OR",
"where": [
{
"name": "name",
"logic_operator": "~*",
"value": search,
}
]
},
"columns": [],
"orders": {
"ascending": true,
"columns": [
'id'
]
},
"paging": {
"length": rowsPerPage,
"start": start
},
'joins': []
}
const result = await axios
.post(REFERRAL_CODE_SEARCH, payload, HEADER)
.then(res => res)
.catch((error) => error.response);
if (result && result.data && result.data.code == 200) {
let resData = result.data.data;
const excelData = [];
resData.map((val, index) => {
let dataRow = {};
dataRow["Kode"] = val.code;
dataRow["Jumlah"] = val.amount;
dataRow["Kuota"] = val.allocation;
dataRow["Kadaluarsa"] = val.exp;
dataRow["Deskripsi"] = val.deskription;
excelData.push(dataRow)
})
await setDataExport(excelData)
} else {
NotificationManager.error('Gagal Export Data!!', 'Failed');
}
}
const exportExcel = () => {
const dataExcel = dataExport || [];
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}`);
XLSX.writeFile(wb, fileName);
setDataExport([])
}
const handleSearch = e => {
const value = e.target.value
setSearch(value);
setCurrentPage(1)
};
const handleOpenDialog = (type) => {
setOpenDialog(true)
setTypeDialog(type)
}
const handleEdit = (data) => {
setDataEdit(data)
handleOpenDialog('Edit');
}
const handleDelete = async (id) => {
await setAlertDelete(true)
await setIdDelete(id)
}
const handleCloseDialog = (type, data) => {
if (type === "save") {
saveReferralCode(data);
} else if (type === "edit") {
editReferralCode(data);
}
setDataEdit([])
setOpenDialog(false)
}
const saveReferralCode = async (data) => {
const formData = data
const result = await axios.post(REFERRAL_CODE_ADD, formData, HEADER)
.then(res => res)
.catch((error) => error.response);
if (result && result.data && result.data.code === 200) {
getReferralCode()
NotificationManager.success(`Data berhasil ditambahkan`, 'Success!!');
} else {
NotificationManager.error(`Data gagal ditambahkan`, 'Failed!!');
}
}
const editReferralCode = async (data) => {
let urlEdit = REFERRAL_CODE_EDIT(data.id)
const formData = data
const result = await axios.put(urlEdit, formData, HEADER)
.then(res => res)
.catch((error) => error.response);
if (result && result.data && result.data.code === 200) {
getReferralCode();
NotificationManager.success(`Data berhasil diubah`, 'Success!!');
} else {
NotificationManager.error(`Data gagal diubah`, `Failed!!`);
}
}
const toggleAddDialog = () => {
setOpenDialog(!openDialog)
}
const onConfirmDelete = async () => {
let url = REFERRAL_CODE_DELETE(idDelete);
const result = await axios.delete(url, HEADER)
.then(res => res)
.catch((error) => error.response);
if (result && result.data && result.data.code === 200) {
getReferralCode()
setIdDelete(0)
setAlertDelete(false)
NotificationManager.success(`Data berhasil dihapus!`, 'Success!!');
} else {
setIdDelete(0)
setAlertDelete(false)
NotificationManager.error(`Data gagal dihapus!}`, 'Failed!!');
}
}
const cancelDelete = () => {
setAlertDelete(false)
setIdDelete(0)
}
const onShowSizeChange = (current, pageSize) => {
setRowsPerPage(pageSize)
}
const onPagination = (current, pageSize) => {
setCurrentPage(current)
}
const dataNotAvailable = () => {
if (dataTable.length === 0) {
return (
<tr>
<td align="center" colSpan="7">{t('noData')}</td>
</tr>
)
}
}
return (
<div>
<NotificationContainer />
<SweetAlert
show={alertDelete}
warning
showCancel
confirmBtnText="Delete"
confirmBtnBsStyle="danger"
title={t('deleteConfirm')}
onConfirm={onConfirmDelete}
onCancel={cancelDelete}
focusCancelBtn
>
{t('deleteMsg')}
</SweetAlert>
<DialogForm
openDialog={openDialog}
closeDialog={handleCloseDialog}
toggleDialog={() => toggleAddDialog}
typeDialog={typeDialog}
dataEdit={dataEdit}
clickOpenModal={clickOpenModal}
dataParent={allDataMenu}
/>
<Card>
<CardHeader style={{ display: "flex", justifyContent: "space-between" }}>
<h4 className="capitalize">{pageName}</h4>
<Row>
<Col>
<Input onChange={handleSearch} value={search} type="text" name="search" id="search" placeholder={t('search')} />
</Col>
<Col>
<Tooltip title={t('demoAdd')}>
<Button style={{ background: "#4caf50", color: "#fff" }} onClick={() => handleOpenDialog('Save')}><i className="fa fa-plus"></i></Button>
</Tooltip>
<Tooltip title={t('exportExcel')}>
<Button style={{ marginLeft: "5px" }} onClick={() => handleExportExcel()}><i className="fa fa-print"></i></Button>
</Tooltip>
</Col>
</Row>
</CardHeader>
<CardBody>
<Spin tip="Loading..." spinning={loading}>
<Table responsive striped hover>
<thead>
<tr>
<th>Aksi</th>
{column.map((i, index) => {
return (
<th key={index} scope="row">{i.name}</th>
)
})}
</tr>
</thead>
<tbody>
{dataNotAvailable()}
{dataTable.map((n, index) => {
return (
<tr key={n.id}>
<td className='nowrap'>
<Tooltip title={t('delete')}>
<i id="TooltipDelete" className="fa fa-trash" style={{ color: 'red', marginRight: 10, cursor: "pointer" }} onClick={() => handleDelete(n.id)}></i>
</Tooltip>
<Tooltip title={t('edit')}>
<i id="TooltipEdit" className="fa fa-edit" style={{ color: 'green', cursor: "pointer" }} onClick={() => handleEdit(n)}></i>
</Tooltip>
</td>
<td>{n.code}</td>
<td>{n.type}</td>
<td>{toRupiah(n.amount)}</td>
<td>{n?.exp ? moment(n.exp).format('DD-MM-YYYY HH:mm') : "-"}</td>
<td>{n.allocation ? n.allocation : "-"}</td>
<td>{n.description ? n.description : "-"}</td>
</tr>
)
})}
</tbody>
</Table>
</Spin>
</CardBody>
</Card>
</div>
)
}
export default ProjectType;
Loading…
Cancel
Save