Android_Retail/src/Pages/Offer/CouponOffer/CouponWiseOfferlist.jsx

788 lines
25 KiB
JavaScript

import React, { useCallback, useEffect, useState } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { useDispatch } from 'react-redux';
import { MdOutlineTextsms } from "react-icons/md";
import { AiOutlineMail } from "react-icons/ai";
import {
changeBreadCrumb,
getEmpAccess,
} from '../../../Features/AppPage/CenterPage';
import { Messages } from '../../../Components/Notifications/Messages';
import FormHeader from '../../PageComponents/FormHeader.jsx';
import { Search } from '../../../Components/Forms/Search';
import Buttons from '../../../Components/Forms/Buttons';
import { Space, Table, Checkbox, Spin } from 'antd';
import {
EditFilled,
DeleteFilled,
PlusOutlined,
ReloadOutlined,
} from '@ant-design/icons';
import { Tables } from '../../../Components/Tables/Table';
import { getSession, dateFormatChange } from '../../../Services/Others';
import { DefaultModal } from '../../../Components/Modal/DefaultModal';
import {
getCouponsdata,
deleteCouponsdata,
getGenCoupondata,
postGenCoupondata,
} from '../../../Features/Offer/CouponWiseOffer/CouponWiseoffer.js';
import { BiSolidCoupon } from 'react-icons/bi';
import { useAuth } from '../../../AuthContext.jsx';
import { postCustomerCouponMail, postSMSCoupon } from '../../../Features/Payment/PaymentDetails/PaymentDetails.js';
import { getPreferenceData } from '../../../Features/BookingScreen/BookingData/BookingData.js';
const CheckboxGroup = Checkbox.Group;
const subDirectory = import.meta.env.ENV_BASE_URL;
const items = [
{
name: 'Home',
link: `${subDirectory}app-page/home`,
},
{
name: 'CouponWiseOffer',
link: `${subDirectory}setting/coupon`,
},
];
const plainOptions = [
{
label: (<div style={{ display: "flex", alignItems: "center", marginTop: "0.2rem" }}><AiOutlineMail size={18} style={{ marginRight: 5 }} />Mail</div>),
value: 'Mail',
},
{
label: (<div style={{ display: "flex", alignItems: "center", marginTop: "0.2rem" }}><MdOutlineTextsms size={18} style={{ marginRight: 5 }} />SMS</div>),
value: 'SMS',
},
// {
// label: (<><ShoppingOutlined style={{ marginRight: 8 }} />WatsApp</>),
// value: 'WatsApp',
// },
];
const CouponWiseOfferlist = () => {
const { SadminuserAccess } = useAuth();
let SAAccessCommonMaster = SadminuserAccess?.find(
(e) => e?.MenuName === 'Coupon Wise Offer'
);
console.log(SAAccessCommonMaster, 'SAAccessCommonMaster', SadminuserAccess);
const navigateTo = useNavigate();
const dispatch = useDispatch();
const location = useLocation();
const CompId = getSession('CompId');
const BranchId = getSession('BranchId');
const AppId = getSession('AppId');
const UserId = getSession('UserId');
const UserType = getSession('UserType');
const [tabledata, setTabledata] = useState([]);
const [messageType, setMessageType] = useState(null);
const [messageData, setMessageData] = useState(null);
const [searchedText, setSearchedText] = useState('');
const [sortedInfo, setSortedInfo] = useState({});
const [page, setpage] = useState(1);
const [Open, setOpen] = useState(false);
const [Coupondata, setCoupondata] = useState();
const [selectedRowKeys, setSelectedRowKeys] = useState();
const [selectedRowData, setSelectedRowData] = useState();
const [data, setdata] = useState([]);
const [selectionType, setSelectionType] = useState('checkbox');
const [Uniqueid, setUniqueid] = useState();
const [empData, setEmpData] = useState();
const [addnewAccess, setaddnewAccess] = useState(true);
const [allowDecimal, setAllowDecimal] = useState(false);
const [checkedList, setCheckedList] = useState([]);
const [isLoading, setIsLoading] = useState(false);
const checkAll = plainOptions.length === checkedList.length;
const indeterminate = checkedList.length > 0 && checkedList.length < plainOptions.length;
const getPreference = async () => {
const data = { AppId: AppId, CompId: CompId, BranchId: BranchId,UserId:UserId };
const { data: res } = await dispatch(getPreferenceData(data)).unwrap()
const decimalSetting = res?.data?.[0]?.SettingDtlDetails?.find((setting) => setting?.SettingIdName?.toLowerCase() === "decimal" && setting?.SettingValue === 'Y');
if (decimalSetting) {
setAllowDecimal(true)
}
}
const actionsFormatter = async (row, rowIndex) => {
if (row.ActiveStatus !== 'D') {
navigateTo(
`${subDirectory}setting/coupon/update`,
{ state: { editstate: row } },
{ key: rowIndex }
);
}
};
const statusFormatter = async (row) => {
let deleteData = {
UniqueId: row.UniqueId,
ActiveStatus: row.ActiveStatus == 'A' ? 'D' : 'A',
UpdatedBy: getSession('UserId'),
};
let response = await dispatch(deleteCouponsdata(deleteData)).unwrap();
if (response?.data?.statusCode == 1) {
Tabledatas();
setMessageType('success');
setMessageData(
row.ActiveStatus == 'A'
? 'In-Activated Successfully'
: 'Activated Successfully'
);
}
};
function safeRound(amountStr) {
if (amountStr == null) return allowDecimal ? '0.00' : '0';
const cleaned = String(amountStr).replace(/[^0-9.-]+/g, '');
const num = Number(cleaned);
if (isNaN(num)) return allowDecimal ? '0.00' : '0';
return allowDecimal ? num.toFixed(2) : Math.round(num).toString();
}
const columns = [
{
title: 'Sl.No',
key: 'sno',
align: 'center',
width: '80px',
render: (text, object, index) => (
<a style={{ color: 'black' }}>{(page - 1) * 10 + index + 1}</a>
),
},
{
title: 'Offer Name',
dataIndex: 'OfferName',
key: 'OfferName',
width: '150px',
render: (text) => <a style={{ color: 'black' }}>{text}</a>,
filteredValue: [searchedText],
onFilter: (value, record) => {
return (
String(record.OfferName)
?.toLowerCase()
?.includes(value?.toLowerCase()) ||
String(record.MinQty)?.toLowerCase()?.includes(value?.toLowerCase()) ||
String(record.MinPurchase)
?.toLowerCase()
?.includes(value?.toLowerCase()) ||
String(record.Point)?.toLowerCase()?.includes(value?.toLowerCase()) ||
String(record.RewardTypeName)
?.toLowerCase()
?.includes(value?.toLowerCase())
);
},
sorter: (a, b) => a?.OfferName?.length - b?.OfferName?.length,
sortOrder: sortedInfo.columnKey === 'OfferName' ? sortedInfo.order : null,
ellipsis: true,
},
{
title: 'Min Qty',
dataIndex: 'MinQty',
key: 'MinQty',
// width: "100px",
align: 'right',
render: (text) => <a style={{ color: 'black' }}>{text}</a>,
},
{
title: 'Min Purchase',
dataIndex: 'MinPurchase',
key: 'MinPurchase',
width: '100px',
align: 'right',
render: (text) => <a style={{ color: 'black' }}>{safeRound(text)}</a>,
},
{
title: 'Reward Type',
dataIndex: 'RewardTypeName',
key: 'RewardTypeName',
width: '100px',
align: 'center',
render: (text) => <a style={{ color: 'black' }}>{text}</a>,
},
{
title: 'Reward Value',
dataIndex: 'Discount',
key: 'Discount',
// width: "100px",
align: 'right',
render: (_, record, index) => (
<a style={{ color: 'black' }}>
{record?.RewardTypeName === 'Discount' ? (
record?.OfferType == 'F' ? (
'₹' + safeRound(record?.OfferAmt)
) : (
record?.OfferAmt + '%'
)
) : (
<a style={{ color: 'black' }}>
{record?.RewardTypeDetails.length + ' ' + "Product's"}
</a>
)}
</a>
),
},
{
title: 'Generate Coupon',
key: 'Print',
dataIndex: 'Print',
// width: "150px",
align: 'center',
render: (_, record, index) =>
tabledata.length >= 1 ? (
<Space size="middle">
{/* {record.QRCode != null ? ( */}
<a>
<BiSolidCoupon
style={{ fontSize: '20px' }}
onClick={() =>
(UserType === 'Super Admin' ||
(UserType === 'Super Admin User' &&
SAAccessCommonMaster?.UpdateAccess === 'Y') ||
(UserType === 'Employee' &&
(empData?.UpdateAccess === 'Y' ||
empData?.AddAccess === 'Y')) ||
UserType === 'Admin') &&
CouponGenereate(record, index)
}
/>
</a>
{/* ) : ( */}
{/* "-" */}
{/* )} */}
</Space>
) : null,
},
{
title: 'From',
dataIndex: 'OfferFrom',
key: 'OfferFrom',
width: '120px',
render: (text) => (
<a style={{ color: 'black' }}>{dateFormatChange(text)}</a>
),
},
{
title: 'To',
dataIndex: 'OfferTo',
key: 'OfferTo',
width: '120px',
render: (text) => (
<a style={{ color: 'black' }}>{dateFormatChange(text)}</a>
),
},
{
title: 'Action',
key: 'Action',
align: 'center',
// width: "150px",
dataIndex: 'Action',
render: (_, record, index) =>
tabledata.length >= 1 ? (
<Space size="middle">
{record.ActiveStatus === 'A' ? (
<a>
<EditFilled
style={{ color: '#1292EE' }}
onClick={() =>
UserType === 'Super Admin' ||
(UserType === 'Super Admin User' &&
SAAccessCommonMaster?.UpdateAccess === 'Y') ||
(UserType === 'Employee' &&
empData?.UpdateAccess === 'Y') ||
UserType === 'Admin'
? actionsFormatter(record, index)
: null
}
/>
</a>
) : (
''
)}
<a>
{record.ActiveStatus === 'A' ? (
<DeleteFilled
style={{
color: '#FF4D4F',
}}
onClick={() =>
UserType === 'Super Admin' ||
(UserType === 'Super Admin User' &&
SAAccessCommonMaster?.DeleteAccess === 'Y') ||
(UserType === 'Employee' &&
empData?.DeleteAccess === 'Y') ||
UserType === 'Admin'
? statusFormatter(record, index)
: null
}
/>
) : (
<ReloadOutlined
style={{
color: '#52C41A',
}}
onClick={() =>
UserType === 'Super Admin' ||
(UserType === 'Super Admin User' &&
SAAccessCommonMaster?.DeleteAccess === 'Y') ||
(UserType === 'Employee' &&
empData?.DeleteAccess === 'Y') ||
UserType === 'Admin'
? statusFormatter(record, index)
: null
}
/>
)}
</a>
</Space>
) : null,
},
];
const columns1 = [
{
title: 'Sl.No',
key: 'sno',
align: 'center',
width: '100px',
render: (text, object, index) => (
<a style={{ color: 'black' }}>{(page - 1) * 10 + index + 1}</a>
),
},
{
title: 'Customber ID',
dataIndex: 'CustId',
key: 'CustId',
width: '150px',
render: (text) => <a style={{ color: 'black' }}>{text}</a>,
filteredValue: [searchedText],
onFilter: (value, record) => {
return (
String(record.OfferName)
?.toLowerCase()
?.includes(value?.toLowerCase()) ||
String(record.MinQty)?.toLowerCase()?.includes(value?.toLowerCase()) ||
String(record.MinPurchase)
?.toLowerCase()
?.includes(value?.toLowerCase()) ||
String(record.Point)?.toLowerCase()?.includes(value?.toLowerCase()) ||
String(record.RewardTypeName)
?.toLowerCase()
?.includes(value?.toLowerCase())
);
},
sorter: (a, b) => a?.OfferName?.length - b?.OfferName?.length,
sortOrder: sortedInfo.columnKey === 'OfferName' ? sortedInfo.order : null,
ellipsis: true,
},
{
title: 'Cust Name',
dataIndex: 'CustName',
key: 'CustName',
width: '80px',
align: 'right',
},
{
title: 'Cust Mobile No',
dataIndex: 'CustMobile',
key: 'CustMobile',
width: '120px',
align: 'right',
},
{
title: 'Cust Address',
dataIndex: 'Address1',
key: 'Address1',
width: '150px',
align: 'center',
},
{
title: 'Coupon Code',
dataIndex: 'CouponCode',
key: 'CouponCode',
width: '90px',
align: 'right',
},
{
title: 'Coupon Status',
dataIndex: 'CouponStatus',
key: 'CouponStatus',
width: '100px',
align: 'right',
render: (text, record) =>
record.CouponStatus === 'N' ? 'Not Used' : 'Used',
},
{
title: 'Issue Date',
dataIndex: 'IssueDate',
key: 'IssueDate',
width: '110px',
align: 'right',
render: (text) => (
<a style={{ color: 'black' }}>{dateFormatChange(text)}</a>
),
},
];
useEffect(() => {
dispatch(changeBreadCrumb({ items: items }));
if (location?.state?.Notiffy) {
setMessageType(location?.state?.Notiffy.messageType);
setMessageData(location?.state?.Notiffy.messageData);
}
Tabledatas();
getPreference();
}, []);
useEffect(() => {
if (UserType === 'Employee') {
fetchApi();
}
}, [UserType]);
useEffect(() => {
let hasAccess = false;
if (UserType === 'Admin' || UserType === 'Super Admin') {
hasAccess = true;
} else if (UserType === 'Employee') {
hasAccess = empData?.AddAccess === 'Y';
} else if (UserType === 'Super Admin User') {
hasAccess = SAAccessCommonMaster?.AddAccess === 'Y';
}
setaddnewAccess(!hasAccess);
}, [empData, SAAccessCommonMaster, UserType]);
const fetchApi = async () => {
let data = {
CompId: CompId,
BranchId: BranchId,
AppId: AppId,
EmpId: UserId,
};
let response = await dispatch(getEmpAccess(data)).unwrap();
let datas = response?.data?.data?.[0]?.EmpAccessDetails?.filter(
(item) => item.ConfigName === 'Coupon Wise Offer'
);
setEmpData(datas?.[0]);
};
const handelAddButton = () => {
navigateTo(`${subDirectory}setting/coupon/new`);
};
const onComplete = useCallback(() => {
setMessageData(null);
setMessageType(null);
}, []);
const Tabledatas = async () => {
let data = {
CompId: CompId,
BranchId: BranchId,
AppId: AppId,
};
let Response = await dispatch(getCouponsdata(data)).unwrap();
setTabledata(Response.data?.data);
};
const onSearch = (value) => {
setSearchedText(value);
};
const onSearchChange = (e) => {
setSearchedText(e?.target?.value);
};
const handleChange = (pagination, filters, sorter) => {
setSortedInfo(sorter);
};
const handlePageChange = (current) => {
setpage(current);
};
const CouponGenereate = async (row) => {
const { OfferId, UniqueId } = row;
const response = await dispatch(getGenCoupondata({ CompId, BranchId, OfferId, AppId, type: 'C' })).unwrap();
if (response?.data?.statusCode === 1) {
setCoupondata(response.data?.data);
const defaultSelectedKeys = [];
const data = response?.data?.data?.map(({
CustId,
CustName,
CustMobile,
CustEmail,
Address1,
CouponCode,
CouponStatus,
IssueDate,
Type,
BrName,
BrEmail, }, index) => {
if (Type === 'Y') defaultSelectedKeys.push(index);
return {
key: index,
CustId,
CustName,
CustMobile,
CustEmail,
Address1,
CouponStatus,
IssueDate,
Type,
BrName,
BrEmail,
CouponCode: CouponCode !== null ? CouponCode : genCoupencode()
}
})
setdata(data);
setSelectedRowKeys(defaultSelectedKeys);
setOpen(prev => !prev);
setUniqueid(UniqueId);
} else {
setMessageType('error');
setMessageData(response?.data?.data?.length === 0 ? "No Customers Listed for this Perticular Offer" : response?.data?.response);
}
};
const handleCancelNew = () => {
setOpen(prev => !prev);
};
const genCoupencode = (length = 6) => {
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
let promoCode = '';
for (let i = 0; i < length; i++) {
promoCode += characters.charAt(
Math.floor(Math.random() * characters.length)
);
}
return promoCode;
}
useEffect(() => {
if (data?.length > 0) {
let Filteredrowdata = data?.filter((a) =>
selectedRowKeys?.includes(a.key)
);
setSelectedRowData(Filteredrowdata);
}
}, [data]);
const onSelectChange = (newSelectedRowKeys) => {
let Filteredrowdata = data?.filter((a) =>
newSelectedRowKeys?.includes(a.key)
);
setSelectedRowKeys(newSelectedRowKeys);
setSelectedRowData(Filteredrowdata);
};
const rowSelection = {
selectedRowKeys,
onChange: onSelectChange,
getCheckboxProps: (record) => ({
disabled: record.Type === 'Y',
}),
selections: [
Table.SELECTION_ALL,
Table.SELECTION_INVERT,
Table.SELECTION_NONE,
{
key: 'odd',
text: 'Select Odd Row',
onSelect: (changeableRowKeys) => {
const newSelectedRowKeys = changeableRowKeys.filter(
(_, index) => index % 2 !== 0
);
setSelectedRowKeys(newSelectedRowKeys);
},
},
{
key: 'even',
text: 'Select Even Row',
onSelect: (changeableRowKeys) => {
const newSelectedRowKeys = changeableRowKeys.filter(
(_, index) => index % 2 === 0
);
setSelectedRowKeys(newSelectedRowKeys);
},
},
],
};
const handleSubmit = async () => {
if (selectedRowData?.length >= 1) {
const filteredData = selectedRowData?.filter(({ Type }) => Type != 'Y');
const { BrName, BrEmail } = filteredData?.[0] || {};
const Postdata = {
BrName,
BrEmail,
CouponId: Uniqueid,
CouponDetails: filteredData?.map(({ CustId, CouponCode, CustName, CustMobile, CustEmail }) => ({
CustId, CouponCode, CustName, CustMobile, CustEmail,
})),
CreatedBy: UserId,
};
setIsLoading(true);
const response = await dispatch(postGenCoupondata(Postdata)).unwrap();
if (response?.data?.statusCode === 1) {
const { CustomerDtl, BrName, BrEmail, Description, MinQty, MinPurchase } = response?.data;
if (checkedList?.includes("Mail")) {
const applicableEmailCustomers = CustomerDtl?.filter(({ CustEmail }) => CustEmail !== null) || [];
if (applicableEmailCustomers?.length > 0) {
const { RewardTypeName, AppliesTo, OfferAmt, ProdCount, RewardOrderTypeDetails, RewardTypeDetails, RewardFreeTypeDetails } = tabledata?.find(({ UniqueId: uid }) => uid === Uniqueid)
let Categories = ''
let Products = ''
if (RewardTypeName === 'Discount' && AppliesTo === 'S') {
Categories = RewardOrderTypeDetails?.filter(({ ProdCat }) => ProdCat !== 0 || ProdCat !== null)?.map(({ ProdCatName }) => ProdCatName)?.filter(Boolean).join()
Products = RewardOrderTypeDetails?.filter(({ ProdCat }) => ProdCat === 0 || ProdCat === null)?.map(({ ProdName }) => ProdName)?.filter(Boolean).join()
} else if (RewardTypeName === 'Free Products') {
Products = [...RewardTypeDetails?.map(({ ProdName }) => ProdName), ...RewardFreeTypeDetails?.map(({ ProdName }) => ProdName)]?.filter(Boolean).join()
}
const postEmailData = {
BrName, BrEmail, Description, MinQty, MinPurchase,
CustomerDtl: applicableEmailCustomers, RewardTypeName, AppliesTo, Categories, Products, Amount: OfferAmt,
Qty: ProdCount
};
await dispatch(postCustomerCouponMail(postEmailData)).unwrap();
}
}
if (checkedList?.includes("SMS")) {
const applicableSMSCustomers = CustomerDtl?.filter(({ CustMobile }) => CustMobile !== null) || [];
if (applicableSMSCustomers?.length > 0) {
const { RewardTypeName, AppliesTo, OfferAmt, ProdCount, RewardOrderTypeDetails, RewardTypeDetails, RewardFreeTypeDetails } = tabledata?.find(({ UniqueId: uid }) => uid === Uniqueid)
let Categories = ''
let Products = ''
if (RewardTypeName === 'Discount' && AppliesTo === 'S') {
Categories = RewardOrderTypeDetails?.filter(({ ProdCat }) => ProdCat !== 0 || ProdCat !== null)?.map(({ ProdCatName }) => ProdCatName)?.filter(Boolean).join()
Products = RewardOrderTypeDetails?.filter(({ ProdCat }) => ProdCat === 0 || ProdCat === null)?.map(({ ProdName }) => ProdName)?.filter(Boolean).join()
} else if (RewardTypeName === 'Free Products') {
Products = [...RewardTypeDetails?.map(({ ProdName }) => ProdName), ...RewardFreeTypeDetails?.map(({ ProdName }) => ProdName)]?.filter(Boolean).join()
}
const postSMSData = {
BrName, BrEmail, Description, MinQty, MinPurchase,
CustomerDtl: applicableSMSCustomers, RewardTypeName, AppliesTo, Categories, Products, Amount: OfferAmt,
Qty: ProdCount
};
await dispatch(postSMSCoupon(postSMSData)).unwrap();
}
}
setOpen(prev => !prev);
setMessageType('success');
setMessageData(`${response?.data?.response}`) ;
}
setIsLoading(false);
}
};
const onChange = list => {
setCheckedList(list);
};
const onCheckAllChange = e => {
setCheckedList(e.target.checked ? plainOptions?.map(({ value }) => value) : []);
};
return (
<div className="userPageTable">
<div className="userPageContent">
<div className="formAddNew">
<Messages
messageType={messageType}
messageData={messageData}
onComplete={onComplete}
/>
<div>
<FormHeader title={'Coupon Wise Offer'} />
</div>
<div className="searchAddDiv">
<div className="formSearch">
<Search
placeholder="Search"
onSearch={onSearch}
onSearchChange={onSearchChange}
/>
</div>
<Buttons
buttonText={'Add New'}
handleSubmit={() => handelAddButton()}
color="901D77"
disabled={addnewAccess}
icon={<PlusOutlined />}
>
OPEN
</Buttons>
</div>
</div>
<div className="reportTable">
<Tables
columns={columns}
data={tabledata}
dataSource={tabledata}
pagination={handlePageChange}
onChange={handleChange}
/>
</div>
</div>
<DefaultModal
open={Open}
title="Coupon Generation"
footer={true}
width={1100}
children={
<>
<Spin spinning={isLoading} tip="Sending...">
<div style={{ display: 'flex', flexDirection: "column", gap: "0.5rem", border: "1px solid #d9d9d9", padding: "0.5rem", borderRadius: "0.50rem" }}>
<p style={{
fontSize: '14px',
fontWeight: '500',
}}>Share Codes via :</p>
<Checkbox indeterminate={indeterminate} onChange={onCheckAllChange} checked={checkAll}>
Check All
</Checkbox>
<CheckboxGroup options={plainOptions} value={checkedList} onChange={onChange} />
</div>
<Table
rowSelection={{ ...rowSelection, selectedRowKeys }}
columns={columns1}
dataSource={data}
pagination={{
onChange: handlePageChange,
defaultPageSize: 10,
showSizeChanger: false,
hideOnSinglePage: true,
}}
onChange={handleChange}
/>
</Spin>
</>
}
handleSubmit={handleSubmit}
handleCancel={handleCancelNew}
/>
</div>
);
};
export default CouponWiseOfferlist;