Android_Retail/src/Pages/DeliveryChallan/DeliveryChallannew.jsx

1668 lines
56 KiB
JavaScript

import React, { useState, useEffect, useRef, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { useDispatch } from 'react-redux';
import {
Form,
Table,
Input,
Select,
AutoComplete,
Radio,
DatePicker,
Button,
Tooltip,
Space,
Segmented,
} from 'antd';
import { BsUpcScan } from "react-icons/bs";
import {
ArrowRightOutlined,
DeleteFilled,
SearchOutlined,
} from '@ant-design/icons';
import { IoMdAddCircleOutline } from 'react-icons/io';
import { FaEye, FaPrint, FaTruck } from 'react-icons/fa';
import { Messages } from '../../Components/Notifications/Messages.jsx';
import { InputField } from '../../Components/Forms/InputField.jsx';
import Buttons from '../../Components/Forms/Buttons.jsx';
import {
getSession,
pdfDiv,
printDiv,
validateSafeInput,
} from '../../Services/Others.js';
import FormHeader from '../PageComponents/FormHeader.jsx';
import { DropDowns } from '../../Components/Forms/DropDown.jsx';
import { CiBarcode } from 'react-icons/ci';
import {
AdminUserData,
getProdQuoaVariantdata,
getPurProductData,
} from '../../Features/PurchaseQuotation/PurchaseQuotation.js';
import './DeliveryChallan.scss';
import { getPurchaseTaxTypeData } from '../../Features/StockMaster/StockMaster.js';
import {
changeBreadCrumb,
getEmpAccess,
} from '../../Features/AppPage/CenterPage.js';
import { useAuth } from '../../AuthContext.jsx';
import { getAllCustomer } from '../../Features/BookingScreen/BookingData/BookingData.js';
const subDirectory = import.meta.env.BASE_URL;
import TooltipWrapper from '../../Components/Tooltip/Tooltip.jsx';
import { DefaultModal } from '../../Components/Modal/DefaultModal.jsx';
import { PostChallan } from '../../Features/DeliveryChallan/DeliveryChallan.js';
import { MdOutlineMail } from 'react-icons/md';
import DeliveryPrint from './DeliveryPrint.jsx';
import { Emailsend } from '../../Features/PurchaseOrder/PurchaseOrder.js';
import FloatLabel from '../../Components/Forms/FloatLabel/index.jsx';
import { debounce } from 'lodash';
import { DCPrintStyleFunction } from './DCPrintStyleFunction.js';
import { useSelector } from 'react-redux';
import { getPrintSelectionComponentData } from '../../Features/ThemeChange/ThemeChange.js';
const DeliveryChellanForm = () => {
const { SadminuserAccess } = useAuth();
let SAAccessCommonMaster = SadminuserAccess?.find(
(e) => e?.MenuName === 'Delivery challan'
);
const formRef = useRef(null);
const transportFormRef = useRef(null);
const [form] = Form.useForm();
const dispatch = useDispatch();
const navigate = useNavigate();
const CompId = getSession('CompId');
const BranchId = getSession('BranchId');
const AppId = getSession('AppId');
const UserId = getSession('UserId');
const UserType = getSession('UserType');
const [DCPrintTemplateStyle, setDCPrintTemplateStyle] = useState(null);
const [DCPrintTemplateDtl, setDCPrintTemplateDtl] = useState(null);
const [messageType, setMessageType] = useState(null);
const [messageData, setMessageData] = useState(null);
// const [AdminUser, setAdminUser] = useState([]);
const [SelecAdminUser, setSelecAdminUser] = useState(null);
const [SelTaxType, setSelTaxType] = useState(null);
const [SelTaxTypeName, setSelTaxTypeName] = useState(null);
const [ProductData, setProductData] = useState([]);
const [AllCustomer, setAllCustomer] = useState(null);
const [Modal, setModal] = useState(false);
console.log(AllCustomer, 'AllCustomer');
const [SelProduct, setSelProduct] = useState(null);
const [selectedProductName, setSelectedProductName] = useState(null);
const [productSearchText, setProductSearchText] = useState("");
const [scanner, setScanner] = useState(false);
console.log(ProductData, 'ProductData');
const [selectedProductVariantData, setselectedProductVariantData] =
useState(null);
const [Variants, setVariants] = useState();
const [TableData, setTableData] = useState([]);
const [editingKey, setEditingKey] = useState('');
const [TotalBillAmount, setTotalBillAmount] = useState(null);
const [TotalCgst, setTotalCgst] = useState(null);
const [TotalSgst, setTotalSgst] = useState(null);
const [TotalIgst, setTotalIgst] = useState(null);
const [TotalAmount, setTotalAmount] = useState(null);
const isEditing = (record, index) => index === editingKey;
const [empData, setEmpData] = useState();
const [addnewAccess, setaddnewAccess] = useState(true);
const [isbarcode, setisbarcode] = useState(false);
const [selectedMode, setSelectedMode] = useState('');
const [isSubmitted, setIsSubmitted] = useState(false);
const [PrintingData, setPrintingData] = useState([]);
const [iSEmail, setiSEmail] = useState(false);
const [pendingOrderDetails, setPendingOrderDetails] = useState(null);
const [pendingRecord, setPendingRecord] = useState(null);
console.log(PrintingData, 'PrintingDataPrintingData');
console.log(TableData, 'TableData');
const items = [
{
name: 'Home',
link: `${subDirectory}app-page/home`,
},
{
name: 'Delivery Challan',
link: `${subDirectory}setting/delivery-challan`,
},
];
useEffect(() => {
dispatch(changeBreadCrumb({ items: items }));
// getAdminUserdata();
getProduct();
fetchdata();
getPrintData();
}, []);
const changebarcode = useCallback(() => {
setisbarcode((prev) => !prev);
}, []);
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 debouncedScannerSearch = useCallback(
debounce((value) => {
const qr = value?.trim();
const matchedProduct = ProductData.find(
(p) => p.QRCode?.toLowerCase() === qr.toLowerCase()
);
if (matchedProduct) {
let productName = {};
productName.label = `${matchedProduct?.ProdName} (${matchedProduct.Size} ${matchedProduct.UomName})${matchedProduct?.BrandName ? ` - ${matchedProduct?.BrandName}` : ''}`
ProductDropDownChange(matchedProduct.ProdId, productName);
if (matchedProduct?.ProdVariantPriceDetails?.length < 2) {
setSelectedProductName("");
setSelProduct(null)
}
} else {
setMessageType("error");
setMessageData("The Scanned Product not Available in Product List")
}
}, 300),
[ProductData]
);
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 === 'Purchase Quotation'
);
setEmpData(datas?.[0]);
};
const getPrintData = async () => {
let data = {
CompId: CompId,
BranchId: BranchId,
AppId: AppId,
};
let response = await dispatch(getPrintSelectionComponentData(data)).unwrap();
if(response?.data?.statusCode === 1) {
let DCPrintTemplate =
response?.data?.data?.[0]?.ComponentDetails?.find(
(item) => item.SetasDefault == 'Y' && item.PrintTypeName === 'Delivery Chalan'
);
console.log(DCPrintTemplate,response?.data?.data?.[0]?.ComponentDetails?.find(
(item) => item.SetasDefault == 'Y' && item.PrintTypeName === 'Delivery Chalan'
), 'DCPrintTemplate');
setDCPrintTemplateStyle(DCPrintTemplate?.StyleName);
setDCPrintTemplateDtl(DCPrintTemplate);
}
};
// useEffect(() => {
// Print();
// }, [PrintData]);
useEffect(() => {
let total = TableData?.reduce((accumulator, currentValue) => {
return accumulator + currentValue.NetAmt;
}, 0);
setTotalAmount(total);
let cgst = TableData?.filter(
(item) => item.TaxName?.toLowerCase() === 'cgst,sgst'
);
let totalgst = cgst?.reduce((accumulator, currentValue) => {
return accumulator + currentValue.TaxAmt;
}, 0);
setTotalCgst(totalgst / 2);
setTotalSgst(totalgst / 2);
let igst = TableData?.filter(
(item) => item.TaxName?.toLowerCase() === 'igst'
);
let totaligst = igst?.reduce((accumulator, currentValue) => {
return accumulator + currentValue.TaxAmt;
}, 0);
setTotalIgst(totaligst);
let billtotal = TableData?.reduce((accumulator, currentValue) => {
return accumulator + currentValue.NetAmt;
}, 0);
console.log(billtotal, total, TableData, 'billtotal');
setTotalBillAmount(billtotal);
}, [TableData]);
const getProduct = async () => {
let Product = await dispatch(
getPurProductData({
CompId: CompId,
AppId: AppId,
BranchId: BranchId,
ActiveStatus: 'A',
})
).unwrap();
if (Product?.data?.statusCode === 1) {
let Productonlydata = Product?.data?.data?.filter(
(item) => item?.ProdTypeName === 'Product'
);
setProductData(Productonlydata);
} else {
setProductData([]);
}
};
const fetchdata = async () => {
let res = await dispatch(
getAllCustomer({ CompId: CompId, AppId: AppId, branchId: BranchId })
).unwrap();
await setAllCustomer(res?.data?.data);
};
const handleAdminUserDropDownChange = (UserId) => {
setSelecAdminUser(UserId);
formRef.current?.setFieldsValue({ CustId: UserId });
setIsSubmitted(false);
};
const handleScanSearch = () => {
if (scanner === false) {
setMessageType("success");
setMessageData("Search by QrCode/BarCode Enabled")
} else {
setMessageType("success");
setMessageData("Search by QrCode/BarCode Disabled")
}
setScanner(prev => !prev)
setSelectedProductName(null);
setselectedProductVariantData(null);
setVariants(null)
formRef?.current?.setFieldsValue({
ProdId: null,
VarProdId: null
});
}
const handleProductSearch = (value) => {
if (scanner) {
debouncedScannerSearch(value);
}
setProductSearchText(value)
setSelectedProductName(value);
setselectedProductVariantData([]);
setVariants([])
};
const ProductDropDownChange = async (ProdId, option) => {
formRef?.current?.resetFields(['VarProdId']);
setProductSearchText("")
setSelectedProductName(option?.label ? option?.label : '')
console.log(ProdId, 'ProdIdProdId');
setSelProduct(ProdId);
formRef.current?.setFieldsValue({ ProdId: ProdId });
let x = ProductData?.find((e) => e.ProdId === ProdId)?.ProdName;
let variantValues1 = await dispatch(
getProdQuoaVariantdata({
CompId: CompId,
AppId: AppId,
BranchId: BranchId,
prodName: x,
})
).unwrap();
let variants1 = variantValues1?.data?.data;
// let cc = variants1?.[0]?.ProductDetail;
let cc = variants1?.filter((item) => item?.ProdName == x)?.[0]?.ProductDetail;
setVariants(
cc?.[0]?.ProdVariantDetails?.map((detail) => ({
...detail,
ProdIdProdName: `${detail.ProdVariantName} ${detail.ProdId}`,
}))
);
if (cc?.[0]?.ProdVariantDetails?.length < 2) {
if (TableData?.some((e) => e.ProdId === ProdId)
) {
setMessageType('error');
setMessageData('Already Product Exists');
} else {
let ProductData1 = ProductData?.find((e) => e.ProdId === ProdId);
console.log(ProductData1, 'ProductData1ProductData1');
let ProduData2 = {
ProdId: ProductData1?.ProdId,
ProdName: ProductData1?.ProdName,
UomName: ProductData1?.UomName,
Price: ProductData1?.SellPrice,
TaxName: ProductData1?.TaxName,
HSNCode: ProductData1?.HSNCode,
Size: ProductData1?.Size,
InwardDtlId: ProductData1?.InwardDtlId,
// OnePcsAvailable:ProductData1?.OnePcsAvailable,
// NumberofPieceinside: ProductData1?.NoOfPcs,
// AmountPerPiece: ProductData1?.OnePcsPrice,
TaxId: ProductData1?.TaxId,
TaxPercentage: ProductData1?.TaxPercentage,
SinglePc: ProductData1?.OnePcsAvailable,
};
let tempPurData = {
...ProduData2,
Qty: 0,
// 'InwardPrice': 0,
// PurcDisc: 0,
// NetAmt: 0,
// BillAmount: 0,
// DiscType: 'P',
// 'WhSalePrice': 0,
// 'ReceivedQty': 0,
// 'AcceptedQty': 0,
// 'RejectedQty': 0,
// "OfferPrice": 0,
// "SpecialPrice": 0,
ProdVariantName: 'Variant 1',
// "FreeItem": 0,
// 'TaxPerc': PurcselectedTax ? PurcselectedTax : 0,
// TaxAmt: 0,
// 'TaxType': SelectedPurcTaxType ? SelectedPurcTaxType : 0,
};
form.setFieldsValue({
// [`BalanceQty${TableData.length + 1}`]: undefined,
// [`ReceivedQty${index}`]: undefined,
// [`AcceptedQty${index}`]: undefined,
// [`RejectedQty${index}`]: undefined,
// [`Amount${TableData.length + 1}`]: ProductData1?.SellPrice,
// [`FreeQty${index}`]: undefined,
// [`InwardPrice${index}`]: undefined,
// [`MRP${index}`]: undefined,
// [`PurcDisc${TableData.length + 1}`]: 0,
// [`SellPrice${TableData.length + 1}`]: ProductData1?.SellPrice,
// [`WhSalePrice${index}`]: undefined,
// [`offerSalePrice${index}`]: undefined,
// [`splSalePrice${index}`]: undefined
});
setTableData([...TableData, tempPurData]);
}
}
};
const ProductVariantDropDownChange = (value) => {
const ProdName2 = Variants?.filter(
(item) => item.ProdIdProdName === value
)?.[0]?.ProdVariantName;
const ProdName1 = TableData?.some(
(e) =>
e.ProdId === SelProduct &&
e.ProdVariantName === ProdName2
);
if (ProdName1) {
setMessageType('error');
setMessageData('Already variant Exists');
} else {
const ProdName = Variants?.filter(
(item) => item.ProdIdProdName === value
)?.[0]?.ProdVariantName;
const OnePcsAvailable = Variants?.filter(
(item) => item.ProdIdProdName === value
)?.[0]?.OnePcsAvailable;
formRef?.current?.setFieldsValue({ VarProdId: value });
setselectedProductVariantData(ProdName);
// let x = VariantData1?.filter((e) => e.InwardDtlId == value);
// let u = ProductData?.find((e) => e.ProdId == selectedProductData);
// console.log(first)
let ProductData1 = ProductData?.find((e) => e.ProdId === SelProduct);
console.log(ProductData1, 'ProductData1ProductData1');
let mrp;
let sellprice;
let InwardDtlId;
if (ProdName == 'Variant 1') {
mrp = ProductData1?.MRP;
sellprice = ProductData1?.SellPrice;
InwardDtlId = ProductData1?.ProdVariantPriceDetails?.find(
(item) => item.ProdVariantName == ProdName
)?.InwardDtlId;
} else {
mrp = ProductData1?.ProdVariantPriceDetails?.find(
(item) => item.ProdVariantName == ProdName
)?.MRP;
sellprice = ProductData1?.ProdVariantPriceDetails?.find(
(item) => item.ProdVariantName == ProdName
)?.SellPrice;
InwardDtlId = ProductData1?.ProdVariantPriceDetails?.find(
(item) => item.ProdVariantName == ProdName
)?.InwardDtlId;
}
let ProduData2 = {
ProdId: ProductData1?.ProdId,
// MRP: mrp,
ProdName: ProductData1?.ProdName,
UomName: ProductData1?.UomName,
Price: sellprice,
TaxName: ProductData1?.TaxName,
HSNCode: ProductData1?.HSNCode,
// StockAvailable: ProductData1?.StockAvailable,
// OnePcsAvailable:ProductData1?.OnePcsAvailable,
// NumberofPieceinside: ProductData1?.NoOfPcs,
// AmountPerPiece: ProductData1?.OnePcsPrice,
InwardDtlId: InwardDtlId,
Size: ProductData1?.Size,
TaxId: ProductData1?.TaxId,
TaxPercentage: ProductData1?.TaxPercentage,
};
// ProduData2["StockAvailable"]="Y"
let tempPurData = {
...ProduData2,
Qty: 0,
// PurcDisc: 0,
// NetAmt: 0,
// BillAmount: 0,
// DiscType: 'P',
ProdVariantName: ProdName,
// TaxAmt: 0,
};
setTableData([...TableData, tempPurData]);
}
};
const onComplete = useCallback(() => {
setMessageData(null);
setMessageType(null);
}, []);
const save = async (index) => {
try {
const row = await form?.validateFields();
const modifiedObject = {};
for (const key in row) {
const newKey = key.slice(0, -1); // Remove the last character ("0") from the key
modifiedObject[newKey] = row[key];
}
const newData = [...TableData];
// const index = newData.findIndex((item) => recordKey === item.InwardDtlId);
if (index > -1) {
const item = newData[index];
newData.splice(index, 1, { ...item, ...modifiedObject });
setTableData(newData);
setEditingKey('');
}
} catch (err) {
console.error('Save failed:', err);
}
};
const handleKeyPress = async (e, record, index) => {
if (e.key === 'Enter') {
try {
await form.validateFields();
save(index);
} catch (error) {
console.error('Save failed:', error);
}
}
};
const statusFormatter = (record)=>{
let filterData=TableData?.filter((e)=> e?.InwardDtlId !=record.InwardDtlId);
setTableData(filterData)
}
const getColumns = (data, seltax) => {
const hasDiscount = data?.some((record) => record.PurcDisc > 0);
const baseColumns = [
{
title: 'Sl.No',
align: 'center',
key: 'sno',
width: '50px',
render: (text, object, index) => (
<a style={{ color: 'black' }}>{index + 1}</a>
),
},
{
title: 'Product Name',
dataIndex: 'ProdName',
key: 'ProdName',
align: 'right',
width: '300px',
render: (text, record, index) => (
<a style={{ color: 'black' }}>
{
record?.ProdName +
'(' +
record?.Size +
'-' +
record?.UomName +
')'
// +
// '(' +
// record?.ProdVariantName +
// ')'
}
</a>
),
},
{
title: 'Variant Name',
dataIndex: 'ProdVariantName',
key: 'ProdVariantName',
},
{
title: 'Qty',
dataIndex: 'Qty',
key: 'Qty',
editable: true,
with: '100px',
render: (text, record, index) => {
return isEditing(record, index) ? (
<Form.Item
name={'Qty' + index}
rules={[
{
required: true,
pattern: /^[1-9]\d*(\.\d+)?$/,
message: 'Quantity must be at least 1.',
},
]}
>
<Input
onPressEnter={(e) => handleKeyPress(e, record, index)}
onBlur={(e) => handleQtyChange(e, record)}
onChange={(e) => handleQtyChange(e, record, index)}
autoComplete="off"
inputMode="decimal"
onInput={(e) => {
let cleanedValue = e.target.value.replace(/[^0-9.]/g, ''); // Remove invalid characters
const parts = cleanedValue.split('.');
if (cleanedValue.startsWith('.')) {
cleanedValue = '0' + cleanedValue;
}
e.target.value =
parts.length > 2
? `${parts[0]}.${parts.slice(1).join('')}`
: cleanedValue;
}}
/>
</Form.Item>
) : (
text
);
},
},
{
title: 'Action',
key: 'Action',
dataIndex: 'Action',
render: (_, record, index) =>
TableData.length >= 1 ? (
<Space size="middle">
<a>
{ (
<DeleteFilled
style={{
color: '#FF4D4F',
}}
onClick={() =>
statusFormatter(record)
}
/>
)
}
</a>
</Space>
) : null,
},
];
return baseColumns;
};
const columns = getColumns(TableData, SelTaxType);
const edit = (record, index) => {
form.setFieldsValue({ ...record });
setEditingKey(index);
// setindex(index);
form.setFieldsValue({
[`Qty${index}`]: record?.Qty,
// [`NetAmt${index}`]: !isNaN(record?.NetAmt) ? record?.NetAmt : 0,
// [`PurcDisc${index}`]: record?.PurcDisc,
// [`Price${index}`]: record?.Price,
});
};
// };
// const statusFormatters = (record, index) => {
// // Remove the row from table data
// const newData = TableData.filter((_, i) => i !== index);
// setTableData(newData);
// setDelete(true);
// setEditingKey('');
// // Get all current form values
// const currentFormValues = form.getFieldsValue();
// // Clear all form fields first
// const allFieldsToClear = [];
// for (let i = 0; i < TableData.length; i++) {
// allFieldsToClear.push(
// `BalanceQty${i}`,
// `Amount${i}`,
// `PurcDisc${i}`,
// `SellPrice${i}`,
// `Qty${i}`,
// `NetAmt${i}`,
// `Price${i}`,
// `DiscType${i}`
// );
// }
// const clearAllValues = {};
// allFieldsToClear.forEach((field) => {
// clearAllValues[field] = undefined;
// });
// // Set new form values with correct indices
// const newFormValues = {};
// newData.forEach((item, newIndex) => {
// newFormValues[`Qty${newIndex}`] = item.Qty;
// newFormValues[`NetAmt${newIndex}`] = item.NetAmt;
// newFormValues[`PurcDisc${newIndex}`] = item.PurcDisc;
// newFormValues[`Price${newIndex}`] = item.Price;
// newFormValues[`DiscType${newIndex}`] = item.DiscType;
// });
// // Apply the new form values
// form.setFieldsValue({ ...clearAllValues, ...newFormValues });
// console.log(form.getFieldsValue(), 'jjij');
// };
const handleQtyChange = (e, record, index) => {
const qty = e.target.value;
if (!/^\d*\.?\d*$/.test(qty)) {
setMessageType('error');
setMessageData('Only numeric values are allowed');
return;
}
const sellprice = parseInt(record.Price);
const Amount = !isNaN(sellprice * parseInt(qty))
? sellprice * parseInt(qty)
: 0;
const taxamt =
SelTaxTypeName?.toLowerCase() === 'withtax'
? (Amount * parseInt(record?.TaxPercentage)) /
(100 + parseInt(record?.TaxPercentage))
: 0;
const newData = TableData.map((item, index1) => {
if (index1 === index) {
return {
...item,
Qty: qty,
NetAmt: Amount,
TaxAmt: taxamt,
// BillAmount: Amount - taxamt,
TotalAmount: Amount * qty,
GrossTotal: Amount + taxamt,
ProductRate: item.Price,
};
}
return item;
});
setTableData(newData);
form.setFieldsValue({
...form.getFieldsValue(),
[`Qty${index}`]: qty,
// [`NetAmt${index}`]: Amount,
// [`ReceivedQty${index}`]: qty,
// [`AcceptedQty${index}`]: acceptedQty,
// [`RejectedQty${index}`]: qty - acceptedQty,
// ReceivedQty: qty,
// AcceptedQty: acceptedQty,
// RejectedQty: qty - acceptedQty,
// [`PurcDisc${index}`]: 0,
// [`DiscType${index}`]: 'P',
});
};
const PrintQuotation = async () => {
if (TableData.some((item) => !item.Qty || parseFloat(item.Qty) < 1)) {
setMessageType('error');
setMessageData('Every product must have a quantity of at least 1.');
return;
}
setIsSubmitted(true);
// await printDiv(`Pur-Quot-Print`, QuotationStyle)
let data1 = transportFormRef.current?.getFieldsValue();
console.log(data1, 'data1');
let data = {
AppId: AppId,
CompId: CompId,
BranchId: BranchId,
CustId: SelecAdminUser,
TotalAmount: TotalBillAmount,
TaxAmount: TotalCgst + TotalSgst + TotalIgst || 0,
GrandTotal: TotalAmount,
VehicleNo: data1?.vehicleNo ? data1?.vehicleNo : null,
Remarks: '',
ModeOfTransport: selectedMode,
TransporterId: data1?.transporter ? data1?.transporter : null,
TransporterName: data1?.transporterName ? data1?.transporterName : null,
ProductDetails: TableData?.map((item) => {
return {
ProdId: item?.ProdId,
InwardDtlId: item?.InwardDtlId,
SinglePc: item?.SinglePc,
Qty: item?.Qty,
ProductRate: item?.ProductRate,
TotalAmount: item?.TotalAmount,
TaxAmount: item?.TaxAmt,
TaxId: item?.TaxId,
GrossTotal: item?.TotalAmount,
};
}),
CreatedBy: UserId,
};
let response = await dispatch(PostChallan(data)).unwrap();
console.log(response, 'responseresponse');
if (response?.data?.statusCode == 1) {
setMessageType('success');
setMessageData(response?.data?.response);
transportFormRef?.current?.resetFields();
formRef?.current?.resetFields();
setSelecAdminUser();
setSelTaxType();
setSelProduct();
setSelTaxTypeName();
setVariants();
setTotalBillAmount();
setTableData([]);
setTotalCgst();
setTotalSgst();
setTotalIgst();
const challanDetail = response?.data?.DeliveryChallanDetails?.[0];
const orderData = {
Remarks: challanDetail?.Remarks,
DCNo: challanDetail?.DCNo,
DCDate: challanDetail?.DCDate,
CustMobile: challanDetail?.CustMobile,
CustName: challanDetail?.CustName,
TransporterName: challanDetail?.TransporterName,
ModeOfTransport: challanDetail?.ModeOfTransport,
TransporterId: challanDetail?.TransporterId,
ProductDetails: challanDetail?.ProductDetails,
TotalAmount: challanDetail?.TotalAmount,
VehicleNo: challanDetail?.VehicleNo
};
setPrintingData([orderData]);
navigate(`${subDirectory}setting/delivery-challan`, {
state: {
Notiffy: {
messageType: 'success',
messageData: response?.data?.response,
},
},
});
}
// if (response?.data?.statusCode == 1) {
// navigate(`${subDirectory}setting/customer-master/`, {
// state: {
// Notiffy: {
// messageType: 'success',
// messageData: response?.data?.response,
// },
// },
// });
// }
else {
setMessageType('error');
setMessageData(response?.data?.response);
}
};
const PurchaseOrderStyle = `<style>
@media print {
@page {
size: A4;
margin: 0;
}
.Quo-Print-Body {
width: 195mm;
margin: 0 auto;
// padding: 10mm;
}
}
.Quo-Print-Body {
margin: 0;
padding: 10px;
background: white;
}
.Quo-Print-Content {
display: flex;
flex-direction: column;
width: 100%;
height:100%
max-width: 200mm;
margin: 0 auto;
border: 1px solid rgb(170, 164, 164);
padding: 10px;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
gap:0.5rem;
}
.Quo-print-Logo{
width: 50px ;
height: 50px;
margin:5px 0 0 5;
}
.Quo-Print-ComCus{
display:flex;
flex-direction:column;
height:18vh;
justify-content:space-between;
}
.Quo-Print-Tabsum{
display:flex;
flex-direction:column;
justify-content:space-between;
gap:1rem;
height:60vh;
}
.Quo-Print-Header{
display: flex;
flex-direction: row;
justify-content: space-between;
}
.Quo-Print-Company{
display:flex;
flex-direction:column;
padding:10px;
gap:0.1rem;
}
.Quo-Print-Cname{
font-size:25px;
}
.Quo-Print-address{
font-size:22px;
display:flex;
flex-wrap:wrap;
}
.Quo-Print-Qno{
display:flex;
flex-direction:column;
padding:10px;
gap:0.1rem;
}
.Quo-Print-Customer{
display:flex;
flex-direction:Column;
padding-left:10px;
gap:0.1rem;
width: 100%;
}
.Horizondal-line{
border-bottom: 0.5px solid rgb(170, 164, 164);
}
.Quo-Print-Table{
display:flex;
} .Quo-Print-ProTable {
width: 100%;
border-collapse: collapse;
margin-top: 15px;
}
.Quo-Print-DataRow {
// line-height: 2.5rem;
border-bottom: 1px solid #eee;
}
.Quo-Print-tableheader {
background-color: #f8f9fa;
border-top: 1px solid rgb(170, 164, 164);
border-bottom: 1px solid rgb(170, 164, 164);
line-height: 3rem;
}
.Quo-Print-TableData {
text-align: right;
padding: 8px;
font-size: 20px;
}
.Quo-Print-TableDataSno {
text-align: center;
padding: 8px;
font-size: 20px;
width: 60px;
}
.Quo-Print-TableDataName {
text-align: left;
padding: 8px;
font-size: 20px;
}
.Quo-Print-headingData {
text-align: center;
padding: 8px;
font-size: 22px;
font-weight: bold;
}
.Quo-Print-TableDataAmt{
text-align:right;
padding-right:5px;
font-size:20px;
}
.Quo-Print-Summary{
display:flex;
flex-direction:row;
justify-content: flex-end;
}
.Quo-Print-SummTableData{
text-align:right;
padding:1px;
font-size:20px;
}
.Quo-Print-Total{
display:flex;
justify-content:flex-end;
border:0.5px solid black;
width:300px;
margin-right: 10px;
font-size:20px;
}
}
</style>`;
const handleSendEmailWithEnteredEmail = async (values) => {
const record = { ...pendingRecord, CustEmail: values.email };
await handleEmailClick(pendingOrderDetails, record);
setiSEmail(false);
setPendingOrderDetails(null);
setPendingRecord(null);
form.resetFields();
};
const handlePrint = async() => {
const DCstyle = await DCPrintStyleFunction(
DCPrintTemplateStyle == undefined ? 'Style 13' : DCPrintTemplateStyle);
const stylesMap = {
'Style 1': 'DCPrintStyle1',
'Style 2': 'DCPrintStyle2',
'Style 3': 'DCPrintStyle3',
'Style 4': 'DCPrintStyle4',
'Style 5': 'DCPrintStyle5',
'Style 6': 'DCPrintStyle6',
'Style 7': 'DCPrintStyle7',
'Style 8': 'DCPrintStyle8',
'Style 9': 'DCPrintStyle9',
'Style 10': 'DCPrintStyle10',
'Style 11': 'DCPrintStyle11',
'Style 12': 'DCPrintStyle12',
'Style 13': 'DC-Default-Print',
A4: 'DCPrintStyleA4',
A5: 'DCPrintStyleA5',
A4Standard: 'DCPrintStyleA4Standard',
};
const selectedStyle =
stylesMap[
DCPrintTemplateStyle == undefined ? 'Style 13' : DCPrintTemplateStyle
];
console.log(selectedStyle,DCstyle, 'selectedStyle');
setTimeout(() => {
printDiv(`${selectedStyle}`, DCstyle);
}, 100);
};
const onChangeprodFunction = (e) => {
if (isbarcode) {
// When in barcode mode, search by QRCode
const productByQR = ProductData.find(
(p) => p.QRCode && p.QRCode.toLowerCase() === e.toLowerCase()
);
if (productByQR) {
const productValue =
productByQR.ProdName +
' ' +
'(' +
productByQR.Size +
productByQR.UomName +
')';
form.setFieldsValue({ ProdId: productValue });
setSelProduct(productValue);
ProductDropDownChange({ value: productValue });
}
} else {
// Normal mode - search by product name
form.setFieldsValue({ ProdId: e });
setSelProduct(e);
}
};
const transporterFn = () => {
setModal(true);
};
const handleEmailClick = async (ProductDetails, record) => {
// alert("This feature is not available yet. Please contact support for assistance.");
const orderData = {
0: { ...record },
customerName: record?.CustName || '',
CustName: record?.CustName || '',
customerAddress: record?.AddressDetails || '',
Address1: record?.AddressDetails || '',
customerMobile: record?.CustMobile || '',
MobileNo: record?.CustMobile || '',
CustMail: record?.CustEmail,
};
// setPrintData(record);
if (orderData?.CustMail) {
setTimeout(async () => {
try {
const blob = await pdfDiv('Pur-Order-Print', PurchaseOrderStyle);
console.log(blob, 'blobblob');
const payload = {
fileBlob: blob,
toEmail: orderData?.CustMail,
type: 'PurchaseOrder',
messageTemplatesList: [],
};
const res = await dispatch(Emailsend(payload))?.unwrap();
console.log('✅ API Response:', res?.data || res);
setMessageData('Email sent successfully');
setMessageType('success');
} catch (error) {
console.error('❌ Email send failed:', error);
setMessageData('Email failed to send');
setMessageType('error');
}
}, 300);
} else {
setPendingOrderDetails(ProductDetails);
setPendingRecord(record);
setiSEmail(true);
}
};
const handleTransportModeChange = (e) => {
setSelectedMode(e.target.value);
// Set the value in the transport form using ref
transportFormRef.current?.setFieldsValue({
transportationMode: e.target.value,
});
};
const closeDeliveryChallanModel = (e) => {
let data = transportFormRef.current?.getFieldsValue();
if (data.lrDate && data.lrDate.format) {
data.lrDate = data.lrDate.format('YYYY-MM-DD');
}
if (data.dateOfSupply && data.dateOfSupply.format) {
data.dateOfSupply = data.dateOfSupply.format('YYYY-MM-DD');
}
console.log(data, 'datadata');
e.stopPropagation();
setModal(false);
};
return (
<div className="pageOverAll">
<div className="userPage">
<div className="userPageContent">
<Messages
messageType={messageType}
messageData={messageData}
onComplete={onComplete}
/>
<div className="formName"
style={{
display: 'flex',
justifyContent: 'space-between',
marginTop: '12px',
}}>
<FormHeader title={'Delivery Challan'} />
<div
style={{
display: 'flex',
alignItems: 'center',
gap: '7px',
padding: '5px',
backgroundColor: 'rgb(29 168 80)',
borderRadius: '5px',
color: 'white',
width: '130px',
cursor: 'pointer',
fontFamily: 'Poppins',
fontWeight: '500',
fontSize: "14px",
justifyContent: "center",
}}
onClick={() => navigate(`${subDirectory}setting/delivery-challan/list`)}
>
<FaEye /> <span>View Chellans</span>
</div>
</div>
<div className="Quo-formDiv">
<Form
ref={formRef}
className="formDivAnt"
onFinish={PrintQuotation}
>
<div className="formDivS">
<div className="DeliveryChallan-inputForm">
<div className="DeliveryChellanDetails">
<div>
<Form.Item
name="CustId"
rules={[
{
required: true,
message: 'Please Select Customer',
},
]}
>
<DropDowns
options={AllCustomer?.map((option) => ({
value: option.CustId,
label:
option.CustShortName ||
option.CustName ||
option.CustMobile,
}))}
label={<label class="required">Customer</label>}
className="field-DropDown"
onChangeFunction={handleAdminUserDropDownChange}
/>
</Form.Item>
</div>
<div className="DeliveryChallanDropDown">
<Form.Item
name="ProdId"
rules={[
{
required: true,
message: 'Please Select Product',
},
]}
>
<div className="product-scan sales-quotation">
<FloatLabel label={"Product Name"} value={selectedProductName}>
<AutoComplete
className="field-DropDown"
value={selectedProductName}
filterOption={(input, option) => {
const product = ProductData.find(p => p.ProdId === option.value);
const nameMatch = option.label.toLowerCase().includes(productSearchText.toLowerCase());
const qrMatch = product?.QRCode?.toLowerCase() == productSearchText.toLowerCase();
return nameMatch || qrMatch;
}}
options={!scanner ? ProductData?.map
((option) => ({
value: option.ProdId,
label: `${option.ProdName} (${option.Size} ${option.UomName})${option?.BrandName ? ` - ${option?.BrandName}` : ''}`
})) : []}
onSelect={ProductDropDownChange}
onChange={handleProductSearch}
onKeyDown={(e) => {
if (scanner && e.key === "Enter") {
e.preventDefault();
}
}}
>
</AutoComplete>
</FloatLabel>
<Tooltip title={"BarCode/QrCode"} placement={"top"}>
<BsUpcScan strokeWidth={0.5} color="#000" style={{ fontSize: "16px", color: scanner ? "#52c41a" : "#888", fontWeight: "600" }} className="product-scan-Icon" onClick={handleScanSearch} />
</Tooltip>
</div>
</Form.Item>
{/* <Form.Item
name="ProdId"
rules={[
{
required: true,
message: 'Please Select Product',
},
]}
>
<AutoComplete
options={ProductData?.map((option) => ({
value:
option.ProdName +
' ' +
'(' +
option.Size +
option.UomName +
')',
label:
option.ProdName +
' ' +
'(' +
option.Size +
option.UomName +
')',
qrCode: option.QRCode,
}))}
style={{ width: '250px', height: '48px' }}
onSelect={(value, option) => {
if (isbarcode && option.qrCode) {
const productByQR = ProductData.find(
(p) => p.QRCode === option.qrCode
);
if (productByQR) {
ProductDropDownChange({
value:
productByQR.ProdName +
' ' +
'(' +
productByQR.Size +
productByQR.UomName +
')',
});
}
} else {
ProductDropDownChange(option);
}
}}
filterOption={(input, option) => {
if (isbarcode) {
return (
option.qrCode &&
option.qrCode
.toLowerCase()
.includes(input.toLowerCase())
);
} else {
return option.label
.toLowerCase()
.includes(input.toLowerCase());
}
}}
value={SelProduct}
>
<InputField
label="Product Name"
style={{}}
onChange={(e) =>
onChangeprodFunction(e?.target?.value)
}
onPressEnter={(e) =>
onChangeprodFunction(e?.target?.value)
}
isOnChange={SelProduct ? true : false}
suffix={
<TooltipWrapper
title="Search Product Name"
// isMobile={isMobile}
>
<CiBarcode
style={{
fontSize: '22px',
paddingRight: '1px',
}}
color={isbarcode ? 'green' : ' '}
onClick={changebarcode}
/>
<SearchOutlined
style={{ color: 'rgba(0,0,0,.45)' }}
/>
</TooltipWrapper>
}
/>
</AutoComplete>
</Form.Item> */}
{Variants?.length > 1 && (
<Form.Item name="VarProdId">
<DropDowns
options={Variants?.map((option) => ({
value: option.ProdIdProdName,
label: option.ProdVariantName,
}))}
label={'Variant Name'}
className="field-DropDown"
onChangeFunction={(e) =>
ProductVariantDropDownChange(e)
}
/>
</Form.Item>
)}
<div
className="Transport-Details"
style={{ textAlign: 'center' }}
onClick={transporterFn}
>
<div>
<IoMdAddCircleOutline size={20} /> Add Transport Details{' '}
<FaTruck scale={20} />
</div>
<DefaultModal
title={
<div style={{ textAlign: 'center' }}>
<FormHeader title={'Transport Details'} />
</div>
}
handleCancel={(e) => {
closeDeliveryChallanModel(e);
}}
open={Modal}
width={700}
footer={null}
children={
<div className="transport-details-form">
<Form layout="vertical" ref={transportFormRef}>
<div style={{ marginBottom: '20px' }}>
<label
style={{
fontSize: '16px',
fontWeight: '500',
}}
>
Transportation Mode
</label>
<div style={{ marginTop: '10px' }}>
<Radio.Group
onChange={handleTransportModeChange}
value={selectedMode}
>
<Radio value="road">Road</Radio>
<Radio value="rail">Rail</Radio>
<Radio value="air">Air</Radio>
<Radio value="notApplicable">
Not Applicable
</Radio>
</Radio.Group>
</div>
</div>
<div
style={{
display: 'grid',
gridTemplateColumns: '1fr 1fr',
gap: '20px',
}}
>
{/* <Form.Item name="lrNumber">
<InputField
label="LR Number"
onChange={(e) =>
transportFormRef.current?.setFieldsValue(
{ lrNumber: e.target.value }
)
}
/>
</Form.Item>
<Form.Item name="lrDate" label="LR Date">
<DatePicker
style={{ width: '50%' }}
format="DD-MM-YYYY"
onChange={(date) =>
transportFormRef.current?.setFieldsValue(
{ lrDate: date }
)
}
/>
</Form.Item> */}
<Form.Item name="vehicleNo">
<InputField
label="Vehicle No."
onChange={(e) =>
transportFormRef.current?.setFieldsValue(
{ vehicleNo: e.target.value }
)
}
/>
</Form.Item>
{/* <Form.Item
name="dateOfSupply"
label="Date of Supply"
>
<DatePicker
style={{ width: '50%' }}
format="DD-MM-YYYY"
onChange={(date) =>
transportFormRef.current?.setFieldsValue(
{ dateOfSupply: date }
)
}
/>
</Form.Item> */}
{/* <Form.Item name="placeOfSupply">
<InputField
label="Place of Supply"
onChange={(e) =>
transportFormRef.current?.setFieldsValue(
{ placeOfSupply: e.target.value }
)
}
/>
</Form.Item> */}
<Form.Item name="transporterName">
<InputField
label="Transporter Name"
onChange={(e) =>
transportFormRef.current?.setFieldsValue(
{ transporterName: e.target.value }
)
}
/>
</Form.Item>
<Form.Item name="transporter">
{/* <DropDowns
options={[
{ value: 'transporter1', label: 'Transporter 1' },
{ value: 'transporter2', label: 'Transporter 2' },
]}
label="Transporter"
className="field-DropDown"
onChangeFunction={value => transportFormRef.current?.setFieldsValue({ transporter: value })}
/> */}
<InputField
label="Transporter Id"
onChange={(e) =>
transportFormRef.current?.setFieldsValue(
{ transporter: e.target.value }
)
}
/>
</Form.Item>
</div>
<div
style={{
marginTop: '20px',
display: 'flex',
flexDirection: 'row-reverse',
}}
>
<Buttons
buttonText="SAVE"
color="901D77"
icon={<ArrowRightOutlined />}
handleSubmit={(e) => {
closeDeliveryChallanModel(e);
}}
/>
</div>
</Form>
</div>
}
/>
</div>
</div>
</div>
<div
className="Deliverychallan-table"
style={{
width: '10px',
}}
>
<Form form={form} component={false}>
<Table
bordered
dataSource={TableData}
columns={columns}
rowClassName="editable-row"
onRow={(record, index) => ({
onClick: () => {
edit(record, index);
},
})}
pagination={false}
/>
</Form>
</div>
</div>
</div>
<div className="QuosubmitButton"
style={{ display: 'flex', gap: '2rem', alignItems: 'center' }}>
<Buttons
buttonText="SUBMIT"
color="901D77"
disabled={addnewAccess}
icon={<ArrowRightOutlined />}
htmlType={true}
/>
{isSubmitted && (
<>
<div>
<MdOutlineMail
size={39}
color="#25D366"
style={{ cursor: 'pointer' }}
onClick={handleEmailClick}
title="Share by Email"
/>
</div>
<div>
<FaPrint
size={32}
color="#1292EE"
style={{ cursor: 'pointer' }}
onClick={handlePrint}
title="Print"
/>
</div>
</>
)}
</div>
</Form>
</div>
<DefaultModal
width={400}
open={iSEmail}
title="User Mail"
handleCancel={() => setiSEmail(false)}
footer={false}
children={
<div>
<Form
form={form}
layout="vertical"
onFinish={handleSendEmailWithEnteredEmail}
>
<Form.Item
label="Mail ID"
name="email"
rules={[
{ required: true, message: 'Email is required' },
{ type: 'email', message: 'Enter a valid email address' },
]}
>
<Input placeholder="Enter your email" />
</Form.Item>
<Button type="primary" htmlType="submit">
Submit
</Button>
</Form>
</div>
}
/>
{PrintingData?.length > 0 &&
<div
style={{ display: "none" }}
>
<DeliveryPrint
PrintingData1={[PrintingData]}
DCprinterTemplateStyle={DCPrintTemplateStyle}
DCPrintTemplateDtl={DCPrintTemplateDtl}
/>
</div>
}
</div>
</div>
</div>
);
};
export default DeliveryChellanForm;