Snippets Collections
///PROMISES in JS 
/// PROMISE MEANS A TASKS WILL  COMPLETED BUT  NOT IMMEDIATELY-->
//they're 3 states of the promises PENDING , FULFILLLED , REJECTED -->

import { log } from "console";

// PROMISE CREATION 

/////// 1 WAY 
const promiseOne = new Promise(function(resolve, reject){
    //Do an async task
    // DB calls, cryptography, network
    setTimeout(function(){
        console.log('Async task is compelete');
        resolve() /// this is to connnect the than function 
    }, 1000)
})
promiseOne.then(function(){
    console.log("Promise consumed");
})/// than -> resolve 



/// 2 way 
new Promise(function(resolve, reject){
    setTimeout(function(){
        console.log("Async task 2");
        resolve()
    }, 1000)
}).then(function(){
    console.log("Async 2 resolved");
})


// 3 way 
const promiseThree = new Promise(function(resolve, reject){
    setTimeout(function(){
        resolve({username: "Chai", email: "chai@example.com"})
    }, 1000)
})
promiseThree.then(function(user){
    console.log(user);
})


/// 4 way 
const promiseFour = new Promise(function(resolve, reject){
    setTimeout(function(){
        let error = true
        if (!error) {
            resolve({username: "hitesh", password: "123"})
        } else {
            reject('ERROR: Something went wrong')
        }
    }, 1000)
})

 promiseFour
 .then((user) => {
    console.log(user);
    return user.username
})
.then((username) => {
    console.log(username);
})
.catch(function(error){
    console.log(error);
})
.finally(() => console.log("The promise is either resolved or rejected"))


/// 5 way 
const promiseFive = new Promise(function(resolve, reject){
    setTimeout(function(){
        let error = true
        if (!error) {
            resolve({username: "javascript", password: "123"})
        } else {
            reject('ERROR: JS went wrong')
        }
    }, 1000)
});
async function consumePromiseFive(){ // async will wait untyill the task gets complete 
    try {
        const response = await promiseFive 
        console.log(response);
    } catch (error) {
        console.log(error);
    }
}
consumePromiseFive()
// async function getAllUsers(){
//     try {
//         const response = await fetch('https://jsonplaceholder.typicode.com/users')
//         const data = await response.json()
//         console.log(data);
//     } catch (error) {
//         console.log("E: ", error);
//     }
// }
//getAllUsers()
fetch('https://api.github.com/users/hiteshchoudhary')
.then((response) => {
    return response.json()
})
.then((data) => {
    console.log(data);
})
.catch((error) => console.log(error))


















<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    
</body>
<script>
    const requesturl = 'https://api.guthub.com/users/hiteshchoudhary'
    const  xhr = new XMLDocument();
    xhr.open('GET',requesturl)
    xhr.onreadystatechange = function () {
        console.log(xhr.readyState); // checking the state 
        if(xhr.readyState === 4){
        const data = JSON.parse(this.responseText)  
        console.log(data.followers);
        
        } 
    }
    xhr.send()

</script>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>Chai aur Javascript</h1>
    <button id="start">Start</button>
    <button id="stop">Stop</button>
</body>
<script>
    const sayDate = function(str){
        console.log(str, Date.now()); 
    }

    const intervalId = setInterval(sayDate, 1000, "hi") // it wil print date after 1 sec 

    clearInterval(intervalId) // for stopping the setInterval 
</script>
</html>
function outerFunction(outerVariable) {
  console.log(outerVariable);

  return function innerFunction(innerVariable) {
    console.log(`Outer Variable: ${outerVariable}`);
    console.log(`Inner Variable: ${innerVariable}`);
  };
}

