Browse Source

implement refferal code

pull/1/head
wahyuun 7 months ago
parent
commit
885f408558
  1. 62
      src/views/SimproV2/Settings/DialogForm.js
  2. 86
      src/views/SimproV2/Settings/index.js

62
src/views/SimproV2/Settings/DialogForm.js

@ -26,6 +26,8 @@ const DialogForm = ({
addressProp, addressProp,
emailProp, emailProp,
userNameProp, userNameProp,
refferalCode,
userProfile
}) => { }) => {
const token = window.localStorage.getItem('token'); const token = window.localStorage.getItem('token');
const [typeDialog, setTypeDialog] = useState(typeDialogProp) const [typeDialog, setTypeDialog] = useState(typeDialogProp)
@ -38,15 +40,15 @@ const DialogForm = ({
const [birthdayDate, setBirthdaydate] = useState(birthdayDateProp) const [birthdayDate, setBirthdaydate] = useState(birthdayDateProp)
const [idNumber, setIdnumber] = useState(idNumberProp) const [idNumber, setIdnumber] = useState(idNumberProp)
const [email, setEmail] = useState(emailProp) const [email, setEmail] = useState(emailProp)
const [password, setPassword] = useState('') const [refferal, setRefferalCode] = useState('')
const [oldPassword, setOldPassword] = useState('') const [oldPassword, setOldPassword] = useState('')
const [newPassword, setNewPassword] = useState('') const [newPassword, setNewPassword] = useState('')
const [newPasswordConfirm, setNewPasswordConfirm] = useState('') const [newPasswordConfirm, setNewPasswordConfirm] = useState('')
const [activeTab, setActiveTab] = useState('tab1') const [activeTab, setActiveTab] = useState('tab1')
console.log('typeDialogProp',typeDialogProp)
const handleSave = () => { const handleSave = () => {
let data = ''; let data = '';
if (typeDialog === "Personal") { if (typeDialog === "Personal" && typeDialogProp !== "Refferal") {
data = { data = {
name: name, name: name,
phone_number: noHp, phone_number: noHp,
@ -59,13 +61,21 @@ const DialogForm = ({
data.birth_date = birthdayDate; data.birth_date = birthdayDate;
} }
closeDialog('profile', data) closeDialog('profile', data)
} else if (typeDialog === "Account") { } else if (typeDialog === "Account" && typeDialogProp !== "Refferal") {
data = { data = {
username: userName, username: userName,
email: email, email: email,
password: newPassword, password: newPassword,
} }
closeDialog('profile', data) closeDialog('profile', data)
} else {
data = {
code: refferal,
user_id: userProfile.id,
username: userProfile.username,
ktp_number: userProfile.ktp_number
}
closeDialog('refferal_code', data)
} }
} }
@ -85,6 +95,19 @@ const DialogForm = ({
) )
} }
function generateRandomString(length) {
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
let result = '';
for (let i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * characters.length));
}
return result;
}
function generateReferralCode() {
const newReferralCode = generateRandomString(6);
setRefferalCode(newReferralCode);
}
const renderForm = () => { const renderForm = () => {
return ( return (
@ -197,12 +220,13 @@ const DialogForm = ({
} }
return ( return (
<>
<Modal size="lg" isOpen={openDialog} toggle={toggleDialog}> <Modal size="lg" isOpen={openDialog} toggle={toggleDialog}>
<ModalHeader className="capitalize" toggle={closeDialog}> <ModalHeader className="capitalize" toggle={closeDialog}>
Update {typeDialog == "Personal" ? `Personal` : "Account"} Data Update {typeDialog == "Personal" ? `Personal` : "Account"} Data
</ModalHeader> </ModalHeader>
<ModalBody> <ModalBody>
{typeDialogProp !== 'Refferal' ? (
<>
<Nav tabs> <Nav tabs>
<NavItem> <NavItem>
<NavLink <NavLink
@ -249,13 +273,37 @@ const DialogForm = ({
{renderFormSetting()} {renderFormSetting()}
</TabPane> </TabPane>
</TabContent> </TabContent>
</>
):(
<Form>
<Row>
<Col md={12}>
<span style={{ color: "red" }}>*</span> Wajib diisi.
</Col>
</Row>
<Row>
<Col md={12}>
<FormGroup>
<Label className="capitalize">Refferal Code</Label>
<Row>
<Col md={8}>
<Input maxLength={16} type="text" value={refferal || refferalCode} onChange={(e) => setRefferalCode(e.target.value)} placeholder={'Input refferal code'} />
</Col>
<Col md={4}>
<Button color="primary" onClick={generateReferralCode}>Generate</Button>
</Col>
</Row>
</FormGroup>
</Col>
</Row>
</Form >
)}
</ModalBody> </ModalBody>
<ModalFooter> <ModalFooter>
<Button color="primary" onClick={() => handleSave()}>{typeDialog == "Profile" ? `Profile` : "Save"}</Button> {' '} <Button color="primary" onClick={() => handleSave()}>{typeDialogProp !== 'Refferal' ? typeDialog == "Profile" ? `Profile` : "Save" : "Generate Code"}</Button> {' '}
<Button className="capitalize" color="secondary" onClick={() => handleCancel()}>Batal</Button> <Button className="capitalize" color="secondary" onClick={() => handleCancel()}>Batal</Button>
</ModalFooter> </ModalFooter>
</Modal> </Modal>
</>
) )

86
src/views/SimproV2/Settings/index.js

@ -5,14 +5,11 @@ import axios from "../../../const/interceptorApi"
import { Card, CardBody, CardHeader, Col, Row, Input, Table, Button } from 'reactstrap'; import { Card, CardBody, CardHeader, Col, Row, Input, Table, Button } from 'reactstrap';
import { NotificationContainer, NotificationManager } from 'react-notifications'; import { NotificationContainer, NotificationManager } from 'react-notifications';
import { Pagination, Tooltip } from 'antd'; import { Pagination, Tooltip } from 'antd';
import { USER_EDIT, SATUAN_ADD, SATUAN_EDIT, SATUAN_DELETE, SATUAN_SEARCH } from '../../../const/ApiConst'; import { USER_EDIT, USER_GET_ID, REFFERAL_GET_ID, REFFERAL_ADD, REFFERAL_EDIT } from '../../../const/ApiConst';
import profile from '../../../assets/img/profile.png' import profile from '../../../assets/img/profile.png'
import DialogForm from './DialogForm' import DialogForm from './DialogForm'
import { ROLE_SEARCH, BASE_OSPRO } from '../../../const/ApiConst' import { ROLE_SEARCH, BASE_OSPRO } from '../../../const/ApiConst'
const Setting = ({ params }) => { const Setting = ({ params }) => {
const token = localStorage.getItem("token") const token = localStorage.getItem("token")
const config = { const config = {
@ -21,17 +18,13 @@ const Setting = ({ params }) => {
"Authorization": `Bearer ${token}` "Authorization": `Bearer ${token}`
} }
} }
const pageName = params.name; const pageName = params.name;
const [openDialog, setOpenDialog] = useState(false) const [openDialog, setOpenDialog] = useState(false)
const [typeDialog, setTypeDialog] = useState('Personal') const [typeDialog, setTypeDialog] = useState('Personal')
const [id, setId] = useState(0) const [id, setId] = useState(0)
const [roleList, setRoleList] = useState([]) const [roleList, setRoleList] = useState([])
const [userProfile, setUserprofile] = useState(null) const [userProfile, setUserprofile] = useState(null)
const [refferal, setReferralCode] = useState(null)
const [userName, setUserName] = useState("") const [userName, setUserName] = useState("")
const [name, setName] = useState('') const [name, setName] = useState('')
const [noHp, setNohp] = useState("") const [noHp, setNohp] = useState("")
@ -44,7 +37,7 @@ const Setting = ({ params }) => {
const [role, setRole] = useState("") const [role, setRole] = useState("")
const [email, setEmail] = useState("") const [email, setEmail] = useState("")
const [employeeType, setEmployeeType] = useState("") const [employeeType, setEmployeeType] = useState("")
const [isCopied, setIsCopied] = useState(false);
useEffect(() => { useEffect(() => {
getDataProfileUser(); getDataProfileUser();
@ -68,7 +61,7 @@ const Setting = ({ params }) => {
setEmployeeType(userProfile?.employee_type); setEmployeeType(userProfile?.employee_type);
} }
}, [userProfile]) }, [userProfile, typeDialog])
const handleOpenDialog = (type) => { const handleOpenDialog = (type) => {
setOpenDialog(true) setOpenDialog(true)
@ -78,12 +71,13 @@ const Setting = ({ params }) => {
const handleCloseDialog = (type, data) => { const handleCloseDialog = (type, data) => {
if (type === "profile") { if (type === "profile") {
saveProfile(data); saveProfile(data);
} else if(type === "refferal_code") {
updateRefferal(data);
} }
setOpenDialog(false) setOpenDialog(false)
} }
const saveProfile = async (data) => { const saveProfile = async (data) => {
let urlEdit = USER_EDIT(id) let urlEdit = USER_EDIT(id)
const formData = data const formData = data
@ -99,6 +93,20 @@ const Setting = ({ params }) => {
} }
} }
const updateRefferal = async (data) => {
let urlEdit = REFFERAL_EDIT(id)
const formData = data
const result = await axios.put(urlEdit, formData, config)
.then(res => res)
.catch((error) => error.response);
if (result && result.data && result.data.code === 200) {
getDataRefferal(data.user_id, data.username, data.ktp_number);
NotificationManager.success(`Code refferal berhasil diedit`, 'Success!!');
} else {
NotificationManager.error(`Code refferal gagal di edit`, `Failed!!`);
}
}
const toggleAddDialog = () => { const toggleAddDialog = () => {
setOpenDialog(!openDialog) setOpenDialog(!openDialog)
} }
@ -121,10 +129,7 @@ const Setting = ({ params }) => {
const getDataProfileUser = async () => { const getDataProfileUser = async () => {
const id = localStorage.getItem("user_id") const id = localStorage.getItem("user_id")
const url = USER_GET_ID(id);
const url = `${BASE_OSPRO}/api/human-resource/edit/${id}`
const result = await axios const result = await axios
.get(url, config) .get(url, config)
.then((res) => res) .then((res) => res)
@ -132,11 +137,49 @@ const Setting = ({ params }) => {
if (result && result.data && result.data.code == 200) { if (result && result.data && result.data.code == 200) {
let dataRes = result.data.data; let dataRes = result.data.data;
setUserprofile(dataRes); setUserprofile(dataRes);
await getDataRefferal(id, dataRes.username, dataRes.ktp_number);
} else { } else {
NotificationManager.error("Gagal Mengambil Data!!", "Failed"); NotificationManager.error("Gagal Mengambil Data!!", "Failed");
} }
}; };
const getDataRefferal = async (user_id, username, ktp_number) => {
const url = REFFERAL_GET_ID(user_id);
const result = await axios
.get(url, config)
.then((res) => res)
.catch((error) => error.response);
if (result && result.data && result.data.code == 200) {
let dataRes = result.data.data;
setReferralCode(dataRes);
} else {
saveRefferalCode(user_id, username, ktp_number);
};
}
const saveRefferalCode = async (user_id, username, ktp_number) => {
const formData = {
'id': parseInt(user_id),
'code': username + ktp_number.substring(0, 4),
'amount': 0
}
const result = await axios
.post(REFFERAL_ADD, formData, config)
.then((res) => res)
.catch((error) => error.response);
if (result && result.data && result.data.code == 200) {
await getDataRefferal(user_id, username, ktp_number);
}
}
function copyToClipboard(text) {
navigator.clipboard.writeText(text).then(() => {
setIsCopied(true);
setTimeout(() => setIsCopied(false), 2000);
}, (err) => {
console.error('Gagal menyalin teks ke clipboard: ', err);
});
}
return ( return (
@ -158,6 +201,8 @@ const Setting = ({ params }) => {
addressProp={address} addressProp={address}
emailProp={email} emailProp={email}
userNameProp={userName} userNameProp={userName}
refferalCode={refferal?.code}
userProfile={userProfile}
/> />
<Card> <Card>
@ -233,6 +278,15 @@ const Setting = ({ params }) => {
<td><b>Tanggal Lahir &nbsp; </b></td> <td><b>Tanggal Lahir &nbsp; </b></td>
<td>: &nbsp; {birthdayDate}</td> <td>: &nbsp; {birthdayDate}</td>
</tr> </tr>
<tr>
<td><b>Referral Code &nbsp; </b></td>
<td>: &nbsp; {refferal?.code} <small style={{ color:'blue', cursor: 'pointer' }} onClick={() => copyToClipboard(refferal?.code)}>{isCopied ? 'Copied' : 'Copy'}</small></td>
<td>
<Tooltip title='Custom Refferal Code'>
<Button color="success" onClick={() => handleOpenDialog('Refferal')}>Custom Refferal Code</Button>
</Tooltip>
</td>
</tr>
</tbody> </tbody>
<br /> <br />
</Col> </Col>

Loading…
Cancel
Save