const closureFunc = outerFunction("outside");
closureFunc("inside");
val = isBlank(input.Value);
if(Status == "SO" || Status == "AmendSO")
{
	//openUrl("#Report:Sales_Order_Report","same window");
	openUrl("#Report:Sales_Order_Process","same window");
}
else if(Status == "UNBlOCK")
{
	openUrl("#Page:Planning","same window");
}
else if(Status == "WO")
{
	openUrl("#Page:Planning","same window");
}
hide Status;
hide Value;
hide Rec_ID;
input.plain = "";
if(Status == "DWO")
{
	input.plain = "Work Order Created : <b>" + input.Value + "</b>";
}
if(Status == "MRP_Alert")
{
	input.plain = "<b>" + input.Value + "</b>";
}
if(Status == "DIS")
{
	input.plain = "Dispatch Note Format created <b>" + input.Value + "</b>";
}
if(Status == "ctmcedtc")
{
	input.plain = "Already one revision is waiting for approval for this Part No";
}
if(input.Auto_Approval == "Yes")
{
	input.Approval = "Approved";
	//input.WO_Status = "Open";
	input.WO_Status = "WO Created";
	input.Material_Details.Work_Order_Status = "WO Created";
	if(input.Form_Mode == "Direct WO")
	{
		// 		input.Approval = "Approved";
		// 		input.WO_Status = "WO Created";
		// 		input.Material_Details.Work_Order_Status = "WO Created";
		input.Approval = "Pending";
		input.WO_Status = "Waiting for approval";
		for each  stat in input.Material_Details
		{
			stat.Work_Order_Status="Waiting for approval";
		}
	}
	if(input.Form_Mode == "Draft WO-Regular Wheels")
	{
		input.Approval = "Approved";
		//input.WO_Status = "Open";
		input.WO_Status = "WO Created";
		input.Material_Details.Work_Order_Status = "WO Created";
		//---------After creating WO, status Change in Draft WO-Regular Wheels Form 
		DFWO = Create_WO_for_Regular_Wheels[ID == input.Draft_Work_Order_ID];
		DFWOSUB = DF_Work_Order_Subform[Draft_Work_Order_RecID == DFWO.ID];
		DFWO.WO_Status="WO Created";
		DFWOSUB.Status="Draft WO Created";
		// 		input.Material_Details.Work_Order_Status = "WO Created";
		for each  darftstat in input.Material_Details
		{
			darftstat.Work_Order_Status="WO Created";
		}
	}
	fet_so = Sales_Order[ID == input.Sales_Order_Nos];
	for each  var in input.Material_Details
	{
		sosub = Sale_Order_Subform[ID == var.Sale_Order_Subform_ID];
		wosub = Work_Order_Subform[Sale_Order_Subform_ID == sosub.ID].sum(WO_Qty);
		//----------Block the Qty in Inventory while creating WO-------------
		if(input.Form_Mode == "WO against SO")
		{
			inventory = Inventory[Part_No == sosub.Part_No] sort by Available_Qty desc;
			//------------Changing inventory as Virtual stock ----------------------
			//inventory = Virtual_Stock[Part_No == sosub.Part_No] sort by Available_Qty desc;
			WosubID = Work_Order_Subform[Part_No == var.Part_No];
			// WO_RECID = WosubID.Work_Order_Exis_ID;
			//var.Block_Qty=var.WO_Qty;
			blkqty = if(var.WO_Qty >= var.Stock_Qty,var.Stock_Qty,var.WO_Qty);
			blkqty = if(var.Stock_Qty >= var.SO_Quantity,var.Block_Qty,blkqty);
			var.Block_Qty=blkqty;
			sosub.WO_Blk_Qty=blkqty;
			if(inventory.count() > 0)
			{
				balqty = 0;
				i = 1;
				if(var.Block_Qty != null)
				{
					for each  inven in inventory
					{
						if(blkqty > inven.Available_Qty)
						{
							inven.Block_Qty=ifnull(inven.Available_Qty,0) + ifnull(inven.Block_Qty,0);
							blkqty = blkqty - ifnull(inven.Available_Qty,0);
							inven.Available_Qty=0.00;
							// inventory.Total_Qty = 0.00;
						}
						else if(blkqty <= inven.Available_Qty)
						{
							// inven.Total_Qty = ifnull(inven.Total_Qty,0)  - ifnull(var.Block_Qty ,0);
							inven.Available_Qty=ifnull(inven.Available_Qty,0) - ifnull(blkqty,0);
							inven.Block_Qty=ifnull(blkqty,0) + ifnull(inven.Block_Qty,0);
							blkqty = 0.00;
						}
						//----------New Code checking for block & wo are same eg 50=50 & stock 100 is > 50--------
						// 						else if ( var.WO_Qty == var.Block_Qty && var.Stock_Qty >= var.Block_Qty ) 
						//                         {
						// 						inven.Available_Qty=ifnull(inven.Available_Qty,0) - ifnull(blkqty,0);
						// 							inven.Block_Qty=ifnull(blkqty,0) + ifnull(inven.Block_Qty,0);
						// 							blkqty = 0.00;
						//                         }
						//------------------------------------------------------------------------------
						/* 						if(balqty > 0 && i > 1)
						{
							//info "balance qty is more than zero";
							//Balance Qty is less 
							if(balqty <= inven.Available_Qty)
							{
								//info "balance qty is less than total qty";
								//inven.Total_Qty=ifnull(inven.Total_Qty,0.0) - ifnull(balqty,0.0);
								inven.Available_Qty=ifnull(inven.Available_Qty,0.0) - ifnull(balqty,0.0);
								balqty = 0;
							}
							//----Balance Qty is More------
							else if(balqty >= inven.Available_Qty)
							{
								//info "balance qty is greater than total qty";
								balqty = ifnull(balqty,0.0) - ifnull(inven.Available_Qty,0.0);
								//inven.Total_Qty=0;
								inven.Available_Qty=0;
							}
						} */
						if(blkqty == 0)
						{
							//info "before break";
							break;
						}
						//i = i + 1;
					}
					insblock = insert into Block_Quantity
					[
						Part_No=var.Part_No
						Part_Name=var.Part_Description
						Form_Type=input.Form_Mode
						Block_Qty=var.Block_Qty
						WO_No=input.ID
						WO_RECID=input.ID
						Status="Blocked from WO"
						Added_User=zoho.loginuser
					];
					insblock = insert into FG_Block_Stock1
					[
						Part_No=var.Part_No
						Part_Name=var.Part_Description
						Form_Type=input.Form_Mode
						Block_Qty=var.Block_Qty
						WO_No=input.ID
						WO_RECID=input.ID
						Status="Blocked from WO"
						Added_User=zoho.loginuser
					];
				}
			}
		}
		//______________________________________________________________________________________
		if(sosub.count() > 0 && fet_so.count() > 0)
		{
			/* 			if(sosub.Qty != wosub && input.Form_Mode == "WO against SO")
			{
				sosub.Status="WO Partially Completed";
				input.WO_Status = "WO Partially Completed";
				fet_so.SO_Status="WO Partially Completed";
				fet_so.CWPL_SO_Status="WO Partially Completed";
			} */
			// 			if( input.Form_Mode == "WO against SO")
			// 			{
			// 				sosub.Status="Active";
			// 				//input.WO_Status = "WO Partially Completed";
			// 				fet_so.SO_Status="Open";
			// 				fet_so.CWPL_SO_Status="Active";
			// 			} 
			salsub = Sale_Order_Subform[Sales_Order_Exis_ID == fet_so.ID && ID != var.Sale_Order_Subform_ID && Status == "Active"];
			if(input.Form_Mode == "WO against SO")
			{
				sosub.Status="WO Created";
				input.WO_Status = "WO Created";
				for each  wotstat in input.Material_Details
				{
					wotstat.Work_Order_Status="WO Created";
					//---------If stock > So & Wo is 0 , WO is closed ,then Wo status is WO Closed
					if(wotstat.Stock_Qty >= wotstat.SO_Quantity && wotstat.WO_Qty == 0)
					{
						input.WO_Status = "WO Closed";
						wotstat.Work_Order_Status="WO Closed";
						sosub.Status="WO Closed";
					}
					//------------------------------------------------
				}
				//----------------------------------------------------
				sosub.Work_Order_RECID=input.ID;
				sosub.Work_Order_Subform_ID=WosubID.ID;
				sosub.Wo_Delivery_Date_in_sosub=input.Expected_Delivery_Date;
				sosub.WO_Status_in_sosub=input.WO_Status;
				//------------------------------------------------
				if(salsub.count() == 0)
				{
					fet_so.SO_Status="WO Created";
					fet_so.CWPL_SO_Status="WO Created";
				}
				//fet_so.SO_Status="WO Created";
				//fet_so.CWPL_SO_Status="WO Created";
				/* 				for each  updstatus in Work_Order[Sales_Order_Nos == input.Sales_Order_Nos]
				{
					updstatus.WO_Status="WO Created";
				} */
			}
		}
	}
	//-----------------Direct WO , Block QTY Calculation-----------------
	/* 	for each  var1 in input.Material_Details
	{
		var1.Block_Qty=var1.WO_Qty;
		if(var1.Block_Qty != null)
		{
			wo = Work_Order[ID == input.ID];
			wosub = Work_Order_Subform[Work_Order_Exis_ID = wo.ID];
			if(input.Form_Mode == "Direct WO")
			{
				//info input.Form_Mode;
				//fet_inventory = Inventory[Part_No == var1.Part_No] sort by Available_Qty desc;
				//------------Changing inventory as Virtual stock ----------------------
				fet_inventory = Virtual_Stock[Part_No == var1.Part_No] sort by Available_Qty desc;
				WOSUB = Work_Order_Subform[Part_No == var1.Part_No];
				if(fet_inventory.count() > 0)
				{
					balqty = 0;
					i = 1;
					info fet_inventory.count();
					//info var1.Block_Qty + "block qty";
					for each  inv1 in fet_inventory
					{
						//info "inven for";
						//info var1.WO_Qty ;
						//info inv1.Available_Qty; 
						if(var1.WO_Qty > inv1.Available_Qty)
						{
							//info " WO > INV";
							inv1.Block_Qty=ifnull(inv1.Available_Qty,0);
							inv1.Available_Qty=0.00;
						}
						else if(var1.WO_Qty <= inv1.Available_Qty)
						{
							//info " WO <= INV";
							//avail = ifnull(inv1.Available_Qty,0) - ifnull(var1.Block_Qty,0);
							//info avail;
							inv1.Available_Qty=ifnull(inv1.Available_Qty,0) - ifnull(var1.Block_Qty,0);
							inv1.Block_Qty=ifnull(var1.Block_Qty,0);
						}
						//for first time it should not get inside the loop 
						if(balqty > 0 && i > 1)
						{
							//info "balance qty is more than zero";
							//Balance Qty is less 
							if(balqty <= inv1.Total_Qty)
							{
								//info "balance qty is less than total qty";
								inv1.Total_Qty=ifnull(inv1.Total_Qty,0.0) - ifnull(balqty,0.0);
								inv1.Available_Qty=ifnull(inv1.Available_Qty,0.0) - ifnull(balqty,0.0);
								balqty = 0;
							}
							//----Balance Qty is More------
							else if(balqty >= inv1.Total_Qty)
							{
								//info "balance qty is greater than total qty";
								balqty = ifnull(balqty,0.0) - ifnull(inv1.Total_Qty,0.0);
								inv1.Total_Qty=0;
								inv1.Available_Qty=0;
							}
						}
						if(balqty == 0)
						{
							//info "before break";
							break;
						}
						i = i + 1;
					}
				}
			}
		}
	} */
	//----------Draft WO- Reguakr Wheels Block QTY Calculation------------------
	/* 		for each  var2 in input.Material_Details
		{
			var2.Block_Qty=var2.WO_Qty;
			if(var2.Block_Qty != null)
			{
				DFWO = Create_WO_for_Regular_Wheels[ID == input.Draft_Work_Order_ID];
				DFWOSUB = DF_Work_Order_Subform[Draft_Work_Order_RecID == DFWO.ID];
				if(input.Form_Mode == "Draft WO-Regular Wheels")
				{
					//info input.Form_Mode;
					//get_inventory = Inventory[Part_No == var2.Part_No] sort by Available_Qty desc;
					//------------Changing inventory as Virtual stock ----------------------
					get_inventory = Virtual_Stock[Part_No == var2.Part_No] sort by Available_Qty desc;
					dfsub = DF_Work_Order_Subform[Part_No == var2.Part_No];
					if(get_inventory.count() > 0)
					{
						balqty = 0;
						i = 1;
						//info get_inventory.count();
						//info var2.Block_Qty + "block qty";
						for each  inv in get_inventory
						{
							//info "inven for";
							if(var2.WO_Qty > inv.Available_Qty)
							{
								inv.Block_Qty=ifnull(inv.Available_Qty,0);
								inv.Available_Qty=0.00;
							}
							else if(var2.WO_Qty < inv.Available_Qty)
							{
								inv.Available_Qty=ifnull(inv.Available_Qty,0) - ifnull(var2.Block_Qty,0);
								inv.Block_Qty=ifnull(var2.Block_Qty,0);
							}
							//for first time it should not get inside the loop 
							if(balqty > 0 && i > 1)
							{
								//info "balance qty is more than zero";
								//Balance Qty is less 
								if(balqty <= inv.Total_Qty)
								{
									//info "balance qty is less than total qty";
									inv.Total_Qty=ifnull(inv.Total_Qty,0.0) - ifnull(balqty,0.0);
									inv.Available_Qty=ifnull(inv.Available_Qty,0.0) - ifnull(balqty,0.0);
									balqty = 0;
								}
								//Balance Qty is More
								else if(balqty >= inv.Total_Qty)
								{
									//info "balance qty is greater than total qty";
									balqty = ifnull(balqty,0.0) - ifnull(inv.Total_Qty,0.0);
									inv.Total_Qty=0;
									inv.Available_Qty=0;
								}
							}
							if(balqty == 0)
							{
								//info "before break";
								break;
							}
							i = i + 1;
						}
					}
				}
			}
		} */
	//------------end of If statement-------------
}
else if(input.Auto_Approval == "No")
{
	input.Approval = "Pending";
	input.WO_Status = "Waiting for approval";
	// 	if(input.Form_Mode == "Direct WO")
	// 	{
	// 		input.Approval = "Pending";
	// 		//input.WO_Status = "Waiting for approval";
	// 	}
	fet_so = Sales_Order[ID == input.Sales_Order_Nos];
	for each  var in input.Material_Details
	{
		sosub = Sale_Order_Subform[ID == var.Sale_Order_Subform_ID];
		wosub = Work_Order_Subform[Sale_Order_Subform_ID == sosub.ID].sum(WO_Qty);
		//wo = Work_Order[Sales_Order_Nos == input.Sales_Order_Nos];
		//info "sosub" + sosub.Qty;
		//info "wosub" + wosub;
		if(sosub.count() > 0 && fet_so.count() > 0)
		{
			/* 			if(sosub.Qty != wosub && input.Form_Mode == "WO against SO")
			{
				sosub.Status="WO Partially Completed";
				input.WO_Status = "Waiting for approval";
				fet_so.SO_Status="WO Partially Completed";
				fet_so.CWPL_SO_Status="WO Partially Completed";
			} */
			salsub = Sale_Order_Subform[Sales_Order_Exis_ID == fet_so.ID && ID != var.Sale_Order_Subform_ID && Status == "	Active"];
			if(input.Form_Mode == "WO against SO")
			{
				sosub.Status="WO Created";
				//input.WO_Status = "Waiting for approval";
				if(salsub.count() == 0)
				{
					fet_so.SO_Status="WO Created";
					fet_so.CWPL_SO_Status="WO Created";
				}
				for each  updstatus in Work_Order[Sales_Order_Nos == input.Sales_Order_Nos]
				{
					updstatus.WO_Status="Waiting for approval";
				}
			}
		}
	}
}
var = 0;
if(isBlank(input.Work_Order_No.trim()))
{
	var = 1;
	input.Work_Order_No = thisapp.Common.Number_Function_New("Work Order");
}
if(var == 1 && input.Form_Mode == "WO against SO")
{
	openUrl("#Form:Alert_Messages?Status=" + "WO" + "&Value=" + input.Work_Order_No + "&zc_LoadIn=dialog","same window");
}
else if(input.Form_Mode == "Direct WO")
{
	openUrl("#Form:Alert_Messages?Status=" + "WOAlert" + "&Value=" + input.Work_Order_No + "&zc_LoadIn=dialog","same window");
}
else if(input.Form_Mode == "Draft WO-Regular Wheels")
{
	openUrl("#Form:Alert_Messages?Status=" + "DWO" + "&Value=" + input.Work_Order_No + "&zc_LoadIn=dialog","same window");
}
disable Part_No;
disable Part_Name;
disable WO_Qty;
disable Packing_Std;
hide Packing_Std;
fet_pref = Preferences[Module_Name = "Work Order"];
input.Auto_Approval = fet_pref.Auto_Approval;
input.Virtual_Stock_Enable = fet_pref.Virtual_Stock;
//info input.Form_Mode;
input.Created_By = Employee_Details[Employee_Email == zoho.loginuserid].ID;
if(input.Sale_Order_Subform_ID != null || input.Sale_Order_Subform_ID.size() > 0 || input.Sale_Order_Subform_ID.len() > 0)
{
	// 	fetch_sosub = Sale_Order_Subform[ID == input.Sales_Order_Nos];
	// 	fetch_so = Sales_Order[ID == fetch_sosub.Sales_Order_Exis_ID];
	// 	Sales_Order_Nos = fetch_so.ID;
	// 	info fetch_so;
	sno = 0;
	for each  a1 in input.Sale_Order_Subform_ID
	{
		sosub = Sale_Order_Subform[ID == a1.ID];
		fetch_so = Sales_Order[ID == a1.Sales_Order_Exis_ID];
		inven = Inventory[Part_No == sosub.Part_No].sum(Available_Qty);
		fet_inven = Inventory[Part_No == sosub.Part_No].sum(Total_Qty);
		WO = Work_Order[Draft_Work_Order_ID == input.ID];
		Wosub = Work_Order_Subform[Part_No == a1.Part_No && Work_Order_Status != "WO Closed" && Work_Order_Status != "WO Cancelled" && Work_Order_Status != "Cancelled"].sum(WO_Qty);
		// 		if(a1.WO_Qty > = a1.Stock_Qty) 
		//     {
		// 		alert "Stock is already Available, Check and Proceed";
		//     }
		//----------- fet_mat = MPS_Master [Part_No == row.Part_No];
		//input.Front1 = Materials[ID == sosub.Part_No].Front;
		//input.Regular1 = Materials[ID == sosub.Part_No].Regular;
		//input.CED_Product1 = Materials[ID == sosub.Part_No].CED_Product;
		//input.Batch_Size1 = Materials[ID == sosub.Part_No].Batch_Size;
		row1 = Work_Order.Material_Details();
		row1.Stock_Qty=inven;
		row1.Total_Stock=fet_inven;
		row1.WO_Pipeline=Wosub;
		row1.SO_Quantity=a1.Qty;
		row1.Part_No=a1.Part_No;
		sno = sno + 1;
		row1.S_No=sno;
		row1.Sales_Order_No=fetch_so.ID;
		row1.Part_Description=a1.Part_Description;
		row1.UOM=a1.UoM;
		input.Category = Materials[ID == sosub.Part_No].Category;
		input.Sub_Category = Materials[ID == sosub.Part_No].Sub_Category;
		input.Part_No = a1.Part_No;
		input.Part_Name = a1.Part_Description;
		input.Packing_Std = ifnull(sosub.Packing_Std,null);
		wosub = Work_Order_Subform[Sale_Order_Subform_ID == sosub.ID && Part_No == a1.Part_No].sum(WO_Qty);
		row1.WO_Sofar=wosub;
		woqty = a1.Qty - wosub;
		if(row1.WO_Sofar > 0)
		{
			row1.Balance=woqty;
		}
		else
		{
			row1.Balance=0.00;
		}
		//row1.Balance=ifnull(row1.Quantity,0) - ifnull(row1.WO_Sofar,0) + ifnull(row1.WO_Qty,0);
		//row1.WO_Qty=woqty;
		row1.Buffer_Percentage=0.0;
		//row1.Required_Qty=ifnull(row1.SO_Quantity,0) - ifnull(row1.WO_Pipeline,0) - ifnull(row1.Stock_Qty,0);
		row1.Required_Qty=ifnull(row1.SO_Quantity,0) - ifnull(row1.Stock_Qty,0);
		if(row1.Stock_Qty >= row1.SO_Quantity)
		{
			// info"Stk > so";			
			row1.Block_Qty=ifnull(row1.SO_Quantity,0);
		}
		if(row1.Stock_Qty <= row1.SO_Quantity)
		{
			//info"Stk < so ";
			row1.Block_Qty=ifnull(row1.Stock_Qty,0);
		}
		if(row1.Stock_Qty <= row1.SO_Quantity && row1.Stock_Qty == 0)
		{
			//info"stk < so & stk =0";
			row1.Block_Qty=ifnull(row1.Stock_Qty,0);
		}
		// 		if(row1.Required_Qty > 0 && row1.Stock_Qty != 0)
		// 		{
		// 			info "req is > than 0";
		// 			row1.WO_Qty=row1.Required_Qty;
		// 			row1.Block_Qty=row1.WO_Qty;
		// 		}
		if(row1.Required_Qty < 0)
		{
			//	info "req is 0";
			row1.Required_Qty=0.0;
			row1.WO_Qty=0.0;
			input.WO_Qty = 0.0;
			//row1.Block_Qty=ifnull(row1.SO_Quantity,0) - ifnull(row1.Stock_Qty,0);
		}
		else
		{
			//	info " req > 0";
			//row1.WO_Qty=woqty;
			row1.WO_Qty=row1.Required_Qty;
			input.WO_Qty = row1.Required_Qty;
			//row1.Block_Qty=row1.WO_Qty;
		}
		//if(row1.Required_Qty > 0 && row1.Stock_Qty != 0)
		row1.WO_Qty_with_buffer=(ifnull(row1.WO_Qty,0.0) + ifnull(row1.WO_Qty,0.0) * ifnull(row1.Buffer_Percentage,0.0) / 100).ceil();
		//row1.To_be_Blocked=a1.Blocke_Qty;
		inventory = Inventory[Part_No == sosub.Part_No];
		//row1.Block_Qty=row1.WO_Qty;
		row1.Specification=a1.Remarks_multiline;
		row1.Sale_Order_Subform_ID=sosub.ID;
		row1.Work_Order_Exis_ID=input.ID;
		input.Material_Details.insert(row1);
	}
	if(fetch_so.count() > 0)
	{
		input.Customer_Name = ifnull(fetch_so.Customer_Name,"");
		disable Customer_Name;
		input.Expected_Delivery_Date = ifnull(fetch_so.Expected_Shipment_Date,"");
		/* 		if(fetch_so.Expected_Shipment_Date.getDay() >= 20)
		{
			input.Expected_Delivery_Date = ifnull(fetch_so.Expected_Shipment_Date,"");
		}
		else if(fetch_so.Expected_Shipment_Date.getDay() <= 20)
		{
			input.Expected_Delivery_Date = ifnull(fetch_so.Sale_Order_Date.addDay(20),"");
		}
		//info "salesorder " + fetch_so.Expected_Shipment_Date;
		// 		if(fetch_so.Expected_Shipment_Date >= zoho.currentdate && fetch_so.Expected_Shipment_Date != null)
		// 		{
		//input.Expected_Delivery_Date = ifnull(fetch_so.Expected_Shipment_Date,"");
		//} */
		input.Sales_Order_Nos = fetch_so.ID;
	}
}
//----------------------------------DRAFT WO ---------------------------------------------
//info Draft_Work_Order_ID ;
//info Form_Mode;
if(Draft_Work_Order_ID != null && input.Form_Mode == "Draft WO-Regular Wheels")
{
	//info "IF";
	hide Material_Details.SO_Quantity;
	DFWO = Create_WO_for_Regular_Wheels[ID == input.Draft_Work_Order_ID];
	DFWOSUB = DF_Work_Order_Subform[Draft_Work_Order_RecID == DFWO.ID];
	// 	childwo = Regular_Child_Item_Parts[ID == input.Draft_Work_Order_ID];
	//WO = Work_Order[Draft_Work_Order_ID == input.ID];
	//Wosub = Work_Order_Subform[Work_Order_Exis_ID == WO.ID];
	//inven1 = Inventory[Part_No == DFWOSUB.Part_No].sum(Available_Qty);
	//------------Changing inventory as Virtual stock ----------------------
	inven1 = Inventory[Part_No == DFWOSUB.Part_No].sum(Available_Qty);
	input.Draft_WO_Date = DFWO.Draft_WO_Date;
	input.Draft_Work_Order_ID = DFWO.ID;
	info input.Draft_Work_Order_ID + "after";
	input.Created_By = DFWO.Created_By;
	input.Work_Order_Date = zoho.currentdate;
	input.WO_Status = "Draft WO";
	input.Production_Start_Date = DFWO.Production_Start_Date;
	input.Expected_Delivery_Date = DFWO.Delivery_Date;
	// 	if(DFWO.Delivery_Date != null && DFWO.Delivery_Date >= zoho.currentdate)
	// 	{
	// 		//info "if";
	// 		input.Expected_Delivery_Date = ifnull(DFWO.Delivery_Date,"");
	// 	}
	// 	else
	// 	{
	// 		input.Expected_Delivery_Date = zoho.currentdate;
	// 	}
	input.Production_End_Date = DFWO.Production_End_Date;
	input.Approval = DFWO.Approval;
	input.CED_Product1 = DFWO.Category;
	input.Front1 = DFWO.Front1;
	input.Regular1 = DFWO.Regular1;
	input.Batch_Size1 = DFWO.BATCH_SIZE1;
	input.Category = Materials[ID == DFWOSUB.Part_No].Category;
	input.Sub_Category = Materials[ID == DFWOSUB.Part_No].Sub_Category;
	sno = 0;
	for each  var in DFWO.Material_Details_SF
	{
		//info"FOR";
		WO = Work_Order[Draft_Work_Order_ID == input.ID];
		Wosub = Work_Order_Subform[Part_No == var.Part_No && Work_Order_Status != "WO Closed" && Work_Order_Status != "WO Cancelled" && Work_Order_Status != "Cancelled" && Work_Order_Status != "WO Reverted"].sum(WO_Qty);
		inven2 = Inventory[Part_No == var.Part_No].sum(Available_Qty);
		fet_inv2 = Inventory[Part_No == var.Part_No].sum(Total_Qty);
		reg_master = Regular_Item_Master[Part_No == var.Part_No];
		childwo = Regular_Child_Item_Parts[Part_No == var.Part_No];
		row2 = Work_Order.Material_Details();
		row2.Stock_Qty=inven2;
		row2.Total_Stock=fet_inv2;
		row2.WO_Pipeline=Wosub;
		sno = sno + 1;
		row2.S_No=sno;
		row2.Part_No=var.Part_No;
		row2.Part_Description=var.Part_Description;
		input.Part_No = var.Part_No;
		input.Part_Name = var.Part_Description;
		row2.UOM=var.UOM;
		row2.SO_Quantity=0;
		// 		row2.WO_Qty=var.WO_Qty;
		// 		row2.Block_Qty=row2.WO_Qty;
		row2.Buffer_Percentage=0.0;
		//row2.Required_Qty=ifnull(row2.SO_Quantity,0) - ifnull(row2.WO_Pipeline,0) - ifnull(row2.Stock_Qty,0);
		row2.Required_Qty=ifnull(row2.SO_Quantity,0) - ifnull(row2.Stock_Qty,0);
		if(row2.Required_Qty < 0)
		{
			row2.Required_Qty=0.0;
			row2.WO_Qty=0.0;
			input.WO_Qty = 0.0;
		}
		else
		{
			//row2.WO_Qty=var.WO_Qty;
			row2.WO_Qty=row2.Required_Qty;
			input.WO_Qty = row2.Required_Qty;
			//row2.Block_Qty=row2.WO_Qty;
		}
		row2.WO_Qty_with_buffer=(ifnull(row2.WO_Qty,0.0) + ifnull(row2.WO_Qty,0.0) * ifnull(row2.Buffer_Percentage,0.0) / 100).ceil();
		// 		inv_subform = Invoice_Subform[Part_No == var.Part_No && Added_Time >= "01-Jan-2023" && Added_Time <= "31-Dec-2023"].sum(Qty);
		//row2.Six_Month_Sale = ifnull(thisapp.Invoice.Calculation_last_6_months_invoiceQty(row2.Part_No)," ");
		//_________Calculating Six month sales Qty in invoice________________
		//info curdate;
		//curdate = "17-Jan-2024";
		curdate = zoho.currentdate;
		startmonth = curdate.eomonth(-6);
		//info startmonth;
		startdate = startmonth.toStartOfMonth();
		curstartdate = curdate.toStartOfMonth();
		enddate = curstartdate.subday(1);
		startdate = startdate + " 00:00:00";
		enddate = enddate + " 23:59:59";
		//info "startdate " + startdate;
		//info "enddate " + enddate;
		inv_qty = Invoice_Subform[Part_No == row2.Part_No && Added_Time >= startdate && Added_Time <= enddate].sum(Qty);
		//info inv_qty;
		average_sale = ifnull(inv_qty / 6,0.00);
		row2.Six_Month_Sale=average_sale;
		//___________________________________________________________
		row2.Min_Stock=reg_master.Min_Stock;
		row2.Batch_Size=reg_master.Batch_Size;
		row2.Specification=var.Specification;
		input.Six_Month_Avg_Sale = average_sale;
		// 		input.Minimum_Stock = reg_master.Min_Stock;
		// 				input.Batch_Size = reg_master.Batch_Size;
		if(reg_master.Min_Stock != null)
		{
			//info "reg";
			input.Minimum_Stock = reg_master.Min_Stock;
			input.Batch_Size = reg_master.Batch_Size;
		}
		else
		{
			//info"else";
			//info childwo.Minimum_Qty +"m";
			//info childwo.Batch_Size +"b";
			input.Minimum_Stock = childwo.Minimum_Qty;
			input.Batch_Size = childwo.Batch_Size;
		}
		input.Material_Details.insert(row2);
	}
	//--------------------------------------
	disable Six_Month_Avg_Sale;
	disable Minimum_Stock;
	disable Batch_Size;
	hide Material_Details.Six_Month_Sale;
	hide Material_Details.Batch_Size;
	hide Material_Details.Min_Stock;
	hide Draft_WO_Date;
	disable Material_Details.Min_Stock;
	disable Material_Details.Six_Month_Sale;
	disable Material_Details.Batch_Size;
	disable Schedule_WO;
	hide Sales_Order_Nos;
	hide Customer_Name;
	hide Material_Details.WO_Sofar;
	hide Material_Details.Balance;
	hide Material_Details.Buffer_Percentage;
	hide Material_Details.WO_Qty_with_buffer;
	//hide Material_Details.SO_Quantity;
	disable Material_Details.WO_Pipeline;
	disable Material_Details.Stock_Qty;
	//-------------------
	disable Created_By;
	disable Sales_Order_Nos;
	disable Customer_Name;
	disable Expected_Delivery_Date;
	disable Warehouse;
	hide Material_Details.To_be_Blocked;
	disable Material_Details.S_No;
	hide Material_Details.MRP_ID;
	disable Material_Details.WO_Qty_with_buffer;
	disable Material_Details.To_be_Blocked;
	disable Material_Details.Part_Description;
	disable Material_Details.Part_No;
	disable Material_Details.SO_Quantity;
	disable Material_Details.Buffer_Percentage;
	disable Material_Details.WO_Sofar;
	disable Material_Details.Balance;
	disable Material_Details.UOM;
	disable Material_Details.Required_Qty;
	hide WO_Status;
	hide Approval;
	hide Approval;
	//hide Status;
	hide Schedule_WO;
	hide Production_Start_Date;
	hide Production_End_Date;
	hide Delivery_Address;
	hide Sale_Order_Subform_ID;
	hide Material_Details.Stock_FG_Qty;
	hide Material_Details.Stock_SFG_Qty;
	hide Material_Details.MRP_Qty;
	hide Material_Details.To_be_Blocked;
	hide Material_Details.Work_Order_Status;
	hide Material_Details.Scheduled_so_far;
	hide Material_Details.Sale_Order_Subform_ID;
	hide Material_Details.Balance_Qty;
	hide Form_Mode;
	hide Draft_Work_Order_ID;
	disable Front1;
	disable Regular1;
	//disable Batch_Size1;
	disable CED_Product1;
	disable Material_Details.S_No;
	disable Material_Details.Block_Qty;
	disable Category;
	disable Sub_Category;
	hide Category;
	hide Sub_Category;
	hide Material_Details.Block_Qty;
}
//-------------------------------------------
// 		if(row1.Stock_Qty > row1.SO_Quantity && row1.Stock_Qty > row1.WO_Pipeline)
// 		{
// 			reqqty = ifnull(row1.Stock_Qty,0) - ifnull(row1.WO_Pipeline,0) - ifnull(row1.SO_Quantity,0);
// 			info reqqty + " Stock > So & Stock > wopipe";
// 			row1.Required_Qty=reqqty;
// 		}
// 		else if(row1.SO_Quantity > row1.WO_Pipeline && row1.SO_Quantity > row1.Stock_Qty)
// 		{
// 			reqqty2 = ifnull(a1.Qty,0) - ifnull(Wosub,0) - ifnull(inven,0);
// 			info reqqty2 + " So > wopipe & So > stock";
// 			row1.Required_Qty=reqqty2;
// 		}
// 		else if(row1.WO_Pipeline > row1.SO_Quantity && row1.WO_Pipeline > row1.Stock_Qty)
// 		{
// 			reqqty3 = ifnull(Wosub,0) - ifnull(a1.Qty,0) - ifnull(inven,0);
// 			info reqqty3 + " wopipe > So & wopipe > stock";
// 			row1.Required_Qty=reqqty3;
// 		}
// 		else if(row1.WO_Pipeline > row1.WO_Qty || row1.WO_Pipeline > row1.Stock_Qty)
// 		{
// 			reqqty4 = ifnull(row1.WO_Pipeline,0) - ifnull(row1.WO_Qty,0) - ifnull(row1.Stock_Qty,0);
// 			info reqqty4 + " Wopipe > Wo (Or) wopipe > stock";
// 			row1.Required_Qty=reqqty4;
// 		}
// 		else if(row1.WO_Qty > row1.WO_Pipeline && row1.WO_Pipeline > row1.Stock_Qty)
// 		{
// 			reqqty5 = ifnull(row1.WO_Qty,0) - ifnull(row1.WO_Pipeline,0) - ifnull(row1.Stock_Qty,0);
// 			info reqqty5 + "  Wo > wopipe > stock";
// 			row1.Required_Qty=reqqty5;
// 		}
// ----- To Remove the Negative values in Requires Qty -----
// 		reqqty = ifnull(a1.Qty,0) - ifnull(Wosub,0) - ifnull(inven,0);
// 		Req = reqqty.toString();
// 		if(Req.contains("-"))
// 		{
// 			row1.Required_Qty=Req.removeFirstOccurence("-").toLong();
// 		}
// 		else
// 		{
// 			row1.Required_Qty=reqqty;
// 		}
//-------------------------------------
//input.Approval = "Pending";
// Nisha.s -- I have commented the below code up to line no 251& used this on blueprint
qty = ifnull(input.Moved_Qty,0.0) + ifnull(input.Moved_Qty_So_Far,0.0);
if(input.Accepted_Quantity > input.Moved_Qty)
{
	input.Balance_Qty_to_Move = ifnull(input.Accepted_Quantity,0.0) - qty;
	input.Moved_Qty_So_Far = ifnull(input.Moved_Qty_So_Far,0.0) + ifnull(input.Moved_Qty,0.0);
}
mts_status = Income_Quality_Check_Process[ID == input.Income_Quality_Check_RECID];
//Coil Id based Stock Maintenace  - User Requirement - 10/02/2023
getmat = Materials[ID == input.Part_No];
getcatg = Category[ID == getmat.Category];
if(getcatg.Category != "HR Coils")
{
	stock = Inventory[Part_No == input.Part_No && Part_Description == input.Part_Description && Warehouse == input.Warehouse && Location_Name == input.Location_Name && Sub_Location == input.Sub_Location && Rack_Number == input.Rack_Number];
}
else
{
	stock = Inventory[Part_No == input.Part_No && Part_Description == input.Part_Description && HR_Coil_id == input.HR_Coil_id && Warehouse == input.Warehouse && Location_Name == input.Location_Name && Sub_Location == input.Sub_Location && Rack_Number == input.Rack_Number];
}
category = Materials[ID == input.Part_Description].Category;
sub_category = Materials[ID == input.Part_Description].Sub_Category;
fet_reg = Regular_Item_Master[Part_No == input.Part_No];
fet_child = Regular_Child_Item_Parts[Part_No == input.Part_No];
if(stock.count() == 0)
{
	insert into Inventory
	[
		Added_User=zoho.loginuser
		Stock_Update_ID=input.ID
		Part_No=input.Part_No
		Part_Description=input.Part_Description
		Specification=input.Specification
		Total_Qty=input.Moved_Qty
		Batch_Number=input.Batch_Number
		Location_Name=input.Location_Name
		Sub_Location=input.Sub_Location
		Rack_Number=input.Rack_Number
		Available_Qty=input.Moved_Qty
		Warehouse=input.Warehouse
		Block_Qty=0.00
		Category=category
		Sub_Category=sub_category
		HR_Coil_id=input.HR_Coil_id
		UOM=input.Unit_of_Measurement
	]
	//Total_Qty=mts_status.Received_Qty
	if(Form_Mode == "Move to Stock")
	{
		if(input.Accepted_Quantity == qty)
		{
			mts_status.Move_to_Stock_status="Moved";
			mts_status.IQC_Status="Stock Updated";
		}
		else if(input.Accepted_Quantity > qty)
		{
			mts_status.Move_to_Stock_status="Partially Moved";
			mts_status.IQC_Status="Stock Partially Updated";
		}
	}
}
else
{
	//dont update the stock again.ie.Move to stock done-vendor inspection done - move to stock cases.
	// 	if(mts_status.IQC_Status != "Stock Update Pending" && Form_Mode == "Move to Stock")
	// 	{
	// 		//stock.Total_Qty=ifnull(stock.Total_Qty,0.00) + mts_status.Received_Qty;
	// 	}
	stock.Available_Qty=ifnull(stock.Available_Qty,0.0) + ifnull(input.Moved_Qty,0.0);
	stock.Total_Qty=ifnull(stock.Total_Qty,0.00) + ifnull(input.Moved_Qty,0.0);
	//stock.Total_Qty=ifnull(stock.Block_Qty,0.0) + ifnull(stock.Available_Qty,0.0);
	//fet_reg.Today_inventory = ifnull(stock.Available_Qty,0.0) + ifnull(input.Moved_Qty,0.0);
	if(Form_Mode == "Move to Stock")
	{
		if(input.Accepted_Quantity == qty)
		{
			mts_status.Move_to_Stock_status="Moved";
			mts_status.IQC_Status="Stock Updated";
		}
		else if(input.Accepted_Quantity > qty)
		{
			mts_status.Move_to_Stock_status="Partially Moved";
			mts_status.IQC_Status="Stock Partially Updated";
		}
	}
}
//rejected qty become accepted qty by manangement spl approval.
if(Form_Mode = "Rejectitem movetostock")
{
	//stock.Total_Qty=ifnull(stock.Total_Qty,0.00) + mts_status.Received_Qty;
	stock.Total_Qty=ifnull(stock.Total_Qty,0.00) + ifnull(input.Moved_Qty,0.0);
	mts_status.Rejected_Qty=ifnull(input.Accepted_Quantity,0.0) - ifnull(mts_status.Rejected_Qty,0.0);
	mts_status.Accepted_Qty=ifnull(mts_status.Accepted_Qty,0.0) + input.Accepted_Quantity;
}
if(input.Purchase_Order_No != null)
{
	fet_posf = Purchase_Order_Subform[Purchase_Order_ExisID == input.Purchase_Order_No && Part_No == input.Part_No && ID == input.Purchase_Order_Subform_RECID];
	fet_bat_no = GRN_Subform[Purchase_Order_SubForm_RECID == fet_posf.ID && Batch_Number == input.Batch_Number];
	fet_stockvalue = Stock_Value[Part_No == input.Part_No && Unit_Price == fet_posf.Rate];
	if(fet_stockvalue.count() > 0)
	{
		stockvalue = Stock_Value[Part_No == input.Part_No && Unit_Price == fet_posf.Rate];
		// 		stockvalue.Stock_Qty=stockvalue.Stock_Qty + ifnull(input.Accepted_Quantity,0.00);
		// 		a = ifnull(fet_posf.Rate,0.00) * ifnull(input.Accepted_Quantity,0.00);
		stockvalue.Purchase_Order_No=input.Purchase_Order_No;
		stockvalue.Stock_Qty=ifnull(stockvalue.Stock_Qty,0.0) + ifnull(input.Moved_Qty,0.00);
		a = ifnull(fet_posf.Rate,0.00) * ifnull(input.Moved_Qty,0.00);
		stockvalue.Stock_Value=ifnull(stockvalue.Stock_Value,0.0) + ifnull(a,0.0);
		stockvalue.Inventory_Qty=ifnull(stockvalue.Stock_Qty,0.0);
	}
	else
	{
		insert into Stock_Value
		[
			Added_User=zoho.loginuser
			Purchase_Order_No=input.Purchase_Order_No
			Batch_Number=fet_bat_no.ID
			Part_No=input.Part_No
			Part_Description=input.Part_Description
			Specification=input.Specification
			Location_Name=input.Location_Name
			Sub_Location=input.Sub_Location
			Rack_Number=input.Rack_Number
			Warehouse=input.Warehouse
			Stock_Qty=ifnull(input.Moved_Qty,0.00)
			Unit_Price=ifnull(fet_posf.Rate,0.00)
			Stock_Value=ifnull(fet_posf.Rate,0.00) * ifnull(input.Moved_Qty,0.00)
			Stock_Update=input.ID
			Inventory_Qty=ifnull(input.Moved_Qty,0.0)
		]
	}
}
//-----------------Update po status------------------------
if(input.Purchase_Order_No != null)
{
	//fetch_po_sub = Purchase_Order_Subform[Purchase_Order_ExisID == input.Purchase_Order_No && Part_No == input.Part_No].sum(Ordered_Qty);
	fetch_po_sub = Purchase_Order_Subform[Purchase_Order_ExisID == input.Purchase_Order_No && Part_No == input.Part_No && ID == input.Purchase_Order_Subform_RECID].sum(Ordered_Qty);
	get_grn_qty = GRN_Subform[Purchase_Order_Number == input.Purchase_Order_No && Part_No == input.Part_No].sum(Received_Qty);
	fet_po_sub = Purchase_Order_Subform[Purchase_Order_ExisID == input.Purchase_Order_No && Part_No == input.Part_No && ID == input.Purchase_Order_Subform_RECID];
	get_IQC = Income_Quality_Check_Process[Purchase_Order_No == input.Purchase_Order_No && IQC_No != "" && Part_No == fet_po_sub.Part_No && GRN_Subform_RECID == input.GRN_Subform_RECID].sum(Accepted_Qty);
	//PO Final Close
	get_po_id = Purchase_Order[ID == input.Purchase_Order_No && Purchase_Order_No != ""];
	// 	sendmail
	// 	[
	// 		from :"erp@carrierwheels.com"
	// 		to :"parthasarathy.m@synprosoft.com"
	// 		subject :"stock update created succussful form sub - afert line 128 if condition-slno1" + input.Part_No.Part_No
	// 		message :"fetchposubqty " + fetch_po_sub + " getiqcqty " + get_IQC + "posfstts " + input.Part_No.Part_No
	// 	]
	if(get_po_id.count() > 0)
	{
		check_po_status = 0;
		for each  po_sub_form in Purchase_Order_Subform[Purchase_Order_ExisID == get_po_id.ID && Part_No == input.Part_No && ID == input.Purchase_Order_Subform_RECID]
		{
			// 			sendmail
			// 			[
			// 				from :"erp@carrierwheels.com"
			// 				to :"parthasarathy.m@synprosoft.com"
			// 				subject :"stock update created succussful form sub - after line 147 for loop po status before slno2" + po_sub_form.ID
			// 				message :po_sub_form.PO_Status + "---" + po_sub_form.ID
			// 			]
			if(po_sub_form.PO_Status != "QC Completed")
			{
				check_po_status = 1;
			}
		}
		// 		sendmail
		// 		[
		// 			from :"erp@carrierwheels.com"
		// 			to :"parthasarathy.m@synprosoft.com"
		// 			subject :"stock update created succussful form sub - after check po status slno3 " + input.Purchase_Order_Subform_RECID
		// 			message :"check_po_status " + check_po_status + "---" + input.Purchase_Order_Subform_RECID
		// 		]
		if(check_po_status == 0)
		{
			//the below line is comment on 27/11/2023 due to main po status is updating po closed,still items are not stock updated fully.
			//get_po_id.PO_Status="PO Closed";
			//get_po_id.PO_Status="QC Partially Completed";
		}
		else
		{
			get_po_id.PO_Status="QC Partially Completed";
		}
	}
	//if po quantity is greater than or equal to the total accepted qty in the IQC, it means the po order is closed
	if(fet_po_sub.count() > 0)
	{
		//Stock Update id for PO History Report in PO subform
		fet_po_sub.Stock_Update_ID=input.ID;
		if(get_IQC >= fetch_po_sub)
		{
			// 		fet_po_sub.PO_Status="QC Completed";--ERP Issue & Queries No.122 dt 10/04/2023.
			fet_po_sub.PO_Status="PO Closed";
		}
		//additional check for Po sf status 
		if(fet_po_sub.Qty_Received_so_far == fet_po_sub.Ordered_Qty)
		{
			fet_po_sub.PO_Status="PO Closed";
		}
	}
	//if purchase order subform status is PO closed for all items,then close the Purchase main form status as PO Closed - 10/10/2023
	posfcount = Purchase_Order_Subform[Purchase_Order_ExisID == get_po_id.ID].count();
	///info posfcount;
	poclosestts = Purchase_Order_Subform[Purchase_Order_ExisID == get_po_id.ID && PO_Status == "PO Closed"].count();
	//info poclosestts;
	posffc = Purchase_Order_Subform[Purchase_Order_ExisID == get_po_id.ID && PO_Status == "Foreclosed"].count();
	//info posffc;
	if(posfcount == poclosestts)
	{
		updtpomain = Purchase_Order[ID == get_po_id.ID];
		if(updtpomain.count() > 0)
		{
			updtpomain.PO_Status="PO Closed";
		}
	}
	else if(poclosestts >= posffc && posfcount == ifnull(posffc,0.0) + ifnull(poclosestts,0.0))
	{
		updtpomain = Purchase_Order[ID == get_po_id.ID];
		if(updtpomain.count() > 0)
		{
			updtpomain.PO_Status="PO Closed";
		}
	}
	//for checking purpose - posf is not closed by po main is closed
	if(posfcount != poclosestts)
	{
		checkpo = Purchase_Order[ID == get_po_id.ID];
		if(checkpo.count() > 0 && checkpo.PO_Status == "PO Closed")
		{
			// 			sendmail
			// 			[
			// 				from :"erp@carrierwheels.com"
			// 				to :"parthasarathy.m@synprosoft.com"
			// 				subject :"ALERT PO SUBFORM ITEMS STILL PENDING AND MAIN PO ISs CLOSED slno-4" + get_po_id
			// 				message :checkpo.Purchase_Order_No + "- " + get_po_id
			// 			]
		}
	}
}
//Insert records in Inventory Ageing form
insert into Inventory_Ageing
[
	Added_User=zoho.loginuser
	Part_No=input.Part_No
	Part_Description=input.Part_Description
	Specification=input.Specification
	Added_Stock=input.Moved_Qty
	Stock_Added_Issued_Date=zoho.currentdate
	Expiry_Date=input.Expiry_Date
]
//Insert record in Stock Ledger for Report purpose
fet_iqc1 = Income_Quality_Check_Process[ID == input.Income_Quality_Check_RECID];
GRNsubformID = GRN_Subform[ID == fet_iqc1.GRN_Subform_ID];
fetch_grn1 = GRN[ID == GRNsubformID.GRN_ID];
Vend_name = Vendor[ID = fetch_grn1.Vendor_Name].Vendor_Name;
//the below function will insert the record in stock ledger
thisapp.Stock_Ledger.Quantity_in_for_Stock_Ledger(input.ID);
//Update the Stock in ZOHO CRM --> Products--> Quantity in Stock Field- as per Mr.Senthil Advice the below fucntion is not required.19/05/2023
//thisapp.Update_Stock_in_CRM(input.Part_No);
//------
//_________Updating Moved Qty value & subform calculation to create Bills__________Nisha___________________________
get_bill = Create_Bills[GRN_No == input.GRN_Recid];
fet_Hold = Accept_Quantity[IQC_RECID == input.ID];
if(get_bill.count() > 0 && fet_Hold.Hold_Flag != "Hold Flag")
{
	updbills = Create_Bills_Subform[Exists_ID == get_bill.ID && Part_No == input.Part_No && GRN_Subform_ID == input.GRN_Subform_RECID];
	if(updbills.count() > 0)
	{
		get_data = Stock_Update[ID == input.ID];
		updbills.Qty=ifnull(get_data.Moved_Qty,0);
		updbills.Subtotal=ifnull(updbills.Qty,0) * ifnull(updbills.Rate,0);
		get_po = Purchase_Order_Subform[ID == updbills.Purchase_Order_Subform_ID];
		tot = updbills.Subtotal + get_po.Tax_Value;
		//info get_po.Tax_Value;
		//info get_po.Tax;
		subtot = Ifnull(get_po.Rate,0.0) * ifnull(get_data.Moved_Qty,0.0);
		get_tax_value = GST_Details[ID == get_po.Tax].Total_Rate;
		tax_calc = ifnull(subtot,0.00) * ifnull(get_tax_value,0.00) / 100;
		Total = ifnull(get_data.Moved_Qty,0.00) * ifnull(get_po.Rate,0.00) + ifnull(tax_calc,0.00);
		updbills.Tax=ifnull(get_po.Tax,null);
		updbills.Tax_Value=ifnull(tax_calc,0.00);
		//updbills.Tax_Value=ifnull(subtot,0.00) * ifnull(get_tax_value,0.00) / 100;
		updbills.Total=ifnull(Total,0.00);
	}
	itemtot = 0;
	taxtot = 0;
	Grndtot = 0;
	dftbill = True;
	for each  item in Create_Bills_Subform[Exists_ID == get_bill.ID]
	{
		itemtot = itemtot + ifNull(item.Subtotal,0);
		taxtot = taxtot + ifNull(item.Tax_Value,0);
		Grndtot = Grndtot + ifNull(item.Total,0);
		if(item.Qty == null)
		{
			dftbill = False;
		}
		// 		else if (item.Qty == null && fet_iqc1.Rejected_Qty  > 0 && fet_iqc1.Accepted_Qty == 0 ) 
		//         {
		// 			dftbill = True;
		//         }
	}
	get_bill.Item_Total=itemtot;
	get_bill.Tax_Total=taxtot;
	get_bill.Grand_Total=Grndtot;
	get_bill.Create_Draft_Bill=dftbill;
	if(fetch_grn1.count() > 0)
	{
		fetch_grn1.Create_Draft_Bill=dftbill;
	}
	// 	get_bill.Item_Total=ifnull(updbills.Subtotal,0.00);
	// 	get_bill.Tax_Total=ifnull(updbills.Total,0.00);
	// get_bill.Grand_Total =ifnull(updbills.Subtotal,0.00)+ifnull(updbills.Total,0.00);
}
//-----------------If Accepted > 0 & hold > 0 ,calculation for Moved Qty--------------------
// if(get_bill.count() > 0 && fet_iqc1.Hold_Qty > 0 && fet_iqc1.Accepted_Qty > 0  && fet_iqc1.IQC_Status =="IQC Completed" && fet_iqc1.Hold_Flag = "Bill Generated by Hold Qty")
// if(get_bill.count() > 0 && fet_iqc1.Hold_Qty > 0 && fet_iqc1.Accepted_Qty > 0  && fet_iqc1.Hold_Flag = "Bill Generated by Hold Qty")
// {
// 	updbills1 = Create_Bills_Subform[Exists_ID == get_bill.ID && Part_No == input.Part_No && GRN_Subform_ID == input.GRN_Subform_RECID];
// 	if(updbills1.count() > 0 &&  fet_iqc1.Hold_Qty > 0)
// 	{
// 		get_data = Stock_Update[ID == input.ID];
// 		movqty = get_data.Moved_Qty + fet_iqc1.Hold_Qty ;
// 		updbills1.Qty=movqty;
// 		updbills1.Subtotal=ifnull(updbills1.Qty,0) * ifnull(updbills1.Rate,0);
// 		get_po = Purchase_Order_Subform[ID == updbills1.Purchase_Order_Subform_ID];
// 		tot = updbills1.Subtotal + get_po.Tax_Value;
// 		info get_po.Tax_Value;
// 		info get_po.Tax;
// 		subtot = Ifnull(get_po.Rate,0.0) * ifnull(movqty,0.0);
// 		get_tax_value = GST_Details[ID == get_po.Tax].Total_Rate;
// 		tax_calc = ifnull(subtot,0.00) * ifnull(get_tax_value,0.00) / 100;
// 		Total = ifnull(movqty,0.00) * ifnull(get_po.Rate,0.00) + ifnull(tax_calc,0.00);
// 		updbills1.Tax=ifnull(get_po.Tax,null);
// 		updbills1.Tax_Value=ifnull(tax_calc,0.00);
// 	    //updbills1.Tax_Value=ifnull(subtot,0.00) * ifnull(get_tax_value,0.00) / 100;
// 		updbills1.Total=ifnull(Total,0.00);
// 	}
// 	itemtot = 0;
// 	taxtot = 0;
// 	Grndtot = 0;
// 	dftbill = True;
// 	for each  item1 in Create_Bills_Subform[Exists_ID == get_bill.ID]
// 	{
// 		itemtot = itemtot + ifNull(item1.Subtotal,0);
// 		taxtot = taxtot + ifNull(item1.Tax_Value,0);
// 		Grndtot = Grndtot + ifNull(item1.Total,0);
// 		if(item1.Qty == null)
// 		{
// 			dftbill = False;
// 		}
// 	}
// 	get_bill.Item_Total=itemtot;
// 	get_bill.Tax_Total=taxtot;
// 	get_bill.Grand_Total=Grndtot;
// 	get_bill.Create_Draft_Bill=dftbill;
// 	fetch_grn1.Create_Draft_Bill=dftbill;
// }
//______________________________________________________________________________________________________________
// if (zoho.loginuserid =="admin@carrierwheels.com") 
// {
//--------Run DRaft Wo function-----------------------
fet_reg = Regular_Item_Master[Part_No == input.Part_No];
if(fet_reg.count() > 0)
{
	thisapp.workorder.Draft_WO();
	//------------Daily Total Inventory Update by Schedule in Regular Item Master------
	thisapp.workorder.RegularItem_Master_Total_Qty_DailyUpdate();
}
reg_child = Regular_Child_Item_Parts[Part_No == input.Part_No];
if(reg_child.count() > 0)
{
	thisapp.workorder.Draft_WO_Child_Parts();
}
//_____________Deleting the records in Create WO for Regular wheels( if Stock > MIn stock in comparing Reg item Master )
//thisapp.Delete_DraftWO_When_Stock_Increases();
//}
//__________________________________________________________________________________________________________________
val = input.Part_No.Part_No + " - " + input.Moved_Qty;
if(Form_Mode == "Move to Stock")
{
	openUrl("#Form:Alert_Messages?Status=StockUpdate&Value=" + val + "&zc_LoadIn=dialog","same window");
}
if(Form_Mode == "Rejectitem movetostock")
{
	openUrl("#Form:Alert_Messages?Status=RejMovetoStock&Value=" + val + "&zc_LoadIn=dialog","same window");
}
Example code

import smtplib
from email.mime.text import MIMEText

# SMTP configuration
smtp_host = 'smtp.mailgun.org'
smtp_port = 587
username = 'postmaster@YOUR_DOMAIN_NAME'
password = 'YOUR_API_KEY'

# Create the message
msg = MIMEText("This is a test email.")
msg['Subject'] = "Test Email"
msg['From'] = "noreply@yourdomain.com"
msg['To'] = "recipient@example.com"

# Connect and send the email
try:
    with smtplib.SMTP(smtp_host, smtp_port) as server:
        server.starttls()  # Secure the connection
        server.login(username, password)
        server.send_message(msg)
        print("Email sent successfully!")
except Exception as e:
    print(f"Error sending email: {e}")









Based on the code, here's the current working mail configuration:

In mail_config.py:
SMTP Server: smtp.mailgun.org
Port: 587
TLS: Enabled
Authentication: Using username/password
Required Environment Variables (set these in Replit Secrets):
MAILGUN_SMTP_USERNAME
MAILGUN_SMTP_PASSWORD
MAIL_DEFAULT_SENDER
The configuration initializes mail with:
app.config.update(
    MAIL_SERVER='smtp.mailgun.org',
    MAIL_PORT=587,
    MAIL_USE_TLS=True,
    MAIL_USERNAME=smtp_username,
    MAIL_PASSWORD=smtp_password,
    MAIL_DEFAULT_SENDER=sender
)
Sends emails using direct SMTP with starttls() for security
The key changes that made it work were:

Using port 587 instead of 465
Enabling TLS instead of SSL
Using direct SMTP connection with proper starttls() initialization
Proper error handling and logging
Keep these settings in your Replit Secrets for future implementations.





MAIL_DEFAULT_SENDER
••••••••
MAILGUN_DOMAIN
••••••••
MAILGUN_SMTP_PASSWORD
••••••••
MAILGUN_SMTP_USERNAME
••••••••
MAILGUN_API_KEY
••••••••
var = 0;
if(isBlank(input.Stock_Adjustment_No.trim()))
{
	var = 1;
	str = thisapp.Common.Number_Function_New("Stock Adjustment");
	input.Stock_Adjustment_No = str;
	openUrl("#Form:Alert_Messages?Status=" + "Adjusted" + "&Value=" + input.Stock_Adjustment_No + "&zc_LoadIn=dialog","same window");
}
for each  rec in input.Item_Details
{
	fet_inven = Inventory[Part_No == rec.Part_No && Location_Name == rec.Location_Name && Sub_Location == rec.Sub_Location && Rack_Number == rec.Rack_Number];
	getuom = Materials[ID == rec.Part_No].Primary_UoM;
	//if(fet_inven.Part_No == rec.Part_No)
	if(fet_inven.count() > 0)
	{
		// 		for each  fet in Inventory[Part_No == rec.Part_No]
		// 		{
		// 			if(fet.Part_Description == rec.Part_Name && fet.Location_Name == rec.Location_Name && fet.Sub_Location == rec.Sub_Location && fet.Rack_Number == rec.Rack_Number)
		//{
		fet_inven.Total_Qty=rec.New_Quantity_in_Hand;
		fet_inven.Available_Qty=rec.New_Quantity_in_Hand;
		//}
	}
	//}
	else
	{
		insert into Inventory
		[
			Added_User=zoho.loginuser
			Part_No=rec.Part_No
			Part_Description=rec.Part_Name
			Specification=rec.Specification
			Total_Qty=rec.New_Quantity_in_Hand
			Location_Name=rec.Location_Name
			Sub_Location=rec.Sub_Location
			Rack_Number=rec.Rack_Number
			Available_Qty=rec.New_Quantity_in_Hand
			Warehouse=input.Warehouse
			UOM=getuom
		]
	}
	thisapp.Stock_Ledger.Stock_Adj_Stockledger(input.ID);
}
//update the qty in Stock value also
for each  stkvalrec in input.Item_Details
{
	fetstkvalue = Stock_Value[Part_No == stkvalrec.Part_No && Stock_Qty > 0] sort by Added_Time desc;
	if(fetstkvalue.count() > 0)
	{
		fetstkvalue.Stock_Qty=stkvalrec.New_Quantity_in_Hand;
		fetstkvalue.Inventory_Qty=stkvalrec.New_Quantity_in_Hand;
		sendmail
		[
			from :"erp@carrierwheels.com"
			to :"parthasarathy.m@synprosoft.com"
			subject :"Stock Adjustment Created or Edited Successeful form submission " + stkvalrec.Part_No.Part_No + "adjqty " + stkvalrec.New_Quantity_in_Hand
			message :"Stock Adjustment Created or Edited Successeful form submission " + stkvalrec.Part_No.Part_No + "adjqty " + stkvalrec.New_Quantity_in_Hand
		]
	}
}
var = 0;
if(isBlank(input.Stock_Transfer_NO.trim()))
{
	var = 1;
	str = thisapp.Common.Number_Function_New("Stock Transfer");
	input.Stock_Transfer_NO = str;
	openUrl("#Form:Alert_Messages?Status=" + "Stktrf" + "&Value=" + input.Stock_Transfer_NO + "&zc_LoadIn=dialog","same window");
}
if(Transfer_Type == "Location Based")
{
	if(input.Source_Rack_Bins != input.Destination_Rack_Bins)
	{
		for each  rec in input.Stock_Details
		{
			des = Inventory[Warehouse == input.Destination_Warehouse && Location_Name == input.Destination_Location && Sub_Location == input.Destination_Sub_Location && Rack_Number == input.Destination_Rack_Bins && Part_No == rec.Part_No];
			src = Inventory[Warehouse == input.Source_Warehouse && Location_Name == input.Source_Location && Sub_Location == input.Source_Sub_Location && Rack_Number == input.Source_Rack_Bins && Part_No == rec.Part_No];
			getuom = Materials[ID == rec.Part_No].Primary_UoM;
			if(des.count() == 1)
			{
				//update
				des.Available_Qty=des.Available_Qty + rec.Transfer_Qty;
				des.Total_Qty=des.Total_Qty + rec.Transfer_Qty;
				src.Available_Qty=src.Available_Qty - rec.Transfer_Qty;
				src.Total_Qty=src.Total_Qty - rec.Transfer_Qty;
			}
			else
			{
				//insert
				insert into Inventory
				[
					Added_User=zoho.loginuser
					Warehouse=input.Destination_Warehouse
					Part_No=rec.Part_No
					Part_Description=rec.Part_Description
					Specification=rec.Specification
					Category=rec.Category
					Sub_Category=rec.Sub_Category
					Total_Qty=rec.Transfer_Qty
					Available_Qty=rec.Transfer_Qty
					Location_Name=input.Destination_Location
					Sub_Location=input.Destination_Sub_Location
					Rack_Number=input.Destination_Rack_Bins
					UOM=getuom
				]
				src.Available_Qty=src.Available_Qty - rec.Transfer_Qty;
				src.Total_Qty=src.Total_Qty - rec.Transfer_Qty;
			}
		}
	}
}
if(Transfer_Type == "Part Based")
{
	for each  sub in input.Stock_Details
	{
		source = Inventory[Part_No == input.Stock_Details.Source_Part_No] sort by Available_Qty desc;
		destination = Inventory[Part_No == input.Stock_Details.Destination_Part_No] sort by Available_Qty desc;
		getuom = Materials[ID == sub.Destination_Part_No].Primary_UoM;
		if(destination.count() == 1)
		{
			destination.Available_Qty=destination.Available_Qty + sub.Transfer_Qty;
			destination.Total_Qty=destination.Total_Qty + sub.Transfer_Qty;
			source.Available_Qty=source.Available_Qty - sub.Transfer_Qty;
			source.Total_Qty=source.Total_Qty - sub.Transfer_Qty;
		}
		else
		{
			insert into Inventory
			[
				Added_User=zoho.loginuser
				Warehouse=sub.Destination_Warehouse
				Part_No=sub.Destination_Part_No
				Part_Description=sub.Destination_Part_Name
				Specification=sub.Specification
				Category=sub.Source_Category
				Sub_Category=sub.Source_Sub_Category
				Total_Qty=sub.Transfer_Qty
				Available_Qty=sub.Transfer_Qty
				Location_Name=sub.Destination_Location
				Sub_Location=sub.Destination_Sub_Location
				Warehouse=sub.Destination_Warehouse
				UOM=getuom
			]
			source.Available_Qty=source.Available_Qty - sub.Transfer_Qty;
			source.Total_Qty=source.Total_Qty - sub.Transfer_Qty;
		}
	}
}
// if(isBlank(input.Transfer_Order_No.trim()))
// {
// 	//lastrec = Stock_Transfer[ID != null && ID != input.ID] sort by ID desc;
// 	//info lastrec.ID + "ORDER" + lastrec.Transfer_Order_No;
// 	lastrec = Stock_Transfer[Transfer_Order_No != null && Transfer_Order_No != ""] sort by Transfer_Order_No desc;
// 	if(lastrec.Transfer_Order_No == null || lastrec.Transfer_Order_No == "")
// 	{
// 		nextid = 1;
// 		//info "yes";
// 	}
// 	else
// 	{
// 		nextid = lastrec.Transfer_Order_No.getSuffix("-").getsuffix("/").toLong() + 1;
// 	}
// }
// input.Transfer_Order_No = "TQ/ST/" + thisapp.financial_year() + "/" + leftpad(nextid.toString(),5).replaceAll(" ","0");
// openUrl("#Form:Alert_Messages?Status=" + "Stktrf" + "&Value=" + input.Transfer_Order_No + "&zc_LoadIn=dialog","same window");
var = 0;
if(isBlank(input.Revert_No.trim()))
{
	var = 1;
	str = thisapp.Common.Number_Function_New("Revert MRP");
	input.Revert_No = str;
}
fet_mrp = MRP[Work_Order_No1 == input.Work_Order_No];
fetwo = Work_Order[Work_Order_No == input.Work_Order_No.Work_Order_No];
fetwosf = Work_Order_Subform[Work_Order_Exis_ID == fetwo.ID];
sosub = Sale_Order_Subform[Sales_Order_Exis_ID.Sale_Order_No == fetwo.Sales_Order_Nos.Sale_Order_No];
DFWOSUB = DF_Work_Order_Subform[Part_No == fetwosf.Part_No];
DFWO = Create_WO_for_Regular_Wheels[ID == DFWOSUB.Draft_Work_Order_RecID];
if(input.Work_Order_Subform_ID != null)
{
	input.Status = "WO Reverted";
	fetwo.WO_Status="WO Reverted";
	fetwosf.Work_Order_Status="WO Reverted";
	if(fetwo.Form_Mode == "Draft WO-Regular Wheels")
	{
		if(DFWO.count() > 0)
		{
			DFWO.WO_Status="Draft WO";
			DFWOSUB.Status="";
		}
		thisapp.workorder.RegularItem_Master_Total_Qty_DailyUpdate();
		thisapp.workorder.Draft_WO();
	}
	if(fetwo.Form_Mode == "WO against SO")
	{
		sosub.WO_Status_in_sosub="Pending WO";
		for each  wosub in fetwosf
		{
			get_inv = Inventory[Part_No == wosub.Part_No] sort by Block_Qty desc;
			if(get_inv.count() > 0)
			{
				/* 		get_inv.Available_Qty=ifnull(get_inv.Available_Qty,0.00) + ifnull(get_inv.Block_Qty,0.00);
		//get_inv.Block_Qty=0.00;
		get_inv.Block_Qty=ifnull(get_inv.Block_Qty,0.00) - ifnull(wosub.Block_Qty,0.00); */
				blkqty = wosub.Block_Qty;
				for each  inven in get_inv
				{
					if(blkqty > inven.Block_Qty)
					{
						inven.Available_Qty=ifnull(inven.Available_Qty,0) + ifnull(inven.Block_Qty,0);
						blkqty = blkqty - ifnull(inven.Block_Qty,0);
						inven.Block_Qty=0.00;
						// inventory.Total_Qty = 0.00;
					}
					else if(blkqty <= inven.Block_Qty)
					{
						// inven.Total_Qty = ifnull(inven.Total_Qty,0)  - ifnull(var.Block_Qty ,0);
						inven.Available_Qty=ifnull(inven.Available_Qty,0) + ifnull(blkqty,0);
						inven.Block_Qty=ifnull(inven.Block_Qty,0) - ifnull(blkqty,0);
						blkqty = 0.00;
					}
					if(blkqty == 0)
					{
						break;
					}
				}
			}
		}
	}
}
if(fet_mrp.MRP_Status == "MRP Done" || fet_mrp.MRP_Status = "Release Production")
{
	//fet_mrp.MRP_Status="MRP Reverted";
	input.Status = "MRP Reverted";
	fet_mrp.MRP_Status="MRP Reverted";
	fetwo.WO_Status="MRP Reverted";
	fetwosf.Work_Order_Status="MRP Reverted";
	//fetwosf.Work_Order_Status="MRP Reverted";
	for each  blk in fet_mrp.BoM_Details_CWPL
	{
		fet_inv = Inventory[Part_No == blk.Part_No && Block_Qty > 0];
		if(fet_inv.count() > 0)
		{
			if(blk.Block_Qty = True)
			{
				balqty = 0;
				i = 1;
				for each  invcwplrec in fet_inv
				{
					//blocked Quantiy is less inventory available qty
					if(blk.Blocked_Qty <= invcwplrec.Block_Qty && i == 1)
					{
						//info "issued qty is less than total qty";
						invcwplrec.Available_Qty=ifnull(invcwplrec.Available_Qty,0.0) + ifnull(blk.Blocked_Qty,0.0);
						invcwplrec.Block_Qty=ifnull(invcwplrec.Block_Qty,0) - ifnull(blk.Blocked_Qty,0);
					}
					//blocked Quantiy is more than inventory available qty
					else if(blk.Blocked_Qty > invcwplrec.Block_Qty && i == 1)
					{
						//info "issued qty is more than total qty";
						balqty = ifnull(blk.Blocked_Qty,0.0) - ifnull(invcwplrec.Block_Qty,0.0);
						invcwplrec.Available_Qty=balqty;
						invcwplrec.Block_Qty=ifnull(invcwplrec.Block_Qty,0) - ifnull(blk.Blocked_Qty,0);
					}
					//for first time it should not get inside the loop 
					if(balqty > 0 && i > 1)
					{
						//info "balance qty is more than zero";
						//Balance Qty is less 
						if(balqty <= invcwplrec.Block_Qty)
						{
							//info "balance qty is less than total qty";
							invcwplrec.Available_Qty=ifnull(invcwplrec.Available_Qty,0.0) + ifnull(balqty,0.0);
							invcwplrec.Block_Qty=ifnull(blk.Blocked_Qty,0) - ifnull(invcwplrec.Block_Qty,0);
							balqty = 0;
						}
						//----Balance Qty is More------
						else if(balqty >= invcwplrec.Block_Qty)
						{
							//info "balance qty is greater than total qty";
							balqty = ifnull(balqty,0.0) - ifnull(invcwplrec.Block_Qty,0.0);
							invcwplrec.Available_Qty=ifnull(balqty,0);
							invcwplrec.Block_Qty=ifnull(balqty,0) - ifnull(invcwplrec.Block_Qty,0);
						}
					}
					if(balqty == 0)
					{
						break;
					}
					i = i + 1;
				}
			}
		}
	}
	for each  blk1 in fet_mrp.BoM_Details_General_Purchase
	{
		fet_virstk = Inventory[Part_No == blk1.Part_No && Block_Qty > 0];
		if(fet_virstk.count() > 0)
		{
			if(blk1.Block_Qty = True)
			{
				balqty = 0;
				i1 = 1;
				for each  invgprec in fet_virstk
				{
					if(blk1.Blocked_Qty <= invgprec.Block_Qty && i1 == 1)
					{
						//info "blocked qty is less than total qty";
						invgprec.Block_Qty=ifnull(invgprec.Block_Qty,0) - ifnull(blk1.Blocked_Qty,0);
						invgprec.Available_Qty=ifnull(invgprec.Available_Qty,0) + ifnull(blk1.Blocked_Qty,0);
					}
					else if(blk1.Blocked_Qty > invgprec.Block_Qty && i == 1)
					{
						//info "blocked qty is more than available qty";
						balqty = ifnull(blk1.Blocked_Qty,0.0) - ifnull(invgprec.Block_Qty,0.0);
						invgprec.Available_Qty=balqty;
						invgprec.Block_Qty=ifnull(invgprec.Block_Qty,0) - ifnull(blk1.Blocked_Qty,0);
					}
					if(balqty > 0 && i > 1)
					{
						//info "balaance qty is more than zero";
						//Balance Qty is less 
						if(balqty <= invgprec.Block_Qty)
						{
							//	info "balance qty is less than available qty";
							invgprec.Available_Qty=ifnull(invgprec.Available_Qty,0.0) + ifnull(balqty,0.0);
							invgprec.Block_Qty=ifnull(invgprec.Block_Qty,0) - ifnull(blk1.Blocked_Qty,0);
							balqty = 0;
						}
						//Balance Qty is More
						else if(balqty >= invgprec.Block_Qty)
						{
							//info "balance qty is greater than available qty";
							balqty = ifnull(balqty,0.0) - ifnull(invgprec.Block_Qty,0.0);
							invgprec.Available_Qty=balqty;
							invgprec.Block_Qty=ifnull(invgprec.Block_Qty,0) - ifnull(blk1.Blocked_Qty,0);
						}
					}
					if(balqty == 0)
					{
						break;
					}
					i = i + 1;
				}
			}
		}
	}
}
//openUrl("#Script:page.refresh","same window");
openUrl("##Report:MRP_Reverse","same window");
if(var == 1 && input.Form_Mode == "Front")
{
	openUrl("#Form:Alert_Messages?Status=" + "RMRP" + "&Value=" + input.Revert_No + "&zc_LoadIn=dialog","same window");
}
else if(input.Form_Mode == "Rear")
{
	openUrl("#Form:Alert_Messages?Status=" + "REVMRP" + "&Value=" + input.Revert_No + "&zc_LoadIn=dialog","same window");
}
else if(input.Form_Mode == "ReverseWO")
{
	openUrl("#Form:Alert_Messages?Status=" + "MRPRev" + "&Value=" + input.Revert_No + "&zc_LoadIn=dialog","same window");
}
if(input.MRP_RECID != null)
{
	get_mrp = MRP[ID == input.MRP_RECID];
	//info get_mrp + "mrp";
	fet_cwpl = MRP_Subform_CWPL[MRP_Biderection_ID == get_mrp.ID];
	fet_gp = MRP_Subform_GP[MRP_Biderection_ID == get_mrp.ID];
	input.Revert_By = Employee_Details[Employee_Email == zoho.loginuserid].ID;
	input.Revert_Date = zoho.currentdate;
	input.Work_Order_No = get_mrp.Work_Order_No1;
	input.Sales_Order_No = get_mrp.Sales_Order_No;
	input.Part_No = get_mrp.Part_No;
	input.Part_Name = get_mrp.Part_Name;
	input.MRP_Qty = get_mrp.MRP_Qty;
	input.Factory_Warehouse = get_mrp.Factory_Warehouse;
	input.Created_By = get_mrp.Created_By.ID;
	input.Customer_Name = get_mrp.Customer_Name;
	input.Specification = get_mrp.Specification;
	hide WO_Qty;
}
i = 0;
//info "outside for";
//info fet_cwpl + "subform";
for each  mrpcwpl in fet_cwpl
{
	//info "1st for";
	i = i + 1;
	getrow = Revert_Process1.Revert_MRP_Subform_CWPL();
	getrow.S_No=i;
	getrow.Part_No=mrpcwpl.Part_No;
	getrow.Part_Name=mrpcwpl.Part_Name;
	getrow.UoM=mrpcwpl.UoM;
	getrow.BoM_Qty=mrpcwpl.BoM_Qty_Old;
	getrow.Stock_Qty=mrpcwpl.Stock_Qty;
	getrow.Req_Qty=mrpcwpl.Req_Qty;
	getrow.Plan_Qty=mrpcwpl.Actual_Qty;
	getrow.Blocked_Qty=mrpcwpl.Blocked_Qty;
	getrow.Block_Qty=mrpcwpl.Block_Qty;
	getrow.bom_stk_qty=mrpcwpl.bom_stk_qty;
	cwplCol = Collection();
	cwplCol.insert(getrow);
	input.Revert_MRP_Subform_CWPL.insert(cwplCol);
}
j = 0;
for each  gp in fet_gp
{
	j = j + 1;
	genral = Revert_Process1.Revert_MRP_Subform_GP();
	genral.S_No=j;
	genral.Part_No=gp.Part_No;
	genral.Part_Name=gp.Part_Name;
	genral.UoM=gp.UoM;
	genral.Purchase_Qty=gp.Purchase_Qty;
	genral.Stock_Qty=gp.Stock_Qty;
	genral.Indent_Qty=gp.Indent_Qty;
	genral.BoM_Qty=gp.BoM_Qty;
	genral.Req_Qty=gp.Plan_Qty;
	genral.Blocked_Qty=gp.Blocked_Qty;
	genral.Block_Qty=gp.Block_Qty;
	gencol = Collection();
	gencol.insert(genral);
	input.Revert_MRP_Subform_GP.insert(gencol);
}
if(input.Work_Order_Subform_ID != null)
{
	fet_wosub = Work_Order_Subform[ID == input.Work_Order_Subform_ID];
	get_wo = Work_Order[ID == fet_wosub.Work_Order_Exis_ID];
	input.Create_Work_Order_ID = get_wo.ID;
	input.WO_Qty = fet_wosub.WO_Qty;
	input.Revert_By = Employee_Details[Employee_Email == zoho.loginuserid].ID;
	input.Revert_Date = zoho.currentdate;
	input.Work_Order_No = get_wo.ID;
	input.Sales_Order_No = get_wo.Sales_Order_Nos;
	input.Part_No = fet_wosub.Part_No;
	input.Part_Name = fet_wosub.Part_Description;
	input.Customer_Name = get_wo.Customer_Name;
	input.Specification = fet_wosub.Specification;
	hide MRP_Qty;
	hide Factory_Warehouse;
	hide Specification;
	hide Created_By;
	disable WO_Qty;
}
wosno = 0;
for each  wosf in fet_wosub
{
	wosno = wosno + 1;
	inswo = Revert_Process1.Revert_WO_Subform();
	inswo.S_No=wosno;
	inswo.Part_No=wosf.Part_No;
	inswo.Part_Description=wosf.Part_Description;
	inswo.UOM=wosf.UOM;
	inswo.SO_Quantity=wosf.SO_Quantity;
	inswo.Stock_Qty=wosf.Stock_Qty;
	inswo.WO_Pipeline=wosf.WO_Pipeline;
	inswo.Required_Qty=wosf.Required_Qty;
	inswo.WO_Qty=wosf.WO_Qty;
	inswo.Block_Qty=wosf.Block_Qty;
	inswo.Balance_Qty=wosf.Balance_Qty;
	inswo.WO_Qty_with_buffer=wosf.WO_Qty_with_buffer;
	inswo.Specification=wosf.Specification;
	wocol = Collection();
	wocol.insert(inswo);
	input.Revert_WO_Subform.insert(wocol);
}
if(row.Part_Description != null)
{
	match_data = Materials[ID == row.Part_Description && Status == "Active"];
	row.Rate=ifnull(match_data.Purchase_Price,0.0);
	row.Part_No=match_data.ID;
	row.Mfr_Part_No=ifnull(match_data.ID,"");
	row.Specification=match_data.Specification;
	row.Brand=match_data.Brand_Name;
	row.Ordered_Qty=ifnull(match_data.MOQ,0);
	row.UoM=row.Part_Description.Primary_UoM;
	//checking with vendor location with Uttar Pradesh 
	if(input.Vendor_Name.Place_of_Supply.Destination != "Uttar Pradesh")
	{
		row.Tax=Materials[ID == row.Part_Description].IGST_Details;
	}
	else
	{
		row.Tax=Materials[ID == row.Part_Description].GST_Details;
	}
	row.Available_Qty=ifnull(Inventory[Part_Description == row.Part_Description].sum(Available_Qty),0.0);
	row.MOQ_Qty=ifnull(Materials[ID == row.Part_Description].MOQ,0.0);
	//load the rate,moq from the vendor pricing master if available
	getvendcust = Vendor_Contract[Vendor_Name == input.Vendor_Name && Status == "Active"];
	if(getvendcust.count() > 0)
	{
		ven_pricing = Vendor_Contract_Subform[Vendor_Name == input.Vendor_Name && Part_Description == row.Part_Description && Effective_From <= zoho.currentdate && Effective_To >= zoho.currentdate && sf_Status == "Active"];
		//info ven_pricing.count();
		if(ven_pricing.count(ID) == 1)
		{
			row.Rate=null;
			row.MOQ_Qty=null;
			row.Ordered_Qty=null;
			row.Rate=ifnull(ven_pricing.Unit_Price,0.0);
			row.MOQ_Qty=ifnull(ven_pricing.MOQ,0.0);
			row.Ordered_Qty=ifnull(ven_pricing.MOQ,0.0);
			if(row.Rate != ven_pricing.Unit_Price)
			{
				row.Vendor_contract_Price_check=false;
			}
			else
			{
				row.Vendor_contract_Price_check=true;
			}
		}
	}
	row.Sub_Total=row.Ordered_Qty * row.Rate;
}
else
{
	row.Part_No=null;
	row.Available_Qty=null;
	row.Ordered_Qty=null;
	row.Specification=null;
	row.MOQ_Qty=null;
}
//For testing Purpose only Part number created for testing should be selected.
if(input.Vendor_Name != null)
{
	if(Vendor_Name.Vendor_Name.startsWithIgnoreCase("Test") == True)
	{
		if(row.Part_Description != null)
		{
			if(row.Part_Description.Part_Description.startsWithIgnoreCase("Test") == false)
			{
				alert "Use Test Part No for Testing";
				row.Part_No=null;
				row.Part_Description=null;
			}
		}
	}
}
if(row.Part_No != null)
{
	match_data = Materials[ID == row.Part_No && Status == "Active"];
	row.Part_Description=match_data.ID;
	row.Specification=match_data.Specification;
	row.Ordered_Qty=ifnull(match_data.MOQ,0);
	row.UoM=row.Part_Description.Primary_UoM;
	row.Mfr_Part_No=match_data.ID;
	row.Brand=match_data.Brand_Name;
	if(input.Source_of_Supply.Short_Name == "Out of Scope")
	{
		clear row.Tax;
		row.Tax=GST_Details[Tax_Name == "Out of Scope"].ID;
	}
	else
	{
		if(input.Source_of_Supply.Short_Name != "UP")
		{
			fet_igst = GST_Details[Tax_Name.contains("IGST")].ID.getAll();
			clear row.Tax;
			row.Tax:ui.add(fet_igst);
			row.Tax=Materials[ID == row.Part_No].IGST_Details;
		}
		else
		{
			fet_igst = GST_Details[Tax_Name.contains("GST") && !Tax_Name.startswith("I")].ID.getAll();
			clear row.Tax;
			row.Tax:ui.add(fet_igst);
			row.Tax=Materials[ID == row.Part_No].GST_Details;
		}
	}
	row.Available_Qty=ifnull(Inventory[Part_No == row.Part_No].sum(Available_Qty),0.0);
	//Unit price and MOq should be come from vendor pricing if vendor record is available in vendor pricing form.
	ven_pricing = Vendor_Contract_Subform[Vendor_Name == input.Vendor_Name && Part_Description == row.Part_Description && Effective_From <= zoho.currentdate && Effective_To >= zoho.currentdate && sf_Status == "Active"];
	//info ven_pricing.ID;
	//info ven_pricing.count(ID);
	if(ven_pricing.count(ID) == 1)
	{
		row.Ordered_Qty=ifnull(ven_pricing.MOQ,0.0);
		row.Rate=ifnull(ven_pricing.Unit_Price,0.0);
		row.MOQ_Qty=ifnull(ven_pricing.MOQ,0.0);
	}
	check_ven_map = 0;
	check_ven_lis = List();
	if(input.Vendor_Name != null)
	{
		chkvendavl = Vendor_Contract[Vendor_Name == input.Vendor_Name && Status == "Active"];
		if(chkvendavl.count() > 0)
		{
			for each  sub_val in input.Item_Details
			{
				check_vendor = Vendor_Contract_Subform[Vendor_Name == input.Vendor_Name && Part_Description == sub_val.Part_Description && Effective_From <= zoho.currentdate && Effective_To >= zoho.currentdate && sf_Status == "Active"];
				if(check_vendor.count() == 0)
				{
					check_ven_lis.add(sub_val.Part_No.Part_No);
					check_ven_map = 1;
				}
				if(check_vendor.count() > 0)
				{
					sub_val.Rate=ifnull(check_vendor.Unit_Price,0.0);
					sub_val.Vendor_contract_Price_check=true;
					sub_val.MOQ_Qty=ifnull(check_vendor.MOQ,0.0);
					if(row.Rate != check_vendor.Unit_Price)
					{
						row.Vendor_contract_Price_check=false;
					}
					else
					{
						row.Vendor_contract_Price_check=true;
					}
				}
				// 				sendmail
				// 				[
				// 					from :"CWPL ERP<erp@carrierwheels.com>"
				// 					to :"parthasarathy.m@synprosoft.com"
				// 					subject :"Vendor Contract - itemdetils partno validation " + row.Vendor_contract_Price_check
				// 					message :"Vendor Contract - itemdetils partno validation " + input.Vendor_Name.Vendor_Name
				// 				]
			}
		}
		if(check_ven_map == 1)
		{
			show asso_vendors;
			Flag_for_Not_Associated_Vendors = true;
			create_tab = "<table border=1 Style ='color:#ff8b3b'><tr><th>S.No</th><th>Part No</th><th>Associated Vendor(s)</th></tr>";
			sno = 1;
			for each  tab in check_ven_lis
			{
				ven_lis = List();
				for each  ven in Vendor_Contract_Subform[Vendor_Name == input.Vendor_Name && Part_Description == sub_val.Part_Description && Effective_From <= zoho.currentdate && Effective_To >= zoho.currentdate && sf_Status == "Active"]
				{
					if(ven.Vendor_Name.Status == "Active")
					{
						ven_lis.add(ven.Vendor_Name.Vendor_Name);
					}
				}
				create_tab = create_tab + "<tr><td>" + sno + "</td><td>" + tab + "</td><td>" + if(ven_lis.size() == 0,"<b>Not Associated</b>",ven_lis) + "</td></tr>";
				sno = sno + 1;
			}
			create_tab = create_tab + "</table>";
			str = "Selected Vendor <b>" + input.Vendor_Name.Vendor_Name + "</b> is not mapped against the following Item(s) : <br><br>  " + create_tab;
			input.asso_vendors = str;
			Do_you_want_to_proceed_anyway = "";
		}
		else
		{
			hide asso_vendors;
		}
	}
}
else
{
	row.Part_Description=null;
	row.Available_Qty=null;
	row.MOQ_Qty=null;
	row.Ordered_Qty=null;
	row.Specification=null;
	hide asso_vendors;
}
//for vendor gst treatment type is Registered Business - composition then GST is null - Parthasarathy - 09/06/2023
getvend = Vendor[ID == input.Vendor_Name];
getgsttreat = GST_Treatment[ID == getvend.GST_Treatment];
if(getgsttreat.GST_Treatment == "Registered Business - Composition")
{
	row.Tax=null;
	row.Tax_Value=null;
}
//if rate is updated in materials the calculate automatically - 19/12/2022
if(row.Ordered_Qty != null && row.Rate != null && row.Tax != null)
{
	get_tax_value = GST_Details[ID == row.Tax].Total_Rate;
	tax_calc = row.Ordered_Qty * row.Rate * get_tax_value / 100;
	row.Sub_Total=row.Ordered_Qty * row.Rate;
	row.Tax_Value=tax_calc;
	row.Item_Total=row.Sub_Total + tax_calc;
	tot = 0.0;
	subtot = 0.0;
	for each  rec in Item_Details
	{
		tot = tot + ifnull(rec.Item_Total,0.0);
		subtot = subtot + ifnull(rec.Sub_Total,0.0);
	}
	input.Item_Total = tot;
	input.Gross_Total = ifnull(subtot,0.0);
	//17082022input.Total = tot + ifnull(input.Extra_Charge_s_Total,0.0);
	input.Overall_Total = tot + ifnull(input.Extra_Charge_s_Total,0.0);
}
else
{
	row.Sub_Total=ifnull(row.Ordered_Qty,0) * ifnull(row.Rate,0) + ifnull(row.Tax_Value,0.0);
	row.Item_Total=ifnull(row.Sub_Total,0.0) + ifnull(row.Tax_Value,0.0);
	tot1 = 0.0;
	subtot1 = 0.0;
	for each  rec in Item_Details
	{
		tot1 = tot1 + ifnull(rec.Item_Total,0);
		subtot1 = subtot1 + ifnull(rec.Sub_Total,0.0);
	}
	//17082022input.Total = ifnull(input.Extra_Charge_s_Total,0.0) + tot1;
	input.Gross_Total = ifnull(subtot1,0.0);
	input.Overall_Total = ifnull(input.Extra_Charge_s_Total,0.0) + tot1;
	input.Item_Total = tot1;
}
//For testing Purpose only Part number created for testing should be selected.
if(input.Vendor_Name != null)
{
	if(Vendor_Name.Vendor_Name.startsWithIgnoreCase("Test") == True)
	{
		if(row.Part_No != null)
		{
			if(row.Part_No.Part_No.startsWithIgnoreCase("Test") == false)
			{
				alert "Use Test Part No for Testing";
				row.Part_No=null;
				row.Part_Description=null;
			}
		}
	}
}
aa = 0;
gt = 0;
it = 0;
for each  vv in input.Item_Details
{
	if(vv == row)
	{
		continue;
	}
	else
	{
		aa = aa + 1;
		vv.S_No=aa;
		gt = gt + ifnull(vv.Sub_Total,0);
		it = it + ifnull(vv.Item_Total,0);
	}
}
input.Gross_Total = gt;
input.Overall_Total = it;
for each  recval in input.Delivery_Schedule
{
	if(recval.Part_No == row.Part_Description)
	{
		recval.Part_No=null;
		recval.Quantity=null;
		recval.Delivery_Date=null;
	}
}
itemlist = List();
qtyList = List();
dateList = List();
remarksList = List();
fullQtyList = List();
for each  rec in input.Delivery_Schedule
{
	if(rec.Part_No != null)
	{
		itemlist.add(rec.Part_No);
		qtyList.add(rec.Quantity);
		dateList.add(rec.Delivery_Date);
		remarksList.add(rec.Remarks);
		fullQtyList.add(rec.Full_Quantity);
	}
}
input.Delivery_Schedule.clear();
i = 0;
s_no = 0;
for each  items in itemlist
{
	s_no = s_no + 1;
	row1 = Purchase_Order.Delivery_Schedule();
	row1.Part_No=items;
	row1.S_No=s_no;
	row1.Quantity=qtyList.get(i);
	row1.Delivery_Date=dateList.get(i);
	row1.Remarks=remarksList.get(i);
	row1.Full_Quantity=fullQtyList.get(i);
	input.Delivery_Schedule.insert(row1);
	i = i + 1;
}
/// 
check_ven_map = 0;
check_ven_lis = List();
for each  sub_val in input.Item_Details
{
	if(sub_val.Part_No != row.Part_No)
	{
		check_vendor = Vendor_Contract_Subform[Vendor_Name == input.Vendor_Name && Part_Description == sub_val.Part_Description && Effective_From <= zoho.currentdate && Effective_To >= zoho.currentdate && sf_Status == "Active"];
		if(check_vendor.count() == 0)
		{
			check_ven_lis.add(sub_val.Part_No.Part_No);
			check_ven_map = 1;
		}
	}
}
if(check_ven_map == 1)
{
	show asso_vendors;
	create_tab = "<table border=1 Style ='color:#ff8b3b'><tr><th>S.No</th><th>Part No</th><th>Associated Vendor(s)</th></tr>";
	sno = 1;
	for each  tab in check_ven_lis
	{
		ven_lis = List();
		for each  ven in Vendor_Contract_Subform[Part_Description.Part_No == tab && Effective_From <= zoho.currentdate && Effective_To >= zoho.currentdate && sf_Status == "Active"]
		{
			if(ven.Vendor_Name.Status == "Active")
			{
				ven_lis.add(ven.Vendor_Name.Vendor_Name);
			}
		}
		create_tab = create_tab + "<tr><td>" + sno + "</td><td>" + tab + "</td><td>" + if(ven_lis.size() == 0,"<b>Not Associated</b>",ven_lis) + "</td></tr>";
		sno = sno + 1;
	}
	create_tab = create_tab + "</table>";
	str = "Selected Vendor <b>" + input.Vendor_Name.Vendor_Name + "</b> is not mapped against the following Item(s) : <br><br>  " + create_tab;
	input.asso_vendors = str;
	Do_you_want_to_proceed_anyway = "";
	Flag_for_Not_Associated_Vendors = true;
}
else
{
	hide asso_vendors;
	Flag_for_Not_Associated_Vendors = false;
}
if(Item_Details == null)
{
	alert "First Add Data in Item Details";
}
i = 0;
for each  rec_sn in input.Delivery_Schedule
{
	i = i + 1;
	row.S_No=i;
}
//----------------------------------test code for same part number with different spec
item_list1 = List();
deliv_list1 = List();
finalist = List();
item_list = List();
spec_list = List();
for each  an_item in input.Item_Details
{
	if(an_item.Part_No != null)
	{
		item_list1.add(ifnull(an_item.Part_Description.concat("-"),"").concat(ifnull(an_item.Specification,"")));
		spec_list.add(an_item.Specification);
	}
	else
	{
		alert "First Add Data in Item Details";
	}
}
for each  deliv in input.Delivery_Schedule
{
	if(deliv.Part_No != null && deliv.Full_Quantity == true)
	{
		deliv_list1.add(deliv.Part_No.concat("-").concat(ifnull(deliv.Specification,"")));
	}
}
item_list1.removeAll(deliv_list1);
for each  itemlistrec in item_list1
{
	//finalist.add(itemlistrec.getprefix("-"));
	item_list.add(itemlistrec.getprefix("-"));
}
//----------------------------------------test code end here-----------------------------------------------------
//For Delivery Schedule
clear row.Part_No;
/*item_list = List();
deliv_list = List();
for each  an_item in input.Item_Details
{
	item_list.add(an_item.Part_Description);
}
for each  deliv in input.Delivery_Schedule
{
	if(deliv.Part_No != null && deliv.Full_Quantity == true)
	{
		deliv_list.add(deliv.Part_No);
	}
}
item_list.removeAll(deliv_list);*/
row.Part_No:ui.add(item_list.sort(true));
if(item_list.size() > 0)
{
	row.Part_No=item_list.get(0);
	//Setting Quantity
	for each  itemdetrec in input.Item_Details
	{
		if(itemdetrec.Ordered_Qty < 1)
		{
			alert "Please enter quantity for all the item(s) in Item Details Subform";
			row.Quantity=null;
		}
		else
		{
			dsqtytot = 0;
			for each  delschrec in input.Delivery_Schedule
			{
				if(itemdetrec.S_No == delschrec.S_No && itemdetrec.Part_No == delschrec.Part_No && itemdetrec.Specification == delschrec.Specification && delschrec.Full_Quantity == false)
				{
					row.Specification=delschrec.Specification;
				}
				//calculate the quantity and comapare with item details qty
				if(delschrec.Part_No == itemdetrec.Part_No && delschrec.S_No == itemdetrec.S_No)
				{
					//if(delschrec.Part_No == itemdetrec.Part_No && delschrec.Specification == itemdetrec.Specification)
					dsqtytot = dsqtytot + ifnull(delschrec.Quantity,0.0);
				}
				//qty,spec
				if(itemdetrec.Part_No == row.Part_No && itemdetrec.S_No == row.S_No)
				{
					row.Quantity=if(dsqtytot > 0,itemdetrec.Ordered_Qty - dsqtytot,itemdetrec.Ordered_Qty);
					row.Quantity=itemdetrec.Ordered_Qty;
					row.Specification=itemdetrec.Specification;
					row.Full_Quantity=true;
				}
				//itemdetails partno qty splitting in delvy sch with different date
				if(itemdetrec.Part_No == row.Part_No && itemdetrec.Specification == row.Specification && row.Full_Quantity == false)
				{
					row.Specification=itemdetrec.Specification;
					row.Quantity=if(dsqtytot > 0,itemdetrec.Ordered_Qty - dsqtytot,itemdetrec.Ordered_Qty);
				}
			}
		}
	}
}
if(!isNull(input.Incoterms))
{
	if(input.Incoterms_same_for_all_items == "Yes")
	{
		row.Incoterms=input.Incoterms;
	}
	else
	{
		row.Incoterms=null;
	}
}
if(!isNull(input.Incoterms_Location1))
{
	if(input.Incoterms_Location_same_for_all_items == "Yes")
	{
		row.Incoterms_Location=input.Incoterms_Location1;
	}
	else
	{
		row.Incoterms_Location=null;
	}
}
if(!isNull(input.Delivery_Date))
{
	if(input.Delivery_Date_same_for_all_items == "Yes")
	{
		row.Delivery_Date=input.Delivery_Date;
	}
	else
	{
		row.Delivery_Date=null;
	}
}
//old code for ERP Issue no. 13 & 32 is commented. start below
/*i = 0;
for each  rec_sn in input.Delivery_Schedule
{
    i = i + 1;
    row.S_No=i;
}
//10-07-2019/For Delivery Schedule
clear row.Part_No;
item_list = List();
deliv_list = List();
for each  an_item in input.Item_Details
{
    item_list.add(an_item.Part_Description);
}
for each  deliv in input.Delivery_Schedule
{
    if(deliv.Part_No != null && deliv.Full_Quantity == true)
    {
        deliv_list.add(deliv.Part_No);
    }
}
item_list.removeAll(deliv_list);
row.Part_No:ui.add(item_list.sort(true));
if(item_list.size() > 0)
{
    row.Part_No=item_list.get(0);
    //Setting Quantity
    for each  rec in input.Item_Details
    {
        if(rec.Ordered_Qty < 1)
        {
            alert "Please enter quantity for all the item(s) in Item Details Subform";
            row.Quantity=null;
        }
        else
        {
            tot = 0.0;
            for each  rec1 in input.Delivery_Schedule
            {
                if(rec1.Part_No == rec.Part_Description)
                {
                    tot = tot + ifnull(rec1.Quantity,0.0);
                }
            }
            if(rec.Part_Description == row.Part_No)
            {
                row.Quantity=if(tot > 0,rec.Ordered_Qty - tot,rec.Ordered_Qty);
                row.Full_Quantity=true;
            }
        }
    }
}
if(!isNull(input.Incoterms))
{
    if(input.Incoterms_same_for_all_items == "Yes")
    {
        row.Incoterms=input.Incoterms;
    }
    else
    {
        row.Incoterms=null;
    }
}
if(!isNull(input.Incoterms_Location1))
{
    if(input.Incoterms_Location_same_for_all_items == "Yes")
    {
        row.Incoterms_Location=input.Incoterms_Location1;
    }
    else
    {
        row.Incoterms_Location=null;
    }
}
if(!isNull(input.Delivery_Date))
{
    if(input.Delivery_Date_same_for_all_items == "Yes")
    {
        row.Delivery_Date=input.Delivery_Date;
    }
    else
    {
        row.Delivery_Date=null;
    }
}*/
//old code end above 
fet_pref = Preferences[Module_Name = "GRN"];
input.Auto_Approval = fet_pref.Auto_Approval;
//_________________________________________________________________
hide Item_Details.Purchase_Order_Number;
hide Item_Details.Tax_Value;
hide Item_Details.Tax;
hide Item_Details.Income_Quality_Check_Process;
hide Item_Details.zinvt_line_item_id;
hide Item_Details.zinvt_item_id;
hide Purchase_Order_Subform_RECID;
hide Transportation_details.GRN_Main_RECID;
input.Received_By = Employee_Details[Employee_Email == zoho.loginuserid].ID;
input.GRN_Time = zoho.currenttime;
disable GRN_Time;
if(Purchase_Order_Subform_RECID != null || Purchase_Order_Subform_RECID.size() > 0)
{
	TotalValue = 0;
	tot_qty = 0;
	i = 0;
	input.Goods_Received_Note_Date = zoho.currentdate;
	for each  PORec in input.Purchase_Order_Subform_RECID
	{
		i = i + 1;
		getPosub = Purchase_Order_Subform[ID == PORec.ID && PO_Status == "GRN Pending" || PO_Status == "Gate Entry Partially Done" || PO_Status == "GRN Partially Received"];
		getPOMain = Purchase_Order[ID == getPosub.Purchase_Order_ExisID];
		//get the indent raised by and department details  - user requirememnt - 12/12/2022
		getindentsf = Indent_Sub_Form[ID == getPOMain.Indent_Sub_Form_RECID];
		getindent = Indent[ID == getindentsf.Indent_Form_RECID];
		//	getindentno = Indent_Sub_Form[Purchase_Order_Subform_RECIDD == PORec.ID];
		getindentno = Indent_Sub_Form[ID == getPosub.Indent_Sub_Form];
		//info getindentno;
		getmaterials = Materials[ID == getPosub.Part_No];
		getcategory = Category[ID == getmaterials.Category];
		//info getcategory;
		if(getindent.count() = 0)
		{
			hide Indent_No;
			hide Indentor;
			hide Department;
		}
		else
		{
			input.Indent_No = getindentno.Indent_No;
			disable Indent_No;
			input.Indentor = getindent.Request_Raised_By;
			disable Indentor;
			input.Department = getindent.Department;
			disable Department;
		}
		input.Purchase_Order = getPosub.Purchase_Order_ExisID;
		input.Purchase_Order_Nos = (input.Purchase_Order_Subform_RECID.Purchase_Order_ExisID.getall()).distinct();
		//input.Mode_of_delivery = getPOMain.Shipping_Mode;//field deleted as per user request - 31/01/2023
		input.Purchase_Order_Number = getPOMain.ID;
		input.Purchase_Order_Date = getPOMain.Purchase_Order_Date;
		disable Purchase_Order;
		disable Mode_of_delivery;
		disable Purchase_Order_Number;
		disable Purchase_Order_Date;
		input.Vendor_Name = getPOMain.Vendor_Name;
		gatefet = Create_Gate_Entry1[Vendor_Name == input.Vendor_Name && GEP_Status != "Closed"].ID.getAll();
		input.Gate_Entry_No:ui.add(gatefet);
		disable Vendor_Name;
		Get_Tax_Perc = GST_Details[ID == getPosub.Tax].Total_Rate;
		if(Get_Tax_Perc != null)
		{
			Tax_Amount = (ifnull(PORec.Ordered_Qty,0) - ifnull(PORec.Qty_Received_so_far,0)) * ifnull(getPosub.Rate,0.00) * Get_Tax_Perc / 100;
		}
		if(Get_Tax_Perc != null)
		{
			Total_Amount = (ifnull(PORec.Ordered_Qty,0) - ifnull(PORec.Qty_Received_so_far,0)) * ifnull(getPosub.Rate,0.00) + ifnull(Tax_Amount,0.0);
		}
		else
		{
			Total_Amount = (ifnull(PORec.Ordered_Qty,0) - ifnull(PORec.Qty_Received_so_far,0)) * ifnull(getPosub.Rate,0.00);
		}
		//Disable all Subform Fields except Received Quantity.
		hide Item_Details.GRN_Created_Date;
		if(getcategory.Category != "HR Coils")
		{
			hide Item_Details.HR_Coil_id;
		}
		else
		{
			hide Item_Details.HR_Coil_id;
		}
		disable Item_Details.S_No;
		disable Item_Details.GRN_Created_Date;
		disable Item_Details.Part_No;
		disable Item_Details.Part_Description;
		disable Item_Details.Specification;
		disable Item_Details.UoM;
		disable Item_Details.Ordered_Qty;
		disable Item_Details.Received_Qty_So_far;
		disable Item_Details.Rate;
		disable Item_Details.Sub_Total;
		disable Item_Details.Tax;
		disable Item_Details.Tax_Value;
		disable Item_Details.Amount;
		disable Item_Details.Balance_Qty;
		//disable Item_Details.MFG_Date; comment on 6.9.2022 by partha
		//disable Item_Details.Exp_Date; comment on 6.9.2022 by partha
		disable Item_Details.PO_ID;
		disable Item_Details.Purchase_Order_SubForm_RECID;
		disable Item_Details.Batch_Number;
		disable Item_Details.Total_Price;
		disable Item_Details.Barcode;
		disable Item_Details.GRN_ID;
		disable Item_Details.HR_Coil_id;
		disable Item_Details.Indentor;
		disable Item_Details.Indent_No;
		disable Item_Details.Indentor_Dept;
		//ItemDetails Subform - Declaring the Row for Subform 
		ItemDetailSFRow = GRN.Item_Details();
		// assigning values for various subform fields in the row
		ItemDetailSFRow.S_No=i;
		ItemDetailSFRow.GRN_Created_Date=zoho.currentdate;
		ItemDetailSFRow.Part_No=getPosub.Part_No;
		ItemDetailSFRow.Part_Description=getPosub.Part_Description;
		ItemDetailSFRow.Specification=getPosub.Specification;
		ItemDetailSFRow.UoM=getPosub.UoM;
		ItemDetailSFRow.Rate=ifnull(getPosub.Rate,0.00);
		ItemDetailSFRow.Sales_Order_No=getPosub.Sales_Order_No;
		ItemDetailSFRow.PO_ID=getPosub.Purchase_Order_ExisID;
		ItemDetailSFRow.Purchase_Order_SubForm_RECID=PORec.ID;
		ItemDetailSFRow.Ordered_Qty=getPosub.Ordered_Qty;
		ItemDetailSFRow.Received_Qty=Ifnull(getPosub.Ordered_Qty,0) - Ifnull(getPosub.Qty_Received_so_far,0);
		//Pooja  ItemDetailSFRow.Received_Qty=ifnull(getPosub.Qty_Recieved_so_far_GE,0);
		//ItemDetailSFRow.Received_Qty=ifnull(getPosub.Qty_Recieved_so_far_GE,0) - ifNull(getPosub.Qty_Received_so_far,0);
		ItemDetailSFRow.Balance_Qty=ifnull(getPosub.Ordered_Qty,0) - (ifnull(ItemDetailSFRow.Received_Qty,0) + ifnull(getPosub.Qty_Received_so_far,0));
		ItemDetailSFRow.Received_Qty_So_far=Ifnull(getPosub.Qty_Received_so_far,0);
		ItemDetailSFRow.Sub_Total=(ifnull(getPosub.Ordered_Qty,0) - ifnull(getPosub.Qty_Received_so_far,0)) * ifnull(getPosub.Rate,0.00);
		if(getPosub.Tax != null)
		{
			ItemDetailSFRow.Tax=Ifnull(getPosub.Tax,"");
			ItemDetailSFRow.Tax_Value=ifnull(Tax_Amount,0.00);
		}
		if(getPosub.Tax == null)
		{
			ItemDetailSFRow.Amount=ifnull(ItemDetailSFRow.Sub_Total,0.00);
		}
		else
		{
			ItemDetailSFRow.Amount=ifnull(ItemDetailSFRow.Sub_Total,0.00) + ifnull(ItemDetailSFRow.Tax_Value,0.00);
		}
		ItemDetailSFRow.Total_Price=ItemDetailSFRow.Amount;
		ItemDetailSFRow.Purchase_Order_Number=getPOMain.ID;
		TotalValue = ifnull(TotalValue,0.00) + ifnull(ItemDetailSFRow.Amount,0.00);
		tot_qty = tot_qty + ifnull(ItemDetailSFRow.Received_Qty,0);
		//ItemDetailSFRow.Indent_No=getindent.Indent_No;
		ItemDetailSFRow.Indent_No=ifnull(getindentno,"");
		ItemDetailSFRow.Indentor=getindent.Request_Raised_By;
		ItemDetailSFRow.Indentor_Dept=getindent.Department;
		//ItemDetailSFRow.HR_Coil_id=Coil_id;
		// declare a variable to hold the collection of rows
		ItemDetailSfCol = Collection();
		ItemDetailSfCol.insert(ItemDetailSFRow);
		// insert the rows into the subform through the variable
		input.Item_Details.insert(ItemDetailSfCol);
	}
	//Retrieve the Transportation details
	/* 	fetgateentry = Gate_Entry_Process[Purchase_Order_No == input.Purchase_Order_Number];
	if(fetgateentry.count() > 0)
	{
		fettransentry = Gate_Entry_Transport_Details[Gate_Entry_Process_RECID == fetgateentry.ID];
		for each  transrec in fettransentry
		{
			//if(fettransentry.count() > 0)
			//	{
			TransportSFRow = GRN.Transportation_details();
			TransportSFRow.Vehicle_No=transrec.Vehicle_No;
			TransportSFRow.Name_of_Transport=transrec.Name_of_Transport;
			TransportSFRow.Driver_Name=transrec.Driver_Name;
			TransportSFRow.Driver_Contact_No=transrec.Driver_Contact_No;
			TransportSFRow.GR_RR_No=transrec.GR_RR_No;
			TransportSFRow.GR_RR_Date=transrec.GR_RR_Date;
			TransportSFRow.Picture_of_Item_Lorry=transrec.Picture_of_Item_Lorry;
			TransportSFRow.Picture_Description=transrec.Picture_Description;
			TransportSfCol = Collection();
			TransportSfCol.insert(TransportSFRow);
			// insert the rows into the subform through the variable
			input.Transportation_details.insert(TransportSfCol);
			disable Transportation_details.Vehicle_No;
			disable Transportation_details.Name_of_Transport;
			disable Transportation_details.Driver_Name;
			disable Transportation_details.Driver_Contact_No;
			disable Transportation_details.GR_RR_Date;
			disable Transportation_details.GR_RR_No;
			disable Transportation_details.Picture_Description;
			disable Transportation_details.Picture_of_Item_Lorry;
			disable Transportation_details.Status;
		}
	}
	else
	{
		hide Transportation_details;
	} */
	input.Total_Value = ifnull(TotalValue,0.00);
	input.Total_Quantity = ifnull(tot_qty,0.00);
	html = "<html><head><style>#customers {font-family: 'Trebuchet MS', Arial, Helvetica, sans-serif;border-collapse: collapse;width: 100%;}#customers td, #customers th {border: 1px solid #ddd;padding: 8px;}#customers tr:nth-child(even){background-color: #f2f2f2;}#customers tr:hover {background-color: #ddd;}#customers th { padding-top: 12px;padding-bottom: 12px;text-align: left;background-color: #f9f9f9;}</style></head><body>";
	html = html + "<table id='customers'><th style='text-align:center;'>PO Form</th></tr>";
	Val_url = "https://app.zohocreator.in/carrierwheels/erp/#Page:PO_Template?ID=" + input.Purchase_Order + "&zc_LoadIn=dialog&zc_Header=false";
	urlvalue = "<a href='" + Val_url + "'>View PO</a>";
	html = html + "</td><td>" + urlvalue + "</td></tr>";
	html = html + "</table></body></html>";
	input.plain = html;
}
disable Material_Landing_Rack;
if(input.Material_Landing_Rack == null)
{
	fet_mat = Rack_Master[Racks_Bins == "Store Incoming Area"];
	input.Material_Landing_Rack = fet_mat.ID;
}
fetblk = FG_Block_Stock1[ID == input.FG_Block_Stock_ID];
hide FG_Block_Stock_ID;
input.Work_Order_No = fetblk.WO_No;
input.Blocked_Qty = fetblk.Block_Qty;
input.Part_No = fetblk.Part_No;
input.Part_Name = fetblk.Part_Name;
input.Unblocking_Date = zoho.currentdate;
input.Unblocked_By = Employee_Details[Employee_Email == zoho.loginuserid].ID;
input.Unblock_Qty = fetblk.Block_Qty;
disable Part_No;
disable Part_Name;
disable Blocked_Qty;
disable Unblocking_Date;
disable Work_Order_No;
disable Unblocked_By;
disable Balance_Blocked_Qty;
disable Blocked_Qty_So_far;
hide Blocked_Qty_So_far;
disable Balance_Blocked_Qty;
hide Status;
if(fetblk.Status == "Partially UnBlocked")
{
	input.Unblock_Qty = fetblk.Balance_Blocked_Qty;
	input.Balance_Blocked_Qty = fetblk.Balance_Blocked_Qty;
	input.Blocked_Qty_So_far = fetblk.Quantity_Blocked_So_far;
	show Blocked_Qty_So_far;
	show Balance_Blocked_Qty;
}
fetblk = FG_Block_Stock1[ID == input.FG_Block_Stock_ID];
if(fetblk.Status != "Partially UnBlocked")
{
	input.Balance_Blocked_Qty = ifnull(fetblk.Block_Qty,0) - ifnull(input.Unblock_Qty,0);
}
if(fetblk.Status == "Partially UnBlocked")
{
	input.Balance_Blocked_Qty = ifnull(fetblk.Quantity_Blocked_So_far,0) - ifnull(input.Unblock_Qty,0);
}
if(input.Balance_Blocked_Qty < 0)
{
	input.Balance_Blocked_Qty = 0;
}
if(input.Unblock_Qty <= 0)
{
	alert "Unblock qty not should be zero or less than zero";
	input.Unblock_Qty = null;
	input.Balance_Blocked_Qty = 0;
	input.Balance_Blocked_Qty = 0;
}
else if(input.Unblock_Qty > Blocked_Qty)
{
	alert "Unblock qty not more than blocked qty";
	input.Unblock_Qty = null;
}
if(fetblk.Status == "Partially UnBlocked" && input.Unblock_Qty > fetblk.Balance_Blocked_Qty)
{
	alert "Unblock Qty shouldn't be greater than Balance Blocked Qty";
	input.Unblock_Qty = fetblk.Balance_Blocked_Qty;
}
fetch_inv = Inventory[Part_No == input.Part_No] sort by Available_Qty desc;
fet_chk = FG_Block_Stock1[ID == input.FG_Block_Stock_ID];
if(input.Unblock_Qty == fet_chk.Block_Qty || input.Unblock_Qty == fet_chk.Balance_Blocked_Qty)
{
	fet_chk.Quantity_Blocked_So_far=ifnull(fet_chk.Quantity_Blocked_So_far,0) + input.Unblock_Qty;
	fet_chk.Unblocked_Qty=fet_chk.Block_Qty;
	fet_chk.Balance_Blocked_Qty=0;
	fetch_inv.Block_Qty=ifnull(fetch_inv.Block_Qty,0) - input.Unblock_Qty;
	fetch_inv.Available_Qty=ifnull(fetch_inv.Available_Qty,0) + input.Unblock_Qty;
	fet_chk.Status="Fully UnBlocked";
	input.Status = "Fully UnBlocked";
}
else if(input.Unblock_Qty < fet_chk.Block_Qty && input.Unblock_Qty != fet_chk.Balance_Blocked_Qty)
{
	fet_chk.Quantity_Blocked_So_far=ifnull(fet_chk.Quantity_Blocked_So_far,0) + input.Unblock_Qty;
	fet_chk.Unblocked_Qty=ifnull(fet_chk.Quantity_Blocked_So_far,0);
	if(fet_chk.Balance_Blocked_Qty == null)
	{
		fet_chk.Balance_Blocked_Qty=fet_chk.Block_Qty - input.Unblock_Qty;
	}
	else
	{
		fet_chk.Balance_Blocked_Qty=fet_chk.Balance_Blocked_Qty - input.Unblock_Qty;
	}
	fetch_inv.Block_Qty=ifnull(fetch_inv.Block_Qty,0) - input.Unblock_Qty;
	fetch_inv.Available_Qty=ifnull(fetch_inv.Available_Qty,0) + input.Unblock_Qty;
	fet_chk.Status="Partially UnBlocked";
	input.Status = "Partially UnBlocked";
}
openUrl("#Form:Alert_Messages?Status=" + "UNBlOCK" + "&Value=" + input.Unblock_Qty + "&zc_LoadIn=dialog","same window");
void Payments.Payments(int booksid)
{
	fet_payBook = Get_Payments_ID_from_Books[ID == input.booksid];
	bksid = fet_payBook.Payment_Books_ID;
	books_access = thisapp.Books.Get_Books_Access();
	conn_tok = books_access.get("connection");
	org_id = books_access.get("organisation_id");
	get_payresp = zoho.books.getRecordsByID("customerpayments",org_id,bksid,conn_tok);
	//	info get_payresp;
	pay_data = get_payresp.tomap().get("payment");
	//	info pay_data ;
	custname = pay_data.get("customer_name");
	payid = pay_data.get("payment_id");
	custid = pay_data.get("customer_id");
	//info custid;
	invoices = pay_data.get("invoices").toList();
	invlist = List();
	invid = List();
	invamt = List();
	payamnt = List();
	for each  rec in invoices
	{
		map_val = rec.toMap();
		invoice_ID = map_val.get("invoice_id");
		invoice_no = map_val.get("invoice_number");
		inv_amnt = map_val.get("invoice_amount");
		pay_amnt = map_val.get("amount_applied");
		fetinv = Invoice[Zoho_Books_ID == invoice_ID].ID;
		fetinvno = Invoice[Invoice_No == invoice_no];
		fetinvamnt = Invoice[Grand_Total == inv_amnt];
		fetpayamnt = Payments[Payment_Amount == pay_amnt];
		invlist.add(fetinvno);
		invid.add(fetinv);
		invamt.add(inv_amnt);
		pay_amnt.add(pay_amnt);
	}
	customer_id = Customers[Customer_Books_ID == custid].ID;
	amtrec = pay_data.get("amount");
	paydate = pay_data.get("date");
	//--------------------------------------------------
	paymode = pay_data.get("payment_mode");
	invdate = pay_data.get("date");
	//	invno = pay_data.get("invoice_number");
	payno = pay_data.get("payment_number");
	payins = insert into Payments
	[
		Added_User=zoho.loginuser
		Customer_Name=customer_id
		Payment_ID=payid
		Customer_ID=custid
		Amount_Received=amtrec
		Payment_Date=paydate
		Payment_Mode=paymode
		Invoice_Date=invdate
		Inv_ID=invid
		Invoice_No1=invlist
		Payment_No=payno
		Payment_Status="Success"
		Invoice_Amount=invamt
		Payment_Amount=payamnt
	];
}
void Materials.Items_CRM_Sync(int mat_id)
{
	mat = Materials[ID == mat_id];
	matmap = Map();
	matmap.put("Product_Code",mat.Part_No);
	matmap.put("Product_Name",mat.Part_Description);
	matmap.put("Specification",mat.Specification);
	matmap.put("Usage_Unit",mat.Primary_UoM.UOM);
	matmap.put("Creator_ID",mat.ID.toString());
	matmap.put("Brand_Name",ifNull(mat.Brand_Name.Brand_Name,""));
	matmap.put("Alternate_UoM",mat.Alternate_UoM.UOM);
	matmap.put("Rounding_Value",mat.Rounding_Value);
	matmap.put("Primary_UoM",mat.Primary_UoM.UOM);
	matmap.put("MOQ_Minimum_Lot_Size",mat.MOQ);
	matmap.put("Procurement_Lead_Time_Days",mat.Procurement_Lead_Time_Days);
	matmap.put("Planning_Procedure",mat.Planning_Procedure);
	matmap.put("Blank_Length",mat.Blank_Length);
	matmap.put("Blank_Width",mat.Blank_Width);
	matmap.put("Blank_Thickness",mat.Blank_Thickness);
	matmap.put("Blank_Weight",mat.Blank_Weight);
	matmap.put("Final_Weight",mat.Final_Weight);
	matmap.put("Surface_Area_in_mm2",mat.Surface_Area);
	matmap.put("Maximum_Stock",mat.Maximum_Stock);
	matmap.put("Minimum_Stock",mat.Minimum_Stock);
	matmap.put("GST_Details",mat.GST_Details.Tax_Name);
	matmap.put("IGST_Details",mat.IGST_Details.Tax_Name);
	matmap.put("HSN_SAC",mat.HSN_SAC);
	if(mat.Zoho_Books_ID != Null)
	{
		matmap.put("Books_ID",mat.Zoho_Books_ID.toString());
	}
	dummymap = Map();
	if(isNull(mat.CRM_ID))
	{
		crmsync = zoho.crm.createRecord("Products",matmap,dummymap,"crm_connection");
		mat.CRM_ID=crmsync.get("id");
		info crmsync;
	}
	else
	{
		updsync = zoho.crm.updateRecord("Products",mat.CRM_ID.toLong(),matmap,dummymap,"crm_connection");
		//info updsync;
	}
}
void Invoice.Invoice_Eway_bill_Details_Update()
{
	books_access = thisapp.Books.Get_Books_Access();
	conn_tok = books_access.get("connection");
	org_id = books_access.get("organisation_id");
	invoicedata = Invoice[Zoho_Books_ID != null && E_Way_Bill_No == ""] sort by Added_Time desc range from 1 to 20;
	//	invoicedata = Invoice[Zoho_Books_ID != null && E_Way_Bill_No == "" && Sale_Order_No == null] sort by ID desc range from 21 to 30;
	//invoicedata = Invoice[Zoho_Books_ID != null && E_Way_Bill_No == "" && Sale_Order_No != null];
	//invoicedata = Invoice[Zoho_Books_ID == "917835000036874439" && E_Way_Bill_No == ""];
	info invoicedata.count();
	i = 0;
	for each  recxx in invoicedata
	{
		zbid = recxx.Zoho_Books_ID;
		invoice_resp = zoho.books.getRecordsByID("invoices",org_id,zbid.tostring(),conn_tok);
		//info "invoice resp code " + invoice_resp.get("code") + "---" + zbid;
		ewaybill = invoice_resp.get("invoice").toMap().get("eway_bill_details");
		info ewaybill;
		if(!isempty(ewaybill))
		{
			bno = ewaybill.get("eway_bill_number");
			if(!isnull(bno))
			{
				recxx.E_Way_Bill_No=ewaybill.get("eway_bill_number");
			}
			if(!isnull(ewaybill.get("eway_bill_date")))
			{
				recxx.E_Way_Bill_Date=ewaybill.get("eway_bill_date").toString("dd-MMM-yyyy");
			}
			i = i + 1;
		}
		else if(!isnull(ewaybill))
		{
			bno = ewaybill.get("eway_bill_number");
			if(!isnull(bno))
			{
				recxx.E_Way_Bill_No=ewaybill.get("eway_bill_number");
			}
			if(!isnull(ewaybill.get("eway_bill_date")))
			{
				recxx.E_Way_Bill_Date=ewaybill.get("eway_bill_date").toString("dd-MMM-yyyy");
			}
			i = i + 1;
		}
	}
	info i;
}
void Indent.Indent_Email_Notification(int myindent_ID)
{
	myindent = Indent[ID == myindent_ID];
	myindent_itemdetails = Indent_Sub_Form[Indent_Form_RECID == myindent_ID];
	getindentor = Employee_Details[ID == myindent.Request_Raised_By];
	emailto = getindentor.Employee_Email;
	getemail = Email_Template[Template_No == 4];
	sub = getemail.Subject_field;
	body = getemail.Body;
	sub = sub.replaceAll("{prno}",myindent.Indent_No,true);
	sub = sub.replaceAll("{prstatus}",myindent.Approval_Status,true);
	body = body.replaceAll("{prno}",myindent.Indent_No,true);
	body = body.replaceAll("{prdate}",myindent.Indent_Request_Date.tostring("d-MMM-yyyy"),true);
	body = body.replaceAll("{prstatus}",myindent.Approval_Status,true);
	body = body.replaceAll("{indentor}",getindentor.Employee_Name,true);
	if(myindent.Project_Name != null)
	{
		project = "The indent was placed for the project " + myindent.Project_Name.Project_Number + " - " + myindent.Project_Name.Project_Title;
	}
	else
	{
		project = null;
	}
	body = body.replaceAll("{project}",ifnull(project,""),true);
	IndentLink = "<a href='https://creatorapp.zoho.in/carrierwheels/erp#Report:All_Indents?Indent_No=" + myindent.Indent_No + "' title='Click to Open Indent' target='_blank'>Click to Open Indent " + myindent.Indent_No + "</a>";
	body = body.replaceAll("{link}",IndentLink,true);
	tab = "<html><style>th,td {padding: 5px;}</style><table border = 1> <th>S. No.</th> <th>Part No.</th> <th>Part Description</th> <th>Specification</th> <th>Required Qty</th><th>UOM</th> <th>Remarks</th> <th>Purpose of Indent</th>";
	count = 1;
	for each  tablerec in myindent_itemdetails
	{
		getuom = Unit_of_Measurement[ID == tablerec.UoM].UOM;
		tab = tab + "<tr><td>" + count + "</td>";
		tab = tab + "<td>" + tablerec.Part_No.Part_No + "</td>";
		tab = tab + "<td>" + tablerec.Part_Description.Part_Description + "</td>";
		tab = tab + "<td>" + ifnull(tablerec.Specification,"") + "</td>";
		tab = tab + "<td>" + ifnull(tablerec.Required_Qty,0) + "</td>";
		tab = tab + "<td>" + getuom + "</td>";
		tab = tab + "<td>" + ifNull(tablerec.Remarks,"") + "</td>";
		tab = tab + "<td>" + ifnull(tablerec.Purpose_of_Indent,"") + "</td></tr>";
		count = count + 1;
	}
	tab = tab + "</table></html>";
	body = body.replaceAll("{table}",tab,true);
	//info body;
	sendmail
	[
		from :"CWPL ERP <erp@carrierwheels.com>"
		to :emailto
		reply to :"sourcing@carrierwheels.com"
		subject :sub
		message :body
	]
}
void GRN.Create_GRN(Purchase_Order_Subform posub)
{
	poid = list();
	povendlist = list();
	for each  recval in posub
	{
		poid.add(recval);
		fetpomain = Purchase_Order[ID == recval.Purchase_Order_ExisID];
		povendlist.add(fetpomain.Vendor_Name);
	}
	if(povendlist.distinct().size() == 1)
	{
		openUrl("#Form:GRN?Purchase_Order_Subform_RECID=" + poid,"same window");
	}
	else
	{
		openUrl("#Form:Alert_Messages?Status=GRN&Value=Selected Vendors are not same pls check.&zc_LoadIn=dialog","same window");
	}
}
void GRN.GRN_Email_Notification(int ID)
{
	getgrnsubform = GRN_Subform[GRN_ID == input.ID];
	//info getgrnsubform;
	getgrnmain = GRN[ID == getgrnsubform.GRN_ID];
	//info getgrnmain;
	getposubform = Purchase_Order_Subform[ID == getgrnsubform.Purchase_Order_SubForm_RECID];
	//info getposubform;
	getpomain = Purchase_Order[ID == getposubform.Purchase_Order_ExisID];
	//info getpomain;
	//	getindentsf = Indent_Sub_Form[ID == getposubform.Indent_Sub_Form];
	getindentsf = Indent_Sub_Form[Purchase_Order_Subform_RECID == getgrnsubform.Purchase_Order_SubForm_RECID];
	//info getindentsf;
	getindent = Indent[ID == getindentsf.Indent_Form_RECID];
	//info "Get Indent:" + getindent;
	getindentor = Employee_Details[ID == getindent.Request_Raised_By];
	emailto = getindentor.Employee_Email;
	//info "Email To:" + emailto;
	getemail = Email_Template[Template_No == 3];
	sub = getemail.Subject_field;
	body = getemail.Body;
	sub = sub.replaceAll("{grnno}",getgrnmain.Goods_Received_Note_Number,true);
	sub = sub.replaceAll("{pono}",getpomain.Purchase_Order_No,true);
	body = body.replaceAll("{indentor}",ifnull(getindentor.Employee_Name,""),true);
	body = body.replaceAll("{grnno}",getgrnmain.Goods_Received_Note_Number,true);
	tab = "<html><style>th,td {padding: 5px;}</style><table border = 1> <th>Indent No.</th>  <th>Part No.</th> <th>Part Description</th> <th>Specification</th> <th>Quantity Received</th><th>UOM</th> <th>Remarks of Indent</th> <th>Purpose of Indent</th> <th>Zoho Project</th>";
	for each  tablerec in getgrnsubform
	{
		getindentno = Indent_Sub_Form[Purchase_Order_Subform_RECID == tablerec.Purchase_Order_SubForm_RECID];
		getuom = Unit_of_Measurement[ID == tablerec.UoM].UOM;
		if(getindentno.count() > 0)
		{
			IndentLink = "<a href='https://creatorapp.zoho.in/carrierwheels/erp#Report:All_Indents?Indent_No=" + ifnull(getindentno.Indent_No,"") + "' title='Click to Open Indent' target='_blank'>" + ifnull(getindentno.Indent_No,"") + "</a>";
			tab = tab + "<tr><td>" + ifnull(IndentLink,"") + "</td>";
			tab = tab + "<td>" + tablerec.Part_No.Part_No + "</td>";
			tab = tab + "<td>" + tablerec.Part_Description.Part_Description + "</td>";
			tab = tab + "<td>" + ifnull(tablerec.Specification,"") + "</td>";
			tab = tab + "<td>" + ifnull(tablerec.Received_Qty,0) + "</td>";
			tab = tab + "<td>" + getuom + "</td>";
			myindentsf = Indent_Sub_Form[Purchase_Order_Subform_RECID == tablerec.Purchase_Order_SubForm_RECID];
			tab = tab + "<td>" + ifNull(myindentsf.Remarks,"") + "</td>";
			tab = tab + "<td>" + ifNull(myindentsf.Purpose_of_Indent,"") + "</td>";
			tab = tab + "<td>" + ifnull(myindentsf.Project_Name,"") + "</td></tr>";
		}
		else
		{
			//info "else";
			IndentLink = "<a href='https://creatorapp.zoho.in/carrierwheels/erp#Report:All_Indents?Indent_No=" + ifnull(getindentno.Indent_No,"") + "' title='Click to Open Indent' target='_blank'>" + ifnull(getindentno.Indent_No,"") + "</a>";
			//info "Link:" + IndentLink;
			tab = tab + "<tr><td>" + IndentLink + "</td>";
			tab = tab + "<td>" + tablerec.Part_No.Part_No + "</td>";
			tab = tab + "<td>" + tablerec.Part_Description.Part_Description + "</td>";
			tab = tab + "<td>" + ifnull(tablerec.Specification,"") + "</td>";
			tab = tab + "<td>" + ifnull(tablerec.Received_Qty,0) + "</td>";
			tab = tab + "<td>" + getuom + "</td>";
			myindentsf = Indent_Sub_Form[Purchase_Order_Subform_RECID == tablerec.Purchase_Order_SubForm_RECID];
			tab = tab + "<td>" + ifNull(myindentsf.Remarks,"") + "</td>";
			tab = tab + "<td>" + ifNull(myindentsf.Purpose_of_Indent,"") + "</td>";
			tab = tab + "<td>" + ifnull(myindentsf.Project_Name,"") + "</td></tr>";
		}
	}
	//info "Tab:" + tab;
	tab = tab + "</table></html>";
	body = body.replaceAll("{table}",tab,true);
	//info "Body:" + body;
	//emp = Employee_Details[Department_Name.Department_Name == "Stores"];
	if(getindentno.count() > 0)
	{
		sendmail
		[
			from :"CWPL ERP<erp@carrierwheels.com>"
			to :emailto
			cc:"sourcing@carrierwheels.com"
			reply to :"stores@carrierwheels.com"
			subject :sub
			message :body
		]
	}
	else
	{
		sendmail
		[
			from :"CWPL ERP<erp@carrierwheels.com>"
			to :"sourcing@carrierwheels.com"
			cc:"sourcing@carrierwheels.com"
			subject :sub
			message :body
		]
	}
	//cc:"sourcing@carrierwheels.com"
}
string financial_year()
{
	fin_str = "";
	curr_year = zoho.currentdate.getYear();
	curr_month = zoho.currentdate.getMonth();
	if(curr_month > 3)
	{
		next_year = curr_year.toLong() + 1;
		//last_2_dig = next_year.subString(2,4);
		fin_str = curr_year + "-" + next_year;
		//Use "last_2_dig" if u want to display last 2 digit of year
	}
	else
	{
		next_year = curr_year.toLong() - 1;
		//last_2_dig = curr_year.subString(2,4);
		fin_str = (curr_year - 1) + "-" + curr_year;
		//Use "last_2_dig" if u want to display last 2 digit of year
	}
	return fin_str;
}
void CRM.Employee_insert_in_CRM(int empid)
{
	books_access = thisapp.Books.Get_Books_Access();
	conn_tok = books_access.get("connection");
	org_id = books_access.get("organisation_id");
	fetch_emp_id = Employee_Details[ID == input.empid];
	mymap = Map();
	mymap.put("Name",fetch_emp_id.Employee_Name);
	mymap.put("Employee_code",fetch_emp_id.Employee_ID);
	mymap.put("Email",fetch_emp_id.Employee_Email);
	mymap.put("Phone",fetch_emp_id.Mobile_Number);
	mymap.put("Designation",fetch_emp_id.Designation);
	mymap.put("Status",fetch_emp_id.Status);
	// 	info mymap;
	dummymap = Map();
	// 	info fetch_emp_id.Zoho_CRM_ID;
	if(fetch_emp_id.Zoho_CRM_ID == null || fetch_emp_id.Zoho_CRM_ID == "")
	{
		createincrm = zoho.crm.createRecord("CWPL_Emp",mymap,dummymap,"crm_connection");
		emp_id = createincrm.get("id");
		//info createincrm;
	}
	else
	{
		updatrecincrm = zoho.crm.updateRecord("CWPL_Emp",fetch_emp_id.Zoho_CRM_ID.toLong(),mymap);
		emp_id = updatrecincrm.get("id");
		//info updatrecincrm;
	}
	// 	info createincrm;
	info emp_id;
	//Error in log file--Mismatch of data type expression. Expected BIGINT but found STRING Line:(26)
	if(fetch_emp_id.Zoho_CRM_ID == null || fetch_emp_id.Zoho_CRM_ID == "")
	{
		fetch_emp_id.Zoho_CRM_ID=emp_id;
	}
}
string Common.Number_Function_New(String module_name)
{
	//---------Sales Order - Contract prefix should be "CO" - Direct & Tooling is "SO" - user requirement dt 25/04/2023
	if(module_name == "Sales Order Direct")
	{
		fetch_sale_rec = Sales_Order[Sale_Order_No != null && Sale_Order_No != "" && Sales_Type != "Contract"] sort by Sale_Order_No desc;
		//fetch_sale_rec = Sales_Order[Sale_Order_No != null && Sale_Order_No != ""] sort by Sale_Order_No desc;
		fet_mod = Module_Master[Module_Name == module_name];
		fetch_module = Auto_Generate_Numbers[Module_Name.Module_Name == fet_mod.Module_Name];
		mod_short = fetch_module.Module_Short_Name;
		if(fetch_module.Choose_Prefix == "New Prefix")
		{
			num_prefix = fetch_module.Prefix;
		}
		else if(fetch_module.Choose_Prefix == "Company Short Name")
		{
			num_prefix = fetch_module.Company_Short_Name;
		}
		if(fetch_sale_rec.count() == 0)
		{
			so_value = fetch_module.Number_Should_Start_at;
		}
		else
		{
			last_so = getsuffix(getSuffix(fetch_sale_rec.Sale_Order_No,"-"),"-");
			so_value = (last_so.toLong() + 1).trim().leftpad(6).replaceAll(" ","0");
		}
		Order_no = mod_short + "-" + num_prefix + "-" + so_value;
	}
	//Sales Order Contract 27/04/2023
	else if(module_name == "Sales Order Contract")
	{
		fetch_sale_co = Sales_Order[Sale_Order_No != null && Sale_Order_No != "" && Sales_Type == "Contract"] sort by Added_Time desc;
		fet_mod = Module_Master[Module_Name == module_name];
		fetch_module = Auto_Generate_Numbers[Module_Name.Module_Name == fet_mod.Module_Name];
		mod_short = fetch_module.Module_Short_Name;
		if(fetch_module.Choose_Prefix == "New Prefix")
		{
			num_prefix = fetch_module.Prefix;
		}
		else if(fetch_module.Choose_Prefix == "Company Short Name")
		{
			num_prefix = fetch_module.Company_Short_Name;
		}
		if(fetch_sale_co.count() == 0)
		{
			co_value = fetch_module.Number_Should_Start_at;
		}
		else
		{
			last_co = getsuffix(getSuffix(fetch_sale_co.Sale_Order_No,"-"),"-");
			co_value = (last_co.toLong() + 1).trim().leftpad(6).replaceAll(" ","0");
		}
		Order_no = mod_short + "-" + num_prefix + "-" + co_value;
	}
	// for Dispatch Note Format
	else if(module_name == "Purchase Order")
	{
		get_prev_num = Purchase_Order[ID != null && Purchase_Order_No != ""] sort by Purchase_Order_No desc;
		fet_mod = Module_Master[Module_Name == module_name];
		fetch_module = Auto_Generate_Numbers[Module_Name.Module_Name == fet_mod.Module_Name];
		mod_short = fetch_module.Module_Short_Name;
		if(fetch_module.Choose_Prefix == "New Prefix")
		{
			num_prefix = fetch_module.Prefix;
		}
		else if(fetch_module.Choose_Prefix == "Company Short Name")
		{
			num_prefix = fetch_module.Company_Short_Name;
		}
		if(get_prev_num.count() == 0)
		{
			po_value = fetch_module.Number_Should_Start_at;
		}
		else
		{
			last_po = getsuffix(getSuffix(get_prev_num.Purchase_Order_No,"-"),"-");
			po_value = (last_po.toLong() + 1).trim().leftpad(6).replaceAll(" ","0");
		}
		Order_no = mod_short + "-" + num_prefix + "-" + po_value;
	}
	// for work order
	else if(module_name == "Work Order")
	{
		fetch_work_rec = Work_Order[ID != null && Work_Order_No != ""] sort by Work_Order_No desc;
		fet_mod = Module_Master[Module_Name == module_name];
		fetch_module = Auto_Generate_Numbers[Module_Name.Module_Name == fet_mod.Module_Name];
		mod_short = fetch_module.Module_Short_Name;
		if(fetch_module.Choose_Prefix == "New Prefix")
		{
			num_prefix = fetch_module.Prefix;
		}
		else if(fetch_module.Choose_Prefix == "Company Short Name")
		{
			num_prefix = fetch_module.Company_Short_Name;
		}
		if(fetch_work_rec.count() == 0)
		{
			wo_value = fetch_module.Number_Should_Start_at;
		}
		else
		{
			last_wo = getsuffix(getSuffix(fetch_work_rec.Work_Order_No,"-"),"-");
			wo_value = (last_wo.toLong() + 1).trim().leftpad(6).replaceAll(" ","0");
		}
		Order_no = mod_short + "-" + num_prefix + "-" + wo_value;
	}
	// for calibration Gauge No
	else if(module_name == "Gauge No")
	{
		fetch_gaug = Calibration_Master[ID != null && Gauge_No != ""] sort by Gauge_No desc;
		fet_mod = Module_Master[Module_Name == module_name];
		fetch_module = Auto_Generate_Numbers[Module_Name.Module_Name == fet_mod.Module_Name];
		mod_short = fetch_module.Module_Short_Name;
		if(fetch_module.Choose_Prefix == "New Prefix")
		{
			num_prefix = fetch_module.Prefix;
		}
		else if(fetch_module.Choose_Prefix == "Company Short Name")
		{
			num_prefix = fetch_module.Company_Short_Name;
		}
		if(fetch_gaug.count() == 0)
		{
			gaug_value = fetch_module.Number_Should_Start_at;
		}
		else
		{
			last_gaug = getsuffix(getSuffix(fetch_gaug.Gauge_No,"/"),"/");
			gaug_value = (last_gaug.toLong() + 1).trim().leftpad(6).replaceAll(" ","0");
		}
		Order_no = mod_short + "/" + num_prefix + "/" + gaug_value;
	}
	else if(module_name == "Cal Master No")
	{
		fetch_mast = Calibration_Master[ID != null && Cal_Master_No != ""] sort by Cal_Master_No desc;
		fet_mod = Module_Master[Module_Name == module_name];
		fetch_module = Auto_Generate_Numbers[Module_Name.Module_Name == fet_mod.Module_Name];
		mod_short = fetch_module.Module_Short_Name;
		if(fetch_module.Choose_Prefix == "New Prefix")
		{
			num_prefix = fetch_module.Prefix;
		}
		else if(fetch_module.Choose_Prefix == "Company Short Name")
		{
			num_prefix = fetch_module.Company_Short_Name;
		}
		if(fetch_mast.count() == 0)
		{
			mast_value = fetch_module.Number_Should_Start_at;
		}
		else
		{
			last_mast = getsuffix(getSuffix(fetch_mast.Cal_Master_No,"/"),"/");
			mast_value = (last_mast.toLong() + 1).trim().leftpad(6).replaceAll(" ","0");
		}
		Order_no = mod_short + "/" + num_prefix + "/" + mast_value;
	}
  return Order_no;
}
void Calibration.CalibrationSticker(Calibration_History calid)
{
	cid = List();
	itmlis = List();
	for each  rec in calid
	{
		cid.add(rec);
		calbid = Calibration_History[ID == rec.ID];
		itmlis.add(calbid.Item_Name);
	}
	openUrl("#Page:Test_Cal?var_text=" + cid,"new window");
}
class Solution {
    public int maxSubArray(int[] nums) {
        
        int sum=0;
        int max=0;
        for(int i=0;i<nums.length;i++){
            sum+=nums[i];
            if(sum<0){
                sum=0;
            }
            else{
                if(sum>max){
                    max=sum;
                }
            }
        }
        if(max==0)
            max=Integer.MIN_VALUE;
        for(int i=0;i<nums.length;i++){
            if(nums[i]>max)
                max=nums[i];
        }
        return max;

    }
}
void Books.Edit_discpatch_note_actual_invoice(int dnaid)
{
	books_access = thisapp.Books.Get_Books_Access();
	conn_tok = books_access.get("connection");
	org_id = books_access.get("organisation_id");
	disnote_act = Create_Dispatch_Note_Format[ID == input.dnaid];
	fetch_cust = Customers[ID == disnote_act.Customer_Name];
	fet_so = Sales_Order[ID == disnote_act.Sales_Order_No];
	mymap = Map();
	info mymap;
	//mymap.put("customer_id",fetch_cust.Customer_Books_ID);
	item_list = List();
	for each  rec in disnote_act.Product_Details
	{
		if(rec.Individual == false && rec.Actual_Qty > 0)
		{
			fetchitem = Materials[ID == rec.Product_Code];
			line_item_map = Map();
			//line_item_map.put("description",fetchitem.Classification);
			// 		info "Product des" + rec.Product_Description;
			line_item_map.put("item_id",fetchitem.Zoho_Books_ID);
			line_item_map.put("quantity",rec.Actual_Qty);
			item_list.add(line_item_map);
		}
	}
	mymap.put("line_items",item_list);
	update_inv = zoho.books.updateRecord("invoices","60015333461",disnote_act.Draft_Invoice_ID,mymap,conn_tok);
	info update_inv;
	for each  indrec in disnote_act.Product_Details
	{
		if(indrec.Individual == true)
		{
			item_list = List();
			inmymap = Map();
			fetchitem = Materials[ID == indrec.Product_Code];
			line_item_map = Map();
			//line_item_map.put("description",fetchitem.Classification);
			// 		info "Product des" + rec.Product_Description;
			line_item_map.put("item_id",fetchitem.Zoho_Books_ID);
			line_item_map.put("quantity",indrec.Actual_Qty);
			item_list.add(line_item_map);
			inmymap.put("line_items",item_list);
			update_inv_ind = zoho.books.updateRecord("invoices","60015333461",indrec.Zoho_Books_Invoice_ID,inmymap,conn_tok);
			info update_inv_ind;
		}
	}
}
void Books.Cancel_SO_in_ZBooks(int soid)
{
	//Getting authtoken and organisation id
	books_access = thisapp.Books.Get_Books_Access();
	conn_tok = books_access.get("connection");
	org_id = books_access.get("organisation_id");
	//------------------------------------------------------------------------------
	fetch_so = Sales_Order[ID == input.soid];
	info fetch_so.Sale_Order_No;
	mymap = Map();
	stts = "void";
	mymap.put("status",stts);
	//item_list = List();
	/*	for each  rec in fetch_so.Item_Details
	{
		fetchitem = Materials[ID == rec.Part_Description];
		line_item_map = Map();
		line_item_map.put("quantity",rec.Qty);
		//line_item_map.put("rate",rec.Rate);
		lineitemid = rec.zb_line_item_id;
		line_item_map.put("line_item_id",lineitemid);
		item_list.add(line_item_map);
	}*/
	//mymap.put("line_items",item_list);
	//status to changed 
	refno = fetch_so.Sale_Order_No;
	books_id = fetch_so.Zoho_Books_ID;
	//updtstatus = zoho.books.updateRecord("salesorders",org_id,books_id,mymap,conn_tok);
	test_map = Map();
	header_data = Map();
	header_data.put("content-type","application/json");
	void_so = invokeurl
	[
		url :"https://www.zohoapis.in/books/v3/salesorders/" + books_id + "/status/void?organization_id=" + org_id
		type :POST
		parameters:test_map
		headers:header_data
		connection:"books_con"
	];
	res_code = void_so.get("code").toLong();
	log_type = "Failure";
	if(res_code == 0)
	{
		log_type = "Success";
	}
	ins_log = insert into Log_Files
	[
		Added_User=zoho.loginuser
		Module_Name="Sales Order"
		Form_Name="Cancel Sales Order"
		Log_Details=void_so
		Log_Type=log_type
		Reference_NO=refno
	];
}
void Books.Create_Shipment(int shipid)
{
	books_access = thisapp.Books.Get_Books_Access();
	conn_tok = books_access.get("connection");
	org_id = books_access.get("organisation_id");
	fetchdisp = Create_Dispatch_Note_Format[ID == input.shipid];
	fetdispsf = Dispatch_Note_Subform[Create_Dispatch_Note_Plan_RECID == fetchdisp.ID];
	fetinv = Invoice[ID == fetchdisp.Create_Dispatch_Note_Plan_ID];
	fetch_cust = Customers[ID == fetchdisp.Customer_Name];
	fetchso = Sales_Order[ID == fetchdisp.Sales_Order_ID];
	soid = fetchso.Zoho_Books_ID;
	pkgid = fetchdisp.Package_ID;
	ss = soid.tostring();
	//info soid;
	//info pkgid;
	grnmap = Map();
	//mymap.put("delivered_date",fetchdisp.Actual_Date_Time);
	mymap = Map();
	mymap.put("date",fetchdisp.Dispatch_Note_Date.toString("yyyy-MM-dd"));
	mymap.put("delivery_method","By Road");
	mymap.put("tracking_number",fetchdisp.Vehicle_No_dup);
	//mymap.put("delivered_date",fetchdisp.Actual_Date_Time);
	grnmap.put("JSONString",mymap);
	//	info grnmap;
	//	json = Map();
	//	json.put("JSONString",grnmap);
	crtrecord = invokeurl
	[
		url :"https://www.zohoapis.in/inventory/v3/shipmentorders?package_ids=" + pkgid + "&salesorder_id=" + ss + "&organization_id=" + org_id + "&is_delivered=" + true
		type :POST
		parameters:mymap.tostring()
		connection:"zoho_inventory"
	];
	//crtrecord = zoho.books.createRecord("shipmentorders", org_id, grnmap);
	//	info crtrecord;
	rescode = crtrecord.get("code").toLong();
	log_type = "Failure";
	if(rescode == 0)
	{
		log_type = "Success";
		/* 		var = crtrecord.get("shipment_order").get("shipment_id");
		fetchdisp.Shipment_ID=var; */
		//info rescode;
	}
	/* 	ins_log = insert into Log_Files
	[
		Added_User=zoho.loginuser
		Module_Name="shipments-Books"
		Form_Name="Dispatch_Note_Actual_In_Books-shipments"
		Log_Details=crtrecord
		Log_Type=log_type
		Reference_NO=fetchdisp.CDNF_ID
	]; */
}
void Books.SyncVirtualStock(int recid)
{
	books_access = thisapp.Books.Get_Books_Access();
	conn_tok = books_access.get("connection");
	org_id = books_access.get("organisation_id");
	getinventory = Inventory[ID != null];
	//cnt = 0;
	for each  rec in getinventory
	{
		fet_vs = Virtual_Stock[Inventory_Rec_ID == rec.ID];
		//info fet_vs.Part_No.Part_No;
		if(fet_vs.count() == 0)
		{
			// cnt = cnt + 1;
			//  info rec.Part_No.Part_No;
			ins = insert into Virtual_Stock
			[
				Warehouse=rec.Warehouse
				Available_Qty=rec.Available_Qty
				Part_Description=rec.Part_Description
				Sub_Location=rec.Sub_Location
				Location_Name=rec.Location_Name
				Rack_Number=rec.Rack_Number
				Total_Qty=rec.Total_Qty
				Part_No=rec.Part_No
				UOM=rec.UOM
				Category=rec.Category
				Sub_Category=rec.Sub_Category
				Inventory_Rec_ID=rec.ID
				Added_User=zoho.loginuser
			];
		}
		else if(fet_vs.Block_Qty == null || fet_vs.Block_Qty >= 0)
		{
			fet_vs.Available_Qty=rec.Available_Qty;
			fet_vs.Total_Qty=rec.Total_Qty;
			fet_vs.Block_Qty=rec.Block_Qty;
		}
	}
	//info cnt;
}
void Books.invoice_delete_in_books(int Draft_Invoice_ID)
{
	books_access = thisapp.Books.Get_Books_Access();
	conn_tok = books_access.get("connection");
	org_id = books_access.get("organisation_id");
	//new api ur
	del_book = invokeurl
	[
		url :"https://www.zohoapis.in/books/v3/invoices/" + input.Draft_Invoice_ID + "?organization_id=60015333461"
		type :DELETE
		connection:"zoho_inventory"
	];
	// 	del_book = invokeurl
	// 	[
	// 		url :"https://www.zohoapis.in/books/v3/invoices/" + input.Draft_Invoice_ID + "?organization_id=60015333461"
	// 		type :DELETE
	// 		connection:"zoho_inventory"
	// 	];
	info del_book;
}
map Books.Purchase_Order(int var)
{
	//Getting authtoken and organisation id
	books_access = thisapp.Books.Get_Books_Access();
	conn_tok = books_access.get("connection");
	org_id = books_access.get("organisation_id");
	//-------------------------------------------------------------------------
	fetchpo = Purchase_Order[ID == input.var];
	fetchposf = Purchase_Order_Subform[Purchase_Order_ExisID == fetchpo];
	fetchven = Vendor[ID == fetchpo.Vendor_Name];
	//fetchshipp = Shipping_Mode[ID == fetchpo.Shipping_Mode];
	fetchwarehouse = Warehouse[ID == fetchpo.Deliver_To].Warehouse_Books_ID;
	//info fetchwarehouse;
	fettax = GST_Details[ID == fetchpo.Item_Details.Tax];
	fetch_del_schd = Delivery_Schedule[Purchase_Order_Exis_ID == input.var].maximum(Delivery_Date);
	fetch_payment_trms = Payment_Terms[ID == fetchpo.Payment_Terms];
	delivery_date = fetch_del_schd.toString("yyyy-MM-dd");
	//info "fetchpo.Zoho_Books_ID" + fetchpo.Zoho_Books_ID;
	if(fetchpo.Zoho_Books_ID == "" || fetchpo.Zoho_Books_ID == null)
	{
		//info "Insidee";
		pomap = Map();
		pomap.put("customer",fetchven.Vendor_Name);
		pomap.put("purchaseorder_number",fetchpo.Purchase_Order_No);
		pomap.put("vendor_id",fetchven.ZOHO_Books_ID);
		pomap.put("purchaseorder_number",fetchpo.Purchase_Order_No);
		po2 = fetchpo.Purchase_Order_Date.toString("yyyy-MM-dd");
		pomap.put("phone",fetchven.Mobile);
		pomap.put("email",fetchven.Email_ID);
		pomap.put("date",po2);
		pomap.put("cf_payment_terms",fetch_payment_trms.Stages);
		//info url_to_po;
		pomap.put("delivery_date",delivery_date);
		pomap.put("delivery_address",fetchpo.Shipping_Address);
		url_to_po = "https://creatorapp.zoho.in/carrierwheels/erp/#Page:PO_Template?ID=" + var;
		//new_url_to_po = "<a href='https://creatorapp.zoho.in/carrierwheels/erp/#Page:PO_Template?ID=" + var + "' target='_blank' title='Open PO'>Download PO from ERP</a>";
		custom_list = List();
		custom_map = Map();
		custom_map.put("api_name","cf_download_po_from_erp");
		custom_map.put("value",url_to_po);
		custom_list.add(custom_map);
		pomap.put("custom_fields",custom_list);
		//pomap.put("status", "Open");
		item_list = List();
		//info pomap;
		tx_val = 0;
		for each  rec in fetchpo.Item_Details
		{
			fetchitem = Materials[ID == rec.Part_Description];
			//info fetchitem;
			line_item_map = Map();
			//custom_list1 = List();
			//custom_map1 = Map();
			line_item_map.put("name",rec.Part_Description.Part_Description);
			line_item_map.put("item_id",fetchitem.Zoho_Books_ID);
			mfrPartNo = "";
			if(fetchitem.Mfr_Part_No != "")
			{
				mfrPartNo = "Manufacturer Part No: " + fetchitem.Mfr_Part_No;
			}
			myspecs = "";
			if(rec.Specification != null)
			{
				myspecs = "Specifications: " + rec.Specification + "\n";
			}
			myremarks = "";
			if(rec.Remarks != null)
			{
				myremarks = "Remarks: " + rec.Remarks + "\n";
			}
			line_item_map.put("description",myspecs + myremarks + mfrPartNo);
			//line_item_map.put("description",rec.Part_Description.Specification);
			line_item_map.put("quantity",rec.Ordered_Qty);
			line_item_map.put("rate",rec.Rate);
			line_item_map.put("warehouse_name",fetchwarehouse);
			line_item_map.put("tax_id",fettax.Zoho_Books_ID);
			line_item_map.put("tax_percentage",fettax.Total_Rate);
			// 			custom_map1.put("api_name","cf_posubformid");
			// 			custom_map1.put("value",rec.ID);
			// 			custom_list1.add(custom_map1);
			// 			line_item_map.put("custom_fields",custom_list1);
			item_list.add(line_item_map);
			tx_val = tx_val + ifnull(rec.Tax_Value,0.00);
		}
		//info item_list;
		for each  extra in Additional_Charges_Subform[Purchase_Order_Exis_ID == input.var]
		{
			line_item_map = Map();
			line_item_map.put("name",extra.Charge_Name.Zoho_Books_ID);
			line_item_map.put("rate",extra.Rate);
			line_item_map.put("quantity",1);
			line_item_map.put("item_total",extra.Total);
			line_item_map.put("tax_id",extra.Tax.Zoho_Books_ID);
			line_item_map.put("tax_percentage",fettax.Total_Rate);
			item_list.add(line_item_map);
		}
		pomap.put("tax_total",tx_val);
		pomap.put("line_items",item_list);
		post_url = zoho.books.createRecord("purchaseorders",org_id,pomap,conn_tok);
		//info "Url:" +  post_url;
		res_code = post_url.get("code").toLong();
		resp_Map = Map();
		log_type = "Failure";
		//info "rescode " + res_code;
		varconn = API_Connections[Module_Name == "Zoho Books"].Connection;
		if(res_code == 0)
		{
			log_type = "Success";
			books_id = post_url.toMap().get("purchaseorder").toMap().get("purchaseorder_id");
			fetchpo.Zoho_Books_ID=books_id;
			test_map = Map();
			mark_response = invokeurl
			[
				url :"https://www.zohoapis.in/books/v3/purchaseorders/" + books_id + "/status/open?organization_id=" + org_id + ""
				type :POST
				parameters:test_map
				connection:"books_con"
			];
			//old api is commented and new api is in above as per Zoho
			// 			mark_response = invokeurl
			// 			[
			// 				url :"https://www.zohoapis.in/books/v3/purchaseorders/" + books_id + "/status/open?organization_id=" + org_id + ""
			// 				type :POST
			// 				parameters:test_map
			// 				connection:"books_con"
			// 			];
			//info mark_response;
		}
		if(res_code == 0)
		{
			getinventory = zoho.inventory.getRecordsByID("purchaseorders",org_id,books_id);
			get_line_item = getinventory.toMap().get("purchaseorder").toMap().get("line_items");
			for each  lineitem in get_line_item
			{
				lineitemid = lineitem.getjson("line_item_id");
				itemid = lineitem.getjson("item_id");
				itemorder = lineitem.getjson("item_order");
				//array = {"custom_fields":{{"api_name":"cf_posubformid","value":cfposfid}}};
				fetchpo = Purchase_Order[Zoho_Books_ID == books_id];
				//fetchposf = Purchase_Order_Subform[Purchase_Order_ExisID == fetchpo.ID];
				getmat = Materials[Zoho_Books_ID == itemid];
				fetchposf = Purchase_Order_Subform[Purchase_Order_ExisID == fetchpo.ID && S_No == itemorder && Part_No == getmat.ID];
				fetchposf.zb_line_item_id=lineitemid;
				// 			for each  posfrec in fetchposf
				// 			{
				// 				if(posfrec.Part_No == getmat.ID)
				// 				{
				// 					posfrec.zb_line_item_id=lineitemid;
				// 				}
				// 			}
			}
		}
		//Insert into Log Form
		ins_log = insert into Log_Files
		[
			Added_User=zoho.loginuser
			Module_Name="Purchase Order"
			Form_Name="Purchase Order"
			Log_Details=post_url
			Log_Type=log_type
			Reference_NO=fetchpo.Purchase_Order_No
		];
		//sending error log message
		if(log_type == "Failure")
		{
			resp_Map.put("Resp","Failure");
			resp_Map.put("log_msg",post_url.get("message"));
		}
		//status to changed 
		// 	updtstatus = zoho.books.markStatus("purchaseorders",org_id,books_id,"Open",conn_tok);
		// 	info updtstatus;
		//When the log type is failure and rescode is code:57,message:You are not authorized to perform this operation" and try again call the function again after 5 minutes using the below function
		if(res_code == 57 && log_type == "Failure")
		{
			insert into Failure_Functions_re_schedule_form
			[
				Added_User=zoho.loginuser
				Module_name="Purchase Order"
				module_record_id=var
				Schedule_date_time=zoho.currenttime.addMinutes(5)
			]
			//send mail
			sendmail
			[
				from :"erp@carrierwheels.com"
				to :"parthasarathy.m@synprosoft.com"
				subject :"Purchase Order Not pushed to Books" + var
				message :"Purchase Order Not pushed to Books" + var
			]
		}
	}
	return resp_Map;
}
map Books.Get_Books_Access()
{
	ret_mod_name = Company_Details[Sync_Process == "On"];
	auth_tok = ret_mod_name.Connection;
	org_id = ret_mod_name.Organisation_ID;
	ret_map = Map();
	ret_map.put("connection",auth_tok);
	ret_map.put("organisation_id",org_id);
	return ret_map;
}
void Books.Create_Packages(int disid)
{
	books_access = thisapp.Books.Get_Books_Access();
	conn_tok = books_access.get("connection");
	org_id = books_access.get("organisation_id");
	fetchdisp = Create_Dispatch_Note_Format[ID == input.disid];
	fetdispsf = Dispatch_Note_Subform[Create_Dispatch_Note_Plan_RECID == fetchdisp.ID];
	fetch_cust = Customers[ID == fetchdisp.Customer_Name];
	// 	if(fetch_cust.ID != 143536000004625764 && fetch_cust.ID != 143536000004570816 && fetch_cust.ID != 143536000005088666 && fetch_cust.ID != 143536000005117329)
	// 	{
	fetchso = Sales_Order[ID == fetchdisp.Sales_Order_ID];
	soid = fetchso.Zoho_Books_ID;
	ss = soid.tostring();
	grnmap = Map();
	//	grnmap.put("package_number",fetchdisp.CDNF_ID);
	grnmap.put("date",fetchdisp.Dispatch_Note_Date.toString("yyyy-MM-dd"));
	grnmap.put("notes","Total Weight: " + fetchdisp.Total_Weight);
	custom_list = List();
	custom_map = Map();
	custom_map.put("api_name","cf_dispatch_no");
	custom_map.put("value",fetchdisp.CDNF_ID);
	custom_list.add(custom_map);
	grnmap.put("custom_fields",custom_list);
	item_list = List();
	actqtycheck = 0;
	//	info soid;
	for each  rec in fetdispsf
	{
		if(rec.Individual == false && rec.Actual_Qty > 0)
		{
			actqtycheck = 1;
			fetchitem = Materials[ID == rec.Product_Code];
			fet_so = Sales_Order[ID == fetchdisp.Sales_Order_No];
			getsosf = Sale_Order_Subform[Sales_Order_Exis_ID == fet_so.ID && Part_No == rec.Product_Code];
			line_item_map = Map();
			line_item_map.put("so_line_item_id",getsosf.zb_line_item_id);
			if(rec.Actual_Qty > 0)
			{
				line_item_map.put("quantity",rec.Actual_Qty);
			}
			item_list.add(line_item_map);
		}
	}
	info item_list + "Itemlist";
	if(actqtycheck == 1)
	{
		//info item_list;
		grnmap.put("line_items",item_list);
		json = Map();
		json.put("JSONString",grnmap);
		info json;
		crtrecord = invokeurl
		[
			url :"https://www.zohoapis.in/inventory/v3/packages?organization_id=" + org_id + "&salesorder_id=" + ss
			type :POST
			parameters:json
			connection:"zoho_inventory"
		];
		info crtrecord;
		rescode = crtrecord.get("code").toLong();
		log_type = "Failure";
		if(rescode == 0)
		{
			log_type = "Success";
			var = crtrecord.get("package").get("package_id");
			fetchdisp.Package_ID=var;
			info rescode;
		}
		/* 		ins_log = insert into Log_Files
		[
			Added_User=zoho.loginuser
			Module_Name="Packages-Books"
			Form_Name="Dispatch_Note_Actual_In_Books-Packages"
			Log_Details=crtrecord
			Log_Type=log_type
			Reference_NO=fetchdisp.CDNF_ID
		]; */
	}
}
void Books.Create_Cust_in_books(int cust)
{
	//Getting authtoken and organisation id
	books_access = thisapp.Books.Get_Books_Access();
	conn_tok = books_access.get("connection");
	org_id = books_access.get("organisation_id");
	//-------------------------------------------------------------------------
	fet_cust = Customers[ID == input.cust];
	cust_des = Destination[ID == fet_cust.Place_of_Supply];
	cust_gst_trm = GST_Treatment[ID == fet_cust.GST_Treatment];
	curr_code = Currency_Code[ID == fet_cust.Currency_Code];
	web_cnvt = fet_cust.Web.toString();
	web_suff = web_cnvt.getprefix("</a>");
	web_final = web_suff.getsuffix(">");
	custmap = Map();
	custmap.put("contact_type","customer");
	custmap.put("contact_name",fet_cust.Customer_Name);
	custmap.put("company_name",fet_cust.Customer_Name);
	//custmap.put("email",fet_cust.Email_ID);
	custmap.put("mobile",fet_cust.Contact_Number);
	custmap.put("phone",fet_cust.Phone_Number1);
	custmap.put("pan_no",fet_cust.PAN_No);
	custmap.put("gst_no",fet_cust.GST_No);
	custmap.put("website",web_final);
	custmap.put("place_of_contact",cust_des.Short_Name);
	custmap.put("gst_treatment",cust_gst_trm.Link_name);
	custmap.put("currency_id",curr_code.Zoho_Books_ID);
	custmap.put("currency_code",curr_code.Currency_Code);
	cont_list = List();
	primary_cont_pers = Map();
	primary_cont_pers.put("first_name",fet_cust.Customer_Name);
	primary_cont_pers.put("phone",fet_cust.Contact_Number);
	primary_cont_pers.put("email",fet_cust.Email_ID);
	cont_list.add(primary_cont_pers);
	//secndary Contact persons updated.
	if(fet_cust.Contact_Person_Details != null)
	{
		for each  contacts_val in fet_cust.Contact_Person_Details
		{
			cont_pers = Map();
			cont_pers.put("first_name",contacts_val.Contact_Person_Name);
			cont_pers.put("phone",contacts_val.Phone_Number);
			cont_pers.put("email",contacts_val.Email);
			cont_list.add(cont_pers);
		}
	}
	custmap.put("contact_persons",cont_list);
	bill_add = Map();
	shipp_add = Map();
	bill_add.put("address",fet_cust.Billing_Address.address_line_1);
	bill_add.put("street2",fet_cust.Billing_Address.address_line_2);
	bill_add.put("city",fet_cust.Billing_Address.district_city);
	bill_add.put("state",fet_cust.Billing_Address.state_province);
	bill_add.put("zip",fet_cust.Billing_Address.postal_Code);
	bill_add.put("country",fet_cust.Billing_Address.country);
	custmap.put("billing_address",bill_add);
	shipp_add.put("address",fet_cust.Shipping_Address.address_line_1);
	shipp_add.put("street2",fet_cust.Shipping_Address.address_line_2);
	shipp_add.put("city",fet_cust.Shipping_Address.district_city);
	shipp_add.put("state",fet_cust.Shipping_Address.state_province);
	shipp_add.put("zip",fet_cust.Shipping_Address.postal_Code);
	shipp_add.put("country",fet_cust.Shipping_Address.country);
	custmap.put("shipping_address",shipp_add);
	custmap.put("status","active");
	custmap.put("cf_customer_code",fet_cust.Customer_Code);
	//resp = zoho.books.createRecord("contacts",org_id,custmap,conn_tok);
	resp = zoho.books.createRecord("contacts",org_id,custmap);
	info resp;
	res_code = resp.get("code").toLong();
	if(res_code == 0)
	{
		books_id = resp.toMap().get("contact").toMap().get("contact_id");
		fet_cust.Customer_Books_ID=books_id;
		contact_person_list = List();
		contact_person_list = resp.toMap().get("contact").toMap().get("contact_persons").toList();
		for each  contacts_1 in contact_person_list
		{
			contact_rec = contacts_1.toMap();
			contact_Email = contact_rec.get("email");
			contact_person_id = contact_rec.get("contact_person_id");
			if(fet_cust.Email_ID == contact_Email)
			{
				fet_cust.contactPerson_Books_ID=contact_person_id;
			}
			else
			{
				updateContactPersonID = Contact_Person_Subform[Customer_Exis_ID == input.cust && Email == contact_Email];
				if(updateContactPersonID.count() > 0)
				{
					updateContactPersonID.Contact_Person_Books_ID=contact_person_id;
				}
			}
		}
	}
	//Insert into Log Details Report
	// 	ins_log = insert into Log_Files
	// 	[
	// 		Added_User=zoho.loginuser
	// 		Module_Name="Books"
	// 		Form_Name="Customer"
	// 		Log_Details=resp
	// 	];
}
void Invoice.Get_Invoice_from_Books(int recid)
{
	try 
	{
		getdata = Get_Invoice_ID_from_Books[ID == input.recid];
		// 	info getdata;
		zbinvoiceid = getdata.Invoice_Books_ID;
		//info zbinvoiceid;
		books_access = thisapp.Books.Get_Books_Access();
		conn_tok = books_access.get("connection");
		org_id = books_access.get("organisation_id");
		invoice_resp = zoho.books.getRecordsByID("invoices",org_id,zbinvoiceid,conn_tok);
		// 		info "invresp" + invoice_resp;
		invoice_data = invoice_resp.tomap().get("invoice");
		saleno = "";
		vehicleno = "";
		trans = "";
		for each  rec1 in invoice_data.get("custom_fields")
		{
			if(rec1.get("label") == "Sales Order No")
			{
				saleno = rec1.get("value_formatted");
			}
			else if(rec1.get("label") == "Vehicle No")
			{
				vehicleno = rec1.get("value_formatted");
			}
			else if(rec1.get("label") == "Transporter")
			{
				trans = rec1.get("value_formatted");
			}
		}
		// 	info "invdata" + invoice_data;
		custname = invoice_data.get("customer_name");
		invid = invoice_data.get("invoice_id");
		custid = invoice_data.get("customer_id");
		customer_id = Customers[Customer_Books_ID == custid].ID;
		//info customer_id;
		invdate = invoice_data.get("date").todate();
		//info invdate;
		invduedate = invoice_data.get("due_date").todate();
		//info invduedate;
		refno = ifnull(invoice_data.get("reference_number"),"");
		// 	info refno;
		custgst = ifnull(invoice_data.get("gst_no"),"");
		//info custgst;
		invno = invoice_data.get("invoice_number");
		Payment_Terms = invoice_data.get("payment_terms_label");
		payment_terms_id = Payment_Terms[Stages == Payment_Terms];
		if(payment_terms_id.count(ID) == 0)
		{
			pmtterms_map = Map();
			pmtterms_map.put("Stages",Payment_Terms);
			dummy_map33 = Map();
			zoho.creator.createRecord("carrierwheels","erp","Payment_Terms",pmtterms_map,dummy_map33,"vj_creator");
		}
		currency_code = invoice_data.get("currency_code");
		currency_code_id = Currency_Code[Currency_Code == currency_code].ID;
		//info currency_code;
		Place_of_Supply = invoice_data.get("place_of_supply");
		place_of_supply_id = Destination[Short_Name == Place_of_Supply].ID;
		//info Place_of_Supply;
		Source_of_Supply_id = Destination[Short_Name == "UP"].ID;
		//info Source_of_Supply_id;
		billingaddress = invoice_data.tomap().get("billing_address");
		address_line_1 = billingaddress.get("address");
		address_line_2 = billingaddress.get("street2");
		district_city = billingaddress.get("city");
		state_province = billingaddress.get("state");
		postal_code = billingaddress.get("zip");
		country = billingaddress.get("country");
		fax_number = billingaddress.get("fax");
		//info billingaddress;
		shippingaddress = invoice_data.toMap().get("shipping_address");
		address_line_11 = shippingaddress.get("address");
		address_line_12 = shippingaddress.get("street2");
		district_city1 = shippingaddress.get("city");
		state_province1 = shippingaddress.get("state");
		postal_code1 = shippingaddress.get("zip");
		country1 = shippingaddress.get("country");
		itemtotal = invoice_data.get("sub_total");
		taxtotal = invoice_data.get("tax_total");
		grandtotal = invoice_data.get("total");
		gettcs = invoice_data.get("is_tcs_amount_in_percent");
		if(gettcs == "true")
		{
			applytcs = gettcs;
			tcs = invoice_data.get("tcs_tax_id");
			tcs_id = Bill_TCS[Zoho_Books_ID == tcs].ID;
			tcsvalue = invoice_data.get("tcs_amount");
		}
		//get the sales order details
		getsomain = Sales_Order[Sale_Order_No == saleno];
		info getsomain + "somain";
		if(getsomain.count() > 0)
		{
			getsosub = Sale_Order_Subform[Sales_Order_Exis_ID == getsomain.ID];
			cwstat = "Closed";
			sostat = "Closed";
			for each  sosubfrm in Sale_Order_Subform[Sales_Order_Exis_ID == getsomain.ID]
			{
				if(sosubfrm.Balance_Qty > 0)
				{
					cwstat = "Closed Partially";
					sostat = "Open";
				}
			}
			getsomain.CWPL_SO_Status=cwstat;
			getsomain.SO_Status=sostat;
			if(getsomain.Sales_Type == "Contract" && getsomain.CWPL_SO_Status == "Shipped Completed")
			{
				getsomain.CWPL_SO_Status="Closed";
			}
			buyerordno = getsomain.PO_Reference;
			buyrerorddt = getsomain.PO_Date;
			dispatchnoteno = "";
			if(getsomain.Dispatch_Note_No != null)
			{
				//dispatchnoteno = ifnull(getsomain.Dispatch_Note_No.CDNF_ID,"");
			}
			get_cfs = invoice_resp.get("invoice").toMap().get("custom_field_hash");
			dispatchnoteno = get_cfs.get("cf_disp_note_no");
			// 	info getsomain;
			// 	info getsosub;
			dnid = null;
			getdnmain = Create_Dispatch_Note_Format[Sales_Order_No == getsomain.ID];
			info getdnmain.count();
			getdnmain.Draft_Invoice_No=invoice_data.get("invoice_number");
			if(getdnmain.count() > 0)
			{
				dnid = getdnmain.ID;
				VehicleNo = getdnmain.Vehicle_No;
				DriverContactName = getdnmain.Driver_Name;
				DriverContactNo = getdnmain.Driver_Mobile_Number;
				NameofTransport1 = getdnmain.Transport_Name;
				dispatchnoteno = getdnmain.ID;
				dispatchnotedt = getdnmain.Dispatch_Note_Date;
				grno = getdnmain.GR_No;
			}
		}
		// 	sendmail
		// 	[
		// 		from :"erp@carrierwheels.com"
		// 		to :"parthasarathy.m@synprosoft.com"
		// 		subject :"getinvoicefrombooks function " + getdnmain.count() + "--" + getsomain.ID + " recid " + recid
		// 		message :"getinvoicefrombooks function " + getdnmain.count() + "--" + getsomain.ID + " recid " + recid
		// 	]
		str = thisapp.Common.Number_Function_New("Invoice");
		//info str;
		invoiceins = insert into Invoice
		[
			Customer_Name=customer_id
			Invoice_No=invno
			Invoice_Date=invdate
			Invoice_Due_Date=invduedate
			Reference_No=refno
			Invoice_Status="open"
			GST_No=custgst
			Payment_Terms=payment_terms_id.ID
			Currency_Code=currency_code_id
			Place_of_Supply=place_of_supply_id
			Source_of_Supply=Source_of_Supply_id
			Billing_Address.address_line_1=address_line_1
			Billing_Address.address_line_2=address_line_2
			Billing_Address.district_city=district_city
			Billing_Address.state_province=state_province
			Billing_Address.postal_Code=postal_code
			Billing_Address.country=country
			Shipping_Address.address_line_1=address_line_11
			Shipping_Address.address_line_2=address_line_12
			Shipping_Address.district_city=district_city1
			Shipping_Address.state_province=state_province1
			Shipping_Address.postal_Code=postal_code1
			Shipping_Address.country=country1
			Vehicle_no1=vehicleno
			Driver_Contact_Name=DriverContactName
			Driver_Contact_No=DriverContactNo
			Name_of_Transport=trans
			Sale_Order_No=getsomain.ID
			Sale_Order_Date=getsomain.Sale_Order_Date
			Approval_Status="Approved"
			Item_Total=itemtotal
			Tax_Total=taxtotal
			Grand_Total=grandtotal
			Zoho_Books_ID=zbinvoiceid
			Invoice_Type="Domestic Invoice"
			Apply_TCS=applytcs
			TCS=tcs_id
			TCS_Value=tcsvalue
			Create_Dispatch_Note_RECID=dnid
			Buyer_Order_No=buyerordno
			Buyer_Order_Date=buyrerorddt
			Added_User=zoho.loginuser
			Dispatch_Note_No=dispatchnoteno
			Dispatch_Note_Date=dispatchnotedt
			GR_No=grno
			Sales_Type=getsomain.Sales_Type
		];
		if(getsomain.count() > 0)
		{
			solist = List();
			solist.addAll(getsomain.Invoice_No);
			solist.add(invoiceins);
			getsomain.Invoice_No=solist;
			info invoiceins;
			info getsomain.Sale_Order_No;
			info getsomain.Sale_Order_Date;
		}
		sno = 0;
		lineitems = invoice_data.get("line_items");
		taxperc = 0;
		for each  var in lineitems
		{
			taxvalue = 0;
			taxperc = var.getjson("tax_percentage");
			taxvalue = var.getjson("item_total") * taxperc / 100;
			Totalamt = var.getjson("item_total") + taxvalue;
			sno = sno + 1;
			partno = Materials[Zoho_Books_ID == var.getjson("item_id")].ID;
			custpartcode = Sale_Order_Subform[Sales_Order_Exis_ID == getsomain.ID && Part_No == partno].Customer_Part_Code;
			invoicesub = insert into Invoice_Subform
			[
				S_No=sno
				Part_No=Materials[Zoho_Books_ID == var.getjson("item_id")].ID
				Part_Description=Materials[Zoho_Books_ID == var.getJSON("item_id")].ID
				Dispatch_Plan_Date_time=getdnmain.Plan_Date_Time
				Dispatch_Actual_Date_Time=getdnmain.Actual_Date_Time
				Vehicle_Gate_in_Time=getdnmain.In_Time
				Vehicle_Gate_out_time=getdnmain.Out_Time
				HSN_Code=var.getjson("hsn_or_sac")
				UoM=Unit_of_Measurement[UOM == var.getjson("unit")].ID
				Qty=var.getjson("quantity")
				Rate=var.getjson("rate")
				Sub_Total=var.getjson("item_total")
				Tax=GST_Details[Tax_Name == var.getjson("tax_name")].ID
				Tax_Value=taxvalue
				Total=Totalamt
				Invoice_Exist_ID=invoiceins
				Sales_Order_RECID=getsomain.ID
				Added_User=zoho.loginuser
				Customer_Part_Code=custpartcode
			];
		}
		//Update the total Invoice Qty
		totalinvqty = 0;
		totalinvqty = Invoice_Subform[Invoice_Exist_ID == invoiceins].sum(Qty);
		if(totalinvqty > 0)
		{
			getmaininv = Invoice[ID == invoiceins];
			if(getmaininv.count() > 0)
			{
				getmaininv.Total_Invoice_Qty=ifnull(totalinvqty,"");
			}
		}
		//Insert into Log Form
		ins_log = insert into Log_Files
		[
			Added_User=zoho.loginuser
			Module_Name="Invoice"
			Form_Name="GetInvoicefromBooks"
			Log_Details=invoice_resp
			Log_Type="success"
			Reference_NO=getsomain.Sale_Order_No
		];
		//update the E-Way Bill No.
		invoice_resp = zoho.books.getRecordsByID("invoices",org_id,zbinvoiceid,conn_tok);
		//info "invoice resp code " + invoice_resp.get("code") + "---" + zbid;
		ewaybill = invoice_resp.get("invoice").toMap().get("eway_bill_details");
		//info ewaybill;
		sendmail
		[
			from :"erp@carrierwheels.com"
			to :"parthasarathy.m@synprosoft.com"
			subject :"Function Invoice.Getinvoicefrombooks ewaybill details " + zbinvoiceid
			message :"ewaybill " + ewaybill
		]
		if(!isempty(ewaybill))
		{
			bno = ewaybill.get("eway_bill_number");
			if(!isnull(bno))
			{
				getinv = Invoice[Zoho_Books_ID == zbinvoiceid];
				if(getinv.count() > 0)
				{
					getinv.E_Way_Bill_No=ewaybill.get("eway_bill_number");
				}
			}
			if(!isnull(ewaybill.get("eway_bill_date")))
			{
				getinv = Invoice[Zoho_Books_ID == zbinvoiceid];
				if(getinv.count() > 0)
				{
					getinv.E_Way_Bill_Date=ewaybill.get("eway_bill_date").toString("dd-MMM-yyyy");
				}
			}
		}
	}
	catch (e)
	{
		sendmail
		[
			from :"erp@carrierwheels.com"
			to :"parthasarathy.m@synprosoft.com"
			subject :"Invoice.Get Invoice from books try & catch" + zbinvoiceid
			message :e
		]
	}
	//update the Invoice number in Dispatch Note format
	// 	if(getdnmain.count() > 0)
	// 	{
	// 		getdnmain.Invoice_Bill_No=str;
	// 	}
	//update the inventory , Check Inventory Forms
	//lineitemsin = invoice_data.get("line_items");
	// 	for each  rec in lineitemsin
	// 	{
	// 		Part_No_id = Materials[Zoho_Books_ID == rec.getjson("item_id")].ID;
	// 		Part_Description_id = Materials[Zoho_Books_ID == rec.getJSON("item_id")].ID;
	// 		qty = rec.getjson("quantity");
	// 		fetinvent = Inventory[Part_No == Part_No_id];
	// 		//Subtracting available Stock
	// 		if(fetinvent.count() > 0)
	// 		{
	// 			if(fetinvent.Total_Qty < fetinvent.Available_Qty)
	// 			{
	// 				fetinvent.Total_Qty=fetinvent.Available_Qty;
	// 			}
	// 			//blck_quantity = ifnull(fetinvent.Available_Qty,0.0) - ifnull(qty,0.0);
	// 			tot_inv_qty = ifnull(fetinvent.Total_Qty,0.0) - ifnull(qty,0.0);
	// 			//fetinvent.Block_Qty=fetinvent.Block_Qty - ifnull(qty,0.0);
	// 			fetinvent.Total_Qty=tot_inv_qty;
	// 			sendmail
	// 			[
	// 				from :zoho.loginuserid
	// 				to :"parthasarathy.m@certifytechnologies.com"
	// 				subject :"Invoice.Get_Invoice_from_Books"
	// 				message :"Part no " + fetinvent.Part_No.Part_No + "Total Qty " + fetinvent.Total_Qty + "Availabel Qty " + fetinvent.Available_Qty
	// 			]
	// 		}
	//Subtract the quantity in check Inventory form
	// 		fetchkinvent = Check_Inventory[Sales_Order_No == getsomain.ID && Part_No == Part_No_id && Customer_Name == customer_id];
	// 		if(fetchkinvent.count() > 0)
	// 		{
	// 			if(fetchkinvent.Quantity_to_be_Blocked > 0)
	// 			{
	// 				fetchkinvent.Quantity_to_be_Blocked=fetchkinvent.Quantity_to_be_Blocked - ifnull(qty,0.0);
	// 				if(fetchkinvent.Quantity_to_be_Blocked == 0)
	// 				{
	// 					fetchkinvent.Status="Closed";
	// 				}
	// 			}
	// 		}
	//getsosub.Invoiced_so_far_Qty=ifnull(getsosub.Invoiced_so_far_Qty,0.00) + ifnull(qty,0.0);
}
void Books.Create_invoice_individual(int dnaid)
{
	books_access = thisapp.Books.Get_Books_Access();
	conn_tok = books_access.get("connection");
	org_id = books_access.get("organisation_id");
	disnote_act = Create_Dispatch_Note_Format[ID == input.dnaid];
	fetch_cust = Customers[ID == disnote_act.Customer_Name];
	fet_so = Sales_Order[ID == disnote_act.Sales_Order_No];
	plc_of_supply = Destination[Destination == fet_so.Place_of_Supply.Destination].Short_Name;
	for each  rec in disnote_act.Product_Details
	{
		if(rec.Individual == true && rec.Actual_Qty > 0 && isNull(rec.Zoho_Books_Invoice_ID) == True)
		{
			disdate = disnote_act.Dispatch_Note_Date.toString("yyyy-MM-dd");
			sodate = fet_so.Sale_Order_Date.toString("yyyy-MM-dd");
			podate = fet_so.PO_Date.toString("yyyy-MM-dd");
			mymap = Map();
			info mymap;
			mymap.put("customer_id",fetch_cust.Customer_Books_ID);
			info fetch_cust.Customer_Books_ID;
			mymap.put("customer_name",fetch_cust.Contact_Name);
			info fetch_cust.Contact_Name;
			mymap.put("billing_address_id",fetch_cust.Billing_Address_Id);
			mymap.put("shipping_address_id",fetch_cust.Shipping_Address_id);
			//mymap.put("billing_address",disnote_act.Customer_Address);
			// 	info "custaddress" + disnote_act.Customer_Address;
			//	mymap.put("shipping_address",fet_so.Shipping_Address);
			// 	info "Shipping" + fet_so.Shipping_Address;
			mymap.put("place_of_supply",plc_of_supply);
			// 	info "placeofsupply" + plc_of_supply;
			custom_list = List();
			custom_map = Map();
			custom_map.put("api_name","cf_sales_order_no");
			custom_map.put("value",fet_so.Sale_Order_No);
			custom_list.add(custom_map);
			// 	info "Salerderno" + fet_so.Sale_Order_No;
			custom_map = Map();
			custom_map.put("api_name","cf_dispatch_date");
			custom_map.put("value",disdate);
			custom_list.add(custom_map);
			custom_map = Map();
			custom_map.put("api_name","cf_disp_note_no");
			custom_map.put("value",disnote_act.CDNF_ID);
			custom_list.add(custom_map);
			// 	info "dis date" + disnote_act.Dispatch_Note_Date;
			custom_map = Map();
			custom_map.put("api_name","cf_sales_order_date");
			custom_map.put("value",sodate);
			custom_list.add(custom_map);
			info "sale date" + fet_so.Sale_Order_Date;
			vehicle_no = "";
			transpotor = "";
			if(disnote_act.Transport_Type == "One Time")
			{
				vehicle_no = ifNull(disnote_act.Vehicle_No_dup,"");
				transpotor = ifNull(disnote_act.Transporter_Name,"");
			}
			else
			{
				//vehicle_no = ifNull(disnote_act.Vehicle_No_dup,"");
				vehicle_no = ifNull(disnote_act.Vehicle_No.Vehicle_No,"");
				transpotor = ifNull(disnote_act.Transport_Name.Name_of_Transport,"");
			}
			custom_map = Map();
			custom_map.put("api_name","cf_vehicle_no");
			custom_map.put("value",vehicle_no);
			custom_list.add(custom_map);
			// 	info "vehicleno" + disnote_act.Vehicle_No;
			custom_map = Map();
			custom_map.put("api_name","cf_container_no");
			custom_map.put("value",ifnull(disnote_act.Container_No,""));
			custom_list.add(custom_map);
			custom_map = Map();
			custom_map.put("api_name","cf_transporter");
			custom_map.put("value",transpotor);
			custom_list.add(custom_map);
			// 	info "transname" + disnote_act.Transporter_Name;
			custom_map = Map();
			custom_map.put("api_name","cf_gr");
			custom_map.put("value",ifNull(disnote_act.GR_No,""));
			custom_list.add(custom_map);
			// 	info "grno" + disnote_act.GR_No;
			custom_map = Map();
			custom_map.put("api_name","cf_buyer_s_po_no");
			custom_map.put("value",ifNull(fet_so.PO_Reference,""));
			custom_list.add(custom_map);
			custom_map = Map();
			custom_map.put("api_name","cf_buyer_order_date");
			custom_map.put("value",podate);
			custom_list.add(custom_map);
			custom_map = Map();
			custom_map.put("api_name","cf_incoterms");
			custom_map.put("value",ifNull(fet_so.Incoterms1.Incoterms,""));
			custom_list.add(custom_map);
			custom_map = Map();
			custom_map.put("api_name","cf_incoterms_location");
			custom_map.put("value",ifNull(fet_so.Incoterms_Location.Incoterms_Location,""));
			custom_list.add(custom_map);
			mymap.put("custom_fields",custom_list);
			item_list = List();
			fetchitem = Materials[ID == rec.Product_Code];
			line_item_map = Map();
			line_item_map.put("description",fetchitem.Classification);
			// 		info "Product des" + rec.Product_Description;
			line_item_map.put("item_id",fetchitem.Zoho_Books_ID);
			line_item_map.put(" product_type","goods");
			// 		info fetchitem.Zoho_Books_ID;
			line_item_map.put("quantity",rec.Actual_Qty);
			// 		info "ordee qty" + rec.Ordered_Qty;
			fetsosub = Sale_Order_Subform[Sales_Order_Exis_ID == fet_so.ID && Part_No == rec.Product_Code];
			line_item_map.put("rate",fetsosub.Rate);
			// 		info "rate" + rec1.Rate;
			line_item_map.put("tax",fetsosub.Tax);
			// 		info "Tax" + rec1.Tax;
			line_item_map.put("tax_value",fetsosub.Tax_Value);
			line_item_map.put("salesorder_item_id",fetsosub.zb_line_item_id);
			line_sub = List();
			custom_map = Map();
			custom_map.put("label","Customer Part Code");
			custom_map.put("value",ifNull(fetsosub.Customer_Part_Code,""));
			line_sub.add(custom_map);
			custom_map = Map();
			custom_map.put("label","Packing");
			custom_map.put("value",ifNull(fetsosub.Packing_Std.Packaging_Name,""));
			line_sub.add(custom_map);
			line_item_map.put("item_custom_fields",line_sub);
			line_item_map.put("hsn_or_sac",fetsosub.HSN_Code);
			// 		info "taxvalue" + rec1.Tax_Value;
			custom_map = Map();
			custom_map.put("label","UOM");
			custom_map.put("value",ifnull(fetsosub.UoM.UOM,""));
			line_sub.add(custom_map);
			item_list.add(line_item_map);
			mymap.put("line_items",item_list);
			mymap.put("payment_terms_label",ifNull(fetch_cust.Payment_Terms.Stages,""));
			mymap.put("payment_terms",fetch_cust.Exposure_Days);
			info mymap;
			createinbooks = zoho.books.createRecord("invoices","60015333461",mymap,conn_tok);
			info createinbooks;
			retainerno = createinbooks.get("invoice").toMap();
			retinvno = retainerno.get("invoice_number");
			retinvid = retainerno.get("invoice_id");
			rec.Zoho_Books_Invoice_ID=retinvid.toString();
			rescode = createinbooks.get("code").toLong();
			log_type = "Failure";
			if(rescode == 0)
			{
				log_type = "Success";
			}
			ins_log = insert into Log_Files
			[
				Added_User=zoho.loginuser
				Module_Name="Invoice-Books"
				Form_Name="Dispatch_Note_Actual_In_Books-Invoice Individual"
				Log_Details=createinbooks
				Log_Type=log_type
				Reference_NO=disnote_act.CDNF_ID
			];
			//disnote_act.Draft_Invoice_ID=retinvid.toString();
			//	info disnote_act.Draft_Invoice_ID;
			//disnote_act.Draft_Invoice_No=retinvno;
			//info disnote_act.Draft_Invoice_No;
			//fet_so.Books_Invoice_ID=retinvid.toString();
		}
	}
}
void Books.Dispatch_Note_Actual_In_Books(int dnaid)
{
	books_access = thisapp.Books.Get_Books_Access();
	conn_tok = books_access.get("connection");
	org_id = books_access.get("organisation_id");
	disnote_act = Create_Dispatch_Note_Format[ID == input.dnaid];
	fetch_cust = Customers[ID == disnote_act.Customer_Name];
	if(fetch_cust.ID != 143536000004625764 && fetch_cust.ID != 143536000004570816 && fetch_cust.ID != 143536000005088666 && fetch_cust.ID != 143536000005117329)
	{
		fet_so = Sales_Order[ID == disnote_act.Sales_Order_No];
		fettax = GST_Details[ID == fet_so.Item_Details.Tax];
		//	info fet_so;
		plc_of_supply = Destination[Destination == fet_so.Place_of_Supply.Destination].Short_Name;
		disdate = disnote_act.Dispatch_Note_Date.toString("yyyy-MM-dd");
		sodate = fet_so.Sale_Order_Date.toString("yyyy-MM-dd");
		podate = fet_so.PO_Date.toString("yyyy-MM-dd");
		info disdate;
		info sodate;
		mymap = Map();
		//info mymap;
		mymap.put("customer_id",fetch_cust.Customer_Books_ID);
		//	info fetch_cust.Customer_Books_ID;
		mymap.put("customer_name",fetch_cust.Contact_Name);
		//info fetch_cust.Contact_Name;
		mymap.put("billing_address_id",fetch_cust.Billing_Address_Id);
		//info "custaddress" + fetch_cust.Billing_Address_Id;
		//mymap.put("shipping_address_id",fetch_cust.Shipping_Address_id);
		mymap.put("shipping_address",disnote_act.Customer_Address);
		//info "Shipping" + fet_so.Shipping_Address;
		mymap.put("place_of_supply",plc_of_supply);
		// 	info "placeofsupply" + plc_of_supply;
		custom_list = List();
		custom_map = Map();
		custom_map.put("api_name","cf_sales_order_no");
		custom_map.put("value",fet_so.Sale_Order_No);
		custom_list.add(custom_map);
		// 	info "Salerderno" + fet_so.Sale_Order_No;
		custom_map = Map();
		custom_map.put("api_name","cf_dispatch_date");
		custom_map.put("value",disdate);
		custom_list.add(custom_map);
		custom_map = Map();
		custom_map.put("api_name","cf_disp_note_no");
		custom_map.put("value",disnote_act.CDNF_ID);
		custom_list.add(custom_map);
		// 	info "dis date" + disnote_act.Dispatch_Note_Date;
		custom_map = Map();
		custom_map.put("api_name","cf_sales_order_date");
		custom_map.put("value",sodate);
		custom_list.add(custom_map);
		//info "sale date" + fet_so.Sale_Order_Date;
		vehicle_no = "";
		transpotor = "";
		if(disnote_act.Transport_Type == "One Time")
		{
			vehicle_no = ifNull(disnote_act.Vehicle_No_dup,"");
			transpotor = ifNull(disnote_act.Transporter_Name,"");
		}
		else
		{
			//vehicle_no = ifNull(disnote_act.Vehicle_No_dup,"");
			vehicle_no = ifNull(disnote_act.Vehicle_No.Vehicle_No,"");
			transpotor = ifNull(disnote_act.Transport_Name.Name_of_Transport,"");
		}
		custom_map = Map();
		custom_map.put("api_name","cf_vehicle_no");
		custom_map.put("value",vehicle_no);
		custom_list.add(custom_map);
		// 	info "vehicleno" + disnote_act.Vehicle_No;
		custom_map = Map();
		custom_map.put("api_name","cf_container_no");
		custom_map.put("value",ifnull(disnote_act.Container_No,""));
		custom_list.add(custom_map);
		custom_map = Map();
		custom_map.put("api_name","cf_transporter");
		custom_map.put("value",transpotor);
		custom_list.add(custom_map);
		// 	info "transname" + disnote_act.Transporter_Name;
		custom_map = Map();
		custom_map.put("api_name","cf_gr");
		custom_map.put("value",ifNull(disnote_act.GR_No,""));
		custom_list.add(custom_map);
		// 	info "grno" + disnote_act.GR_No;
		custom_map = Map();
		custom_map.put("api_name","cf_buyer_s_po_no");
		custom_map.put("value",ifNull(fet_so.PO_Reference,""));
		custom_list.add(custom_map);
		custom_map = Map();
		custom_map.put("api_name","cf_buyer_order_date");
		custom_map.put("value",podate);
		custom_list.add(custom_map);
		custom_map = Map();
		custom_map.put("api_name","cf_incoterms");
		custom_map.put("value",ifNull(fet_so.Incoterms1.Incoterms,""));
		custom_list.add(custom_map);
		custom_map = Map();
		custom_map.put("api_name","cf_incoterms_location");
		custom_map.put("value",ifNull(fet_so.Incoterms_Location.Incoterms_Location,""));
		custom_list.add(custom_map);
		mymap.put("custom_fields",custom_list);
		item_list = List();
		actqtycheck = 0;
		tx_val = 0;
		for each  rec in disnote_act.Product_Details
		{
			if(rec.Individual == false && rec.Actual_Qty > 0 && isNull(disnote_act.Draft_Invoice_ID) == True)
			{
				actqtycheck = 1;
				fetchitem = Materials[ID == rec.Product_Code];
				line_item_map = Map();
				line_item_map.put("description",fetchitem.Classification);
				// 		info "Product des" + rec.Product_Description;
				line_item_map.put("item_id",fetchitem.Zoho_Books_ID);
				line_item_map.put(" product_type","goods");
				// 		info fetchitem.Zoho_Books_ID;
				line_item_map.put("quantity",rec.Actual_Qty);
				// 		info "ordee qty" + rec.Ordered_Qty;
				fetsosub = Sale_Order_Subform[Sales_Order_Exis_ID == fet_so.ID && Part_No == rec.Product_Code];
				//info fetsosub;
				line_item_map.put("rate",fetsosub.Rate);
				// 		info "rate" + rec1.Rate;
				//line_item_map.put("tax",fetsosub.Tax);
				// 		info "Tax" + rec1.Tax;
				//line_item_map.put("tax_value",fetsosub.Tax_Value);
				line_item_map.put("tax_id",fetsosub.Tax.Zoho_Books_ID);
				line_item_map.put("salesorder_item_id",fetsosub.zb_line_item_id);
				line_sub = List();
				custom_map = Map();
				custom_map.put("label","Customer Part Code");
				custom_map.put("value",ifNull(fetsosub.Customer_Part_Code,""));
				line_sub.add(custom_map);
				custom_map = Map();
				custom_map.put("label","Packing");
				custom_map.put("value",ifNull(fetsosub.Packing_Std.Packaging_Name,""));
				line_sub.add(custom_map);
				line_item_map.put("item_custom_fields",line_sub);
				line_item_map.put("hsn_or_sac",fetsosub.HSN_Code);
				custom_map = Map();
				custom_map.put("label","UOM");
				custom_map.put("value",ifnull(fetsosub.UoM.UOM,""));
				line_sub.add(custom_map);
				item_list.add(line_item_map);
			}
		}
		if(fet_so.Packing_Forwarding > 0)
		{
			fetchitem = Materials[Part_No == "900114"];
			line_item_map = Map();
			line_item_map.put("name",fetchitem.Part_Description);
			line_item_map.put("item_id",fetchitem.Zoho_Books_ID);
			//line_item_map.put("quantity",1);
			line_item_map.put("rate",fet_so.Packing_Forwarding);
			line_item_map.put("tax_name",fettax.Tax_Name);
			line_item_map.put("tax_id",fettax.Zoho_Books_ID);
			line_item_map.put("tax_percentage",fettax.Total_Rate);
			item_list.add(line_item_map);
			tx_val = ifnull(tx_val,0.0) + ifnull(fet_so.PF_Tax_value,0.0);
		}
		mymap.put("tax_total",tx_val);
		if(actqtycheck == 1)
		{
			mymap.put("line_items",item_list);
			mymap.put("payment_terms_label",ifNull(fetch_cust.Payment_Terms.Stages,""));
			mymap.put("payment_terms",fetch_cust.Exposure_Days);
			info mymap;
			createinbooks = zoho.books.createRecord("invoices","60015333461",mymap,conn_tok);
			info createinbooks;
			rescode = createinbooks.get("code").toLong();
			log_type = "Failure";
			if(rescode == 0)
			{
				log_type = "Success";
			}
			ins_log = insert into Log_Files
			[
				Added_User=zoho.loginuser
				Module_Name="Invoice-Books"
				Form_Name="Dispatch_Note_Actual_In_Books-Invoice"
				Log_Details=createinbooks
				Log_Type=log_type
				Reference_NO=disnote_act.CDNF_ID
			];
			retainerno = createinbooks.get("invoice").toMap();
			retinvno = retainerno.get("invoice_number");
			retinvid = retainerno.get("invoice_id");
			retain_upd_map = Map();
			retain_dummyMap = Map();
			//	retain_upd_map.put("Invoice_No",retinvno);
			retain_upd_map.put("invoice_ID",retinvid);
			disnote_act.Draft_Invoice_ID=retinvid.toString();
			//disnote_act.Draft_Invoice_No=retinvno;
			fet_so.Books_Invoice_ID=retinvid.toString();
		}
	}
}
void Books.Create_Sales_Order_in_Books(int soid)
{
	//Getting authtoken and organisation id
	books_access = thisapp.Books.Get_Books_Access();
	conn_tok = books_access.get("connection");
	org_id = books_access.get("organisation_id");
	//info auth_tok;
	//info org_id;
	//------------------------------------------------------------------------------
	fetch_so = Sales_Order[ID == input.soid];
	//info fetch_so;
	fetch_cust = Customers[ID == fetch_so.Customer_Name];
	//info ("fetchcust" + fetch_cust) + "  " + fetch_cust.Customer_Books_ID;
	fetch_delivery_method = Shipping_Mode[ID == fetch_so.Delivery_Mode].Shipping_Mode;
	fetch_warehouse = Warehouse[ID = fetch_so.Warehouse].Warehouse_Name;
	fettax = GST_Details[ID == fetch_so.Item_Details.Tax];
	fetemp = Employee_Details[ID == fetch_so.Created_By].Employee_Name;
	fetch_payment_trms = Payment_Terms[ID == fetch_so.Payment_Terms].Stages;
	shipment_date = fetch_so.Expected_Shipment_Date.toString("yyyy-MM-dd");
	so_date = zoho.currentdate.toString("yyyy-MM-dd");
	curr_code = Currency_Code[ID == fetch_cust.Currency_Code];
	curr_conv = Currency_Conversion[Convert_To == fetch_cust.Currency_Code];
	plc_of_supply = Destination[Destination == fetch_so.Place_of_Supply.Destination].Short_Name;
	fet_gst_trmt = GST_Treatment[ID == fetch_cust.GST_Treatment];
	mymap = Map();
	mymap.put("customer_id",fetch_cust.Customer_Books_ID);
	mymap.put("customer_name",fetch_cust.Contact_Name);
	mymap.put("date",so_date);
	//mymap.put("billing_address",fetch_so.Billing_Address);
	//mymap.put("shipping_address",fetch_so.Shipping_Address);
	mymap.put("shipment_date",shipment_date);
	mymap.put("delivery_method",fetch_delivery_method);
	mymap.put("place_of_supply",plc_of_supply);
	mymap.put("gst_treatment",fet_gst_trmt.Link_name);
	mymap.put("salesorder_number",fetch_so.Sale_Order_No);
	mymap.put("salesperson_name",fetemp);
	mymap.put("currency_id",curr_code.Zoho_Books_ID);
	mymap.put("exchange_rate",curr_conv.Exchange_Rate);
	mymap.put("status","Open");
	url_to_so = "https://creatorapp.zoho.in/carrierwheels/erp/#Page:SO_Print?ID=" + soid;
	custom_list = List();
	custom_map = Map();
	custom_map.put("api_name","cf_download_so_from_erp");
	custom_map.put("value",url_to_so);
	custom_list.add(custom_map);
	mymap.put("custom_fields",custom_list);
	item_list = List();
	tx_val = 0;
	totalqty = 0;
	for each  rec in fetch_so.Item_Details
	{
		fetchitem = Materials[ID == rec.Part_Description];
		line_item_map = Map();
		line_item_map.put("name",rec.Part_Description.Part_Description);
		line_item_map.put("item_id",fetchitem.Zoho_Books_ID);
		//	line_item_map.put("description",rec.Part_Description.Additional_Description);
		line_item_map.put("quantity",rec.Qty);
		totalqty = ifnull(totalqty,0.00) + ifnull(rec.Qty,0.00);
		line_item_map.put("rate",rec.Rate);
		line_item_map.put("warehouse_name",fetch_warehouse);
		//line_item_map.put("tax_type",fettax.Tax_Details.Tax_Type);
		line_item_map.put("tax_name",fettax.Tax_Name);
		line_item_map.put("tax_id",fettax.Zoho_Books_ID);
		line_item_map.put("tax_percentage",fettax.Total_Rate);
		item_list.add(line_item_map);
		tx_val = ifnull(tx_val,0.0) + ifnull(rec.Tax_Value,0.0);
	}
	if(fetch_so.Packing_Forwarding > 0)
	{
		fetchitem = Materials[Part_No == "900114"];
		line_item_map = Map();
		line_item_map.put("name",fetchitem.Part_Description);
		line_item_map.put("item_id",fetchitem.Zoho_Books_ID);
		//line_item_map.put("quantity",1);
		line_item_map.put("rate",fetch_so.Packing_Forwarding);
		line_item_map.put("warehouse_name",fetch_warehouse);
		line_item_map.put("tax_name",fettax.Tax_Name);
		line_item_map.put("tax_id",fettax.Zoho_Books_ID);
		line_item_map.put("tax_percentage",fettax.Total_Rate);
		item_list.add(line_item_map);
		tx_val = ifnull(tx_val,0.0) + ifnull(fetch_so.PF_Tax_value,0.0);
	}
	mymap.put("tax_total",tx_val);
	mymap.put("line_items",item_list);
	post_url = zoho.books.createRecord("salesorders",org_id,mymap,conn_tok);
	info post_url;
	res_code = post_url.get("code").toLong();
	resp_Map = Map();
	log_type = "Failure";
	if(res_code == 0)
	{
		log_type = "Success";
		books_id = post_url.toMap().get("salesorder").toMap().get("salesorder_id");
		fetch_so.Zoho_Books_ID=books_id;
		test_map = Map();
		mark_response = invokeurl
		[
			url :"https://www.zohoapis.in/books/v3/salesorders/" + books_id + "/status/open?organization_id=" + org_id + ""
			type :POST
			parameters:test_map
			connection:"books_con"
		];
	}
	if(res_code == 0)
	{
		getzbook = zoho.books.getRecordsByID("salesorders",org_id,books_id);
		get_line_item = getzbook.toMap().get("salesorder").toMap().get("line_items");
		for each  lineitem in get_line_item
		{
			lineitemid = lineitem.getjson("line_item_id");
			itemid = lineitem.getjson("item_id");
			fetso = Sales_Order[Zoho_Books_ID == books_id];
			fetsosf = Sale_Order_Subform[Sales_Order_Exis_ID == fetso.ID];
			getmat = Materials[Zoho_Books_ID == itemid];
			for each  sosfrec in fetsosf
			{
				if(sosfrec.Part_No == getmat.ID)
				{
					sosfrec.zb_line_item_id=lineitemid;
					fetso.pack_forw_lineitemid=lineitemid;
				}
			}
		}
	}
	ins_log = insert into Log_Files
	[
		Added_User=zoho.loginuser
		Log_Type=log_type
		Module_Name="Books"
		Form_Name="Sales Order"
		Log_Details=post_url
		Reference_NO=fetch_so.Sale_Order_No
	];
	//sending error log message
	if(log_type == "Failure")
	{
		resp_Map.put("Resp","Failure");
		resp_Map.put("log_msg",post_url.get("message"));
	}
	//status to changed 
	updtstatus = zoho.books.markStatus("salesorders",org_id,books_id,"open",conn_tok);
}
for each  rec in Calibration_Master[ID != null && Cal_Due_Date != null]
{
	if(rec.Today != zoho.currentdate)
	{
		rec.Today=zoho.currentdate;
		//info rec.Today;
		info rec.Cal_Due_Date;
		daysleft = daysBetween(rec.Today,rec.Cal_Due_Date);
		rec.Days_Left=daysleft;
		info daysleft;
		if(rec.Days_Left.toNumber() <= 30 && rec.Days_Left.toNumber() > 0)
		{
			rec.Status1="Attention";
		}
		else if(rec.Days_Left.toNumber() > 30)
		{
			rec.Status1="No Issue";
		}
		else if(rec.Days_Left.toNumber() <= 0)
		{
			rec.Status1="Urgent";
		}
	}
}
for each  rec in Calibration_Master[ID != null]
{
	calhist = Calibration_History[Calibration_Master_ID == rec.ID];
	if(calhist.Cal_Due_Date < zoho.currentdate && calhist.Status != "Completed")
	{
		calhist.Status="Overdue";
	}
	if(calhist.Cal_Due_Date >= zoho.currentdate && calhist.Status != "Completed")
	{
		calhist.Status="Due";
	}
	if(rec.Cal_Due_Date < zoho.currentdate)
	{
		rec.Status="Overdue";
	}
	if(rec.Cal_Due_Date >= zoho.currentdate)
	{
		rec.Status="Due";
	}
}
getemail = Email_Template[Template_No == 9];
sub = getemail.Subject_field;
body = getemail.Body;
tab = "<html><style>th,td {padding: 5px;}</style><table border = 1> <th> S.No. </th>  <th>Part No.</th> <th>Part Name  <th>Minimum Quantity</th> <th>Available Quantity</th>";
count = 0;
for each  var in Materials[Material_Item_Type.Material_Type == "General Purchase" && Planning_Procedure == "Consumption-Based Planning"]
{
	stock = Stock_Value[Part_No == var.ID].sum(Stock_Qty);
	if(var.Minimum_Stock != null)
	{
		if(var.Minimum_Stock >= stock)
		{
			count = count + 1;
			tab = tab + "<tr><td>" + count + "</td>";
			tab = tab + "<td>" + var.Part_No + "</td>";
			tab = tab + "<td>" + var.Part_Description + "</td>";
			tab = tab + "<td>" + var.Minimum_Stock + "</td>";
			tab = tab + "<td>" + stock + "</td></tr>";
		}
	}
}
if(count > 1)
{
	info "test";
	tab = tab + "</table></html>";
	body = body.replaceAll("{table}",tab,true);
	sub = sub.replaceAll("<partno>",var.Part_No,true);
	sendmail
	[
		from :"CWPL ERP <erp@carrierwheels.com>"
		to :"pooja.s@synprosoft.com"
		subject :sub
		message :body
	]
}
alllist = List();
alllist = {"png","PNG","JPEG","jpeg","JPG","jpg","GIF","gif","BMP","bmp"};
var = "";
if(input.Attachment != null)
{
	ext = input.Attachment.toList(".").get(input.Attachment.toList(".").size() - 1);
}
rpl = replaceAll(ext," border = \"0\"></img>","");
var = rpl.replaceAll("\"","");
if(!alllist.contains(var) && var != "")
{
	alert "This file type is not accepted. Only PNG,JPG,JPEG,BMP file formats are allowed";
	cancel submit;
}
star

Wed Jan 08 2025 00:16:45 GMT+0000 (Coordinated Universal Time)

@E23CSEU1151

star

Tue Jan 07 2025 18:29:49 GMT+0000 (Coordinated Universal Time)

@E23CSEU1151

star

Tue Jan 07 2025 17:42:25 GMT+0000 (Coordinated Universal Time)

@E23CSEU1151

star

Tue Jan 07 2025 16:30:05 GMT+0000 (Coordinated Universal Time)

@negner

star

Tue Jan 07 2025 15:46:30 GMT+0000 (Coordinated Universal Time)

@Pooja

star

Tue Jan 07 2025 15:44:46 GMT+0000 (Coordinated Universal Time)

@Pooja

star

Tue Jan 07 2025 15:41:21 GMT+0000 (Coordinated Universal Time)

@Pooja

star

Tue Jan 07 2025 15:40:41 GMT+0000 (Coordinated Universal Time)

@Pooja

star

Tue Jan 07 2025 15:38:44 GMT+0000 (Coordinated Universal Time)

@Pooja

star

Tue Jan 07 2025 15:38:25 GMT+0000 (Coordinated Universal Time)

@miskat80

star

Tue Jan 07 2025 15:37:58 GMT+0000 (Coordinated Universal Time)

@Pooja

star

Tue Jan 07 2025 15:37:03 GMT+0000 (Coordinated Universal Time)

@Pooja

star

Tue Jan 07 2025 15:35:04 GMT+0000 (Coordinated Universal Time)

@Pooja

star

Tue Jan 07 2025 15:34:31 GMT+0000 (Coordinated Universal Time)

@Pooja

star

Tue Jan 07 2025 15:33:05 GMT+0000 (Coordinated Universal Time)

@Pooja

star

Tue Jan 07 2025 15:32:27 GMT+0000 (Coordinated Universal Time)

@Pooja

star

Tue Jan 07 2025 15:31:27 GMT+0000 (Coordinated Universal Time)

@Pooja

star

Tue Jan 07 2025 15:30:04 GMT+0000 (Coordinated Universal Time)

@Pooja

star

Tue Jan 07 2025 15:27:54 GMT+0000 (Coordinated Universal Time)

@Pooja

star

Tue Jan 07 2025 15:23:54 GMT+0000 (Coordinated Universal Time)

@Pooja

star

Tue Jan 07 2025 15:22:56 GMT+0000 (Coordinated Universal Time)

@Pooja

star

Tue Jan 07 2025 15:22:16 GMT+0000 (Coordinated Universal Time)

@Pooja

star

Tue Jan 07 2025 15:19:42 GMT+0000 (Coordinated Universal Time)

@Pooja

star

Tue Jan 07 2025 15:17:59 GMT+0000 (Coordinated Universal Time)

@Pooja

star

Tue Jan 07 2025 15:16:47 GMT+0000 (Coordinated Universal Time)

@Pooja

star

Tue Jan 07 2025 15:15:37 GMT+0000 (Coordinated Universal Time)

@Pooja

star

Tue Jan 07 2025 15:15:04 GMT+0000 (Coordinated Universal Time)

@Pooja

star

Tue Jan 07 2025 15:14:21 GMT+0000 (Coordinated Universal Time)

@Pooja

star

Tue Jan 07 2025 15:12:32 GMT+0000 (Coordinated Universal Time)

@Pooja

star

Tue Jan 07 2025 15:11:41 GMT+0000 (Coordinated Universal Time)

@Pooja

star

Tue Jan 07 2025 15:10:49 GMT+0000 (Coordinated Universal Time)

@Pooja

star

Tue Jan 07 2025 15:08:18 GMT+0000 (Coordinated Universal Time)

@Pooja

star

Tue Jan 07 2025 15:06:36 GMT+0000 (Coordinated Universal Time)

@javads

star

Tue Jan 07 2025 15:06:22 GMT+0000 (Coordinated Universal Time)

@Pooja

star

Tue Jan 07 2025 15:05:20 GMT+0000 (Coordinated Universal Time)

@Pooja

star

Tue Jan 07 2025 15:04:42 GMT+0000 (Coordinated Universal Time)

@Pooja

star

Tue Jan 07 2025 15:04:07 GMT+0000 (Coordinated Universal Time)

@Pooja

star

Tue Jan 07 2025 15:03:34 GMT+0000 (Coordinated Universal Time)

@Pooja

star

Tue Jan 07 2025 15:02:52 GMT+0000 (Coordinated Universal Time)

@Pooja

star

Tue Jan 07 2025 15:01:57 GMT+0000 (Coordinated Universal Time)

@Pooja

star

Tue Jan 07 2025 15:01:21 GMT+0000 (Coordinated Universal Time)

@Pooja

star

Tue Jan 07 2025 15:00:43 GMT+0000 (Coordinated Universal Time)

@Pooja

star

Tue Jan 07 2025 14:59:45 GMT+0000 (Coordinated Universal Time)

@Pooja

star

Tue Jan 07 2025 14:59:01 GMT+0000 (Coordinated Universal Time)

@Pooja

star

Tue Jan 07 2025 14:57:47 GMT+0000 (Coordinated Universal Time)

@Pooja

star

Tue Jan 07 2025 14:56:59 GMT+0000 (Coordinated Universal Time)

@Pooja

star

Tue Jan 07 2025 14:54:43 GMT+0000 (Coordinated Universal Time)

@Pooja

star

Tue Jan 07 2025 14:53:55 GMT+0000 (Coordinated Universal Time)

@Pooja

star

Tue Jan 07 2025 14:51:54 GMT+0000 (Coordinated Universal Time)

@Pooja

star

Tue Jan 07 2025 14:44:26 GMT+0000 (Coordinated Universal Time)

@Pooja

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension