Snippets Collections
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;
}
i = 0;
for each  rec in input.Item_Details1
{
	i = i + 1;
	rec.S_No=i;
}
itmname = "";
des = "";
for each  sub in input.Item_Details1
{
	if(sub.S_No == 1)
	{
		itmname = sub.Item_Name;
		des = sub.Description;
	}
}
if(itmname != null)
{
	for each  sub1 in input.Item_Details1
	{
		if(sub1.S_No > 1)
		{
			sub1.Item_Name=itmname;
			sub1.Description=des;
		}
	}
}
// itm = List();
// for each  var in input.Item_Details1
// {
// 	fetcal = Calibration_Master[Item_Name == var.Item_Name.Item_Name].ID.getAll();
// 	itm.add(fetcal);
// 	itm = itm.distinct();
// 	var.Item_Name:ui.add(itm);
// }
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";
}
if(input.Calibration_Master_ID != null)
{
	fetcal = Calibration_Master[ID == input.Calibration_Master_ID];
	input.Item_Name = fetcal.ID;
	input.Gauge_No = fetcal.ID;
	input.Description_Make = fetcal.Description_Make;
	input.Location = fetcal.Location;
	input.Range = fetcal.ID;
	input.Least_Count = fetcal.ID;
	input.Permissable_Error = fetcal.Permissable_Error;
	input.Usable_Range = fetcal.ID;
	input.Internal_External = fetcal.Internal_External;
	input.Calibration_Type = fetcal.Internal_External;
	input.Closed_Date = zoho.currentdate;
	input.Cal_Done_Date = zoho.currentdate;
	input.Cal_Due_Date = fetcal.Cal_Due_Date;
	input.Master_Instrument = fetcal.Master_Instruments;
	input.Checked_By = ifnull(Employee_Details[Employee_Email == "kapilsaini7890ks@gmail.com"].ID,"");
	input.Verification_By = ifnull(Employee_Details[Employee_Email = "manishchaudhary@carrierwheels.com"].ID,"");
	input.Approved_By = ifnull(Employee_Details[Employee_Email = "barkha@carrierwheels.com"].ID,"");
	input.Calibration_By = ifnull(Employee_Details[Employee_Email == zoho.loginuserid].ID,"");
	if(input.Internal_External == "Both")
	{
		enable Calibration_Type;
	}
	else
	{
		disable Calibration_Type;
	}
}
//Hide/Disable
//disable Calibration_Type ;
hide Checked_By;
disable Internal_External;
hide Vendor_Name;
hide Vendor_Address;
hide Calibration_Done;
hide Closed_Date;
disable Item_Details1.S_No;
//disable Calibration_By;
disable Permissable_Error;
disable Usable_Range;
disable Least_Count;
//disable Internal_External;
disable Cal_Due_Date;
disable Item_Name;
disable Gauge_No;
disable Description_Make;
disable Location;
disable Range;
disable Master_Instrument;
//disable Master_Instrument;
disable Vendor_Address;
hide Shipping_Cost;
hide Calibration_Master_ID;
hide Status;
hide Transportation_Details;
hide Vehicle_Photo;
hide Transport_Name;
hide Transporter_Name;
hide Driver_Name;
hide Driver_Mobile;
hide Driver_License_No;
hide Vehicle_Type;
hide Vehicle_No_dup;
hide Vehicle_RC_No;
hide Vehicle_No;
hide GR_RR_No;
hide Calibration_No;
//disable Calibration_Type;
//disable Closed_By;
hide Calibration_History_ID;
hide Approval;
//hide Verification_By;
hide Approved_By;
if(input.Start_Date != null && input.Frequency != null)
{
	mon = input.Frequency;
	input.Cal_Due_Date = input.Start_Date.addDay(mon);
	input.Cal_Due_Date = input.Cal_Due_Date.subDay(1);
	startDate = input.Cal_Due_Date;
	endDate = input.Today.subDay(1);
	input.Days_Left = daysBetween(endDate,startDate);
}
if(input.Start_Date != null && input.Frequency != null)
{
	mon = input.Frequency;
	input.Cal_Due_Date = input.Start_Date.addDay(mon);
	input.Cal_Due_Date = input.Cal_Due_Date.subDay(1);
	startDate = input.Cal_Due_Date;
	endDate = input.Today.subDay(1);
	input.Days_Left = daysBetween(endDate,startDate);
}
rec = 0;
if(isBlank(input.Cal_Master_No.trim()))
{
	rec = 1;
	str1 = thisapp.Common.Number_Function_New("Cal Master No");
	input.Cal_Master_No = str1;
}
if(input.Calibration_Master_ID == null)
{
	info "if";
	input.Obsolete_Status = "Active";
	var = 0;
	if(isBlank(input.Gauge_No.trim()))
	{
		var = 1;
		str = thisapp.Common.Number_Function_New("Gauge No");
		input.Gauge_No = str;
		openUrl("#Form:Alert_Messages?Status=" + "cal" + "&Value=" + input.Gauge_No + "&zc_LoadIn=dialog","same window");
	}
}
if(input.Calibration_Master_ID != null && Revision_Status == "Yes")
{
	fetcal = Calibration_Master[ID == input.ID];
	fetcal.Obsolete_Status="Inactive";
	fetcal.Approval="Pending for Approval";
	openUrl("#Report:All_Calibration_Masters","same window");
}
thisapp.Calibration.CalibrationHistory(input.ID);
// GIN num generation
try 
{
	input.Status = "Open";
	for each  rec in input.Item_Details
	{
		rec.Status=input.Status;
	}
	var = 0;
	if(input.GIN_Number.trim().len() < 1)
	{
		var = 1;
		str = thisapp.Common.Number_Function_New("Goods Issued Note");
		input.GIN_Number = str;
	}
	//as per the advice from Mr.senthil dt 05/1/2024 in stock values form reduce the stockqty based on FIFO method(added time)
	for each  itdrec in input.Item_Details
	{
		getstkvalue = Stock_Value[Part_No == itdrec.Part_No && Stock_Qty > 0] sort by Added_Time asc;
		if(getstkvalue.count() > 0)
		{
			svbalqty = 0;
			svi = 1;
			for each  stokvalrec in getstkvalue
			{
				//Issued Quantiy is less total qty
				if(itdrec.Issued_Quantity <= stokvalrec.Stock_Qty && svi == 1)
				{
					stokvalrec.Stock_Qty=ifnull(itdrec.Qty_after_Issued,0.0);
					stokvalrec.Stock_Value=ifnull(itdrec.Rate,0.0) * ifnull(itdrec.Qty_after_Issued,0.0);
					stokvalrec.Inventory_Qty=ifnull(itdrec.Qty_after_Issued,0.0);
				}
				//Issued Quantity is more total qty
				else if(itdrec.Issued_Quantity > stokvalrec.Stock_Qty && svi == 1)
				{
					svbalqty = ifnull(itdrec.Issued_Quantity,0.0) - ifnull(stokvalrec.Stock_Qty,0.0);
					stokvalrec.Stock_Qty=0;
					stokvalrec.Stock_Value=0;
					stokvalrec.Inventory_Qty=0;
				}
				//for first time it should not get inside the loop 
				if(svbalqty > 0 && svi > 1)
				{
					//Balance Qty is less 
					if(svbalqty <= stokvalrec.Stock_Qty)
					{
						stokvalrec.Stock_Qty=ifnull(stokvalrec.Stock_Qty,0.0) - ifnull(svbalqty,0.0);
						stokvalrec.Stock_Value=ifnull(stokvalrec.Unit_Price,0.0) * ifnull(stokvalrec.Stock_Qty,0.0);
						stokvalrec.Inventory_Qty=ifnull(stokvalrec.Inventory_Qty,0.0) - ifnull(svbalqty,0.0);
						svbalqty = 0;
					}
					//Balance Qty is More
					else if(svbalqty >= stokvalrec.Stock_Qty)
					{
						svbalqty = ifnull(svbalqty,0.0) - ifnull(stokvalrec.Stock_Qty,0.0);
						stokvalrec.Stock_Qty=0;
						stokvalrec.Stock_Value=0;
						stokvalrec.Inventory_Qty=0;
					}
				}
				if(svbalqty == 0)
				{
					info "before break";
					break;
				}
				svi = svi + 1;
			}
		}
		else if(getstkvalue.count() == 0)
		{
			insert into Stock_Value
			[
				Added_User=zoho.loginuser
				Part_No=itdrec.Part_No
				Part_Description=itdrec.Part_Description
				Specification=itdrec.Specification
				Stock_Qty=ifnull(itdrec.Qty_after_Issued,0.0)
				Unit_Price=ifnull(itdrec.Rate,0.00)
				Stock_Value=ifnull(itdrec.Rate,0.00) * ifnull(itdrec.Qty_after_Issued,0.00)
				Inventory_Qty=ifnull(itdrec.Qty_after_Issued,0.0)
			]
		}
	}
	// //insert the part no if not available in stock value form.the below comment and new code is above on 5/1/2024
	/*for each  stkvalrec in input.Item_Details
{
	getinvent = Inventory[Part_No == stkvalrec.Part_No && Total_Qty > 0];
	if(getinvent.count() > 0)
	{
		fet_stockvalue = Stock_Value[Part_No == stkvalrec.Part_No && Unit_Price == stkvalrec.Rate];
		if(fet_stockvalue.count() == 0)
		{
			insert into Stock_Value
			[
				Added_User=zoho.loginuser
				Part_No=stkvalrec.Part_No
				Part_Description=stkvalrec.Part_Description
				Specification=stkvalrec.Specification
				Location_Name=getinvent.Location_Name
				Sub_Location=getinvent.Sub_Location
				Rack_Number=getinvent.Rack_Number
				Warehouse=getinvent.Warehouse
				Stock_Qty=ifnull(stkvalrec.Qty_after_Issued,0.0)
				Unit_Price=ifnull(stkvalrec.Rate,0.00)
				Stock_Value=ifnull(stkvalrec.Rate,0.00) * ifnull(stkvalrec.Qty_after_Issued,0.00)
				Inventory_Qty=ifnull(stkvalrec.Qty_after_Issued,0.0)
			]
		}
		else if(fet_stockvalue.count() > 0)
		{
			fet_stockvalue = Stock_Value[Part_No == stkvalrec.Part_No && Unit_Price == stkvalrec.Rate];
			if(fet_stockvalue.Stock_Qty > 0)
			{
				fet_stockvalue.Stock_Qty=ifnull(fet_stockvalue.Stock_Qty,0.0) - ifnull(stkvalrec.Issued_Quantity,0.0);
				fet_stockvalue.Stock_Value=ifnull(stkvalrec.Rate,0.0) * ifnull(fet_stockvalue.Stock_Qty,0.0);
				fet_stockvalue.Inventory_Qty=ifnull(fet_stockvalue.Stock_Qty,0.0);
			}
			else
			{
				fet_stockvalue.Stock_Qty=ifnull(stkvalrec.Qty_after_Issued,0.0);
				fet_stockvalue.Stock_Value=ifnull(stkvalrec.Rate,0.0) * ifnull(stkvalrec.Qty_after_Issued,0.0);
				fet_stockvalue.Inventory_Qty=ifnull(stkvalrec.Qty_after_Issued,0.0);
			}
		}
	}
}*/
	//
	if(input.Form_Mode == "GIN against WO")
	{
		iss_qty = 0;
		ava_qty = 0;
		bal_qty = 0;
		for each  wovar in input.Item_Details
		{
			getinv = Inventory[Part_No == wovar.Part_No && Location_Name.Location__Name == "Production WIP" && Sub_Location.Sub_Location == "Paint Shop"];
			getin = Inventory[Part_No == wovar.Part_No && Location_Name.Location__Name != "Production WIP" && Total_Qty > 0] sort by Total_Qty desc;
			// 			sendmail
			// 			[
			// 				from :zoho.loginuserid
			// 				to :"pooja.s@synprosoft.com","parthasarathy.m@synprosoft.com"
			// 				subject :"GIN Successful form submission - getinV"
			// 				message :"Part No " + getin.Part_No.Part_No + "PRD WIP TOT QTY-" + getinv.Total_Qty + "PRD WIP AVL QTY-" + getinv.Available_Qty + "PRD WIP BLK QTY-" + getinv.Block_Qty + "ID-" + getin.ID + "getinv insert Count-" + getinv.count() + "NOPRDWIP TQ " + getin.Total_Qty + "noprdwip aq " + getin.Available_Qty + "noprd blkqty " + getin.Block_Qty
			// 			]
			if(getin.count() > 0)
			{
				//Block is greater than Issue qty
				if(getin.Block_Qty >= wovar.Issued_Quantity && getin.Block_Qty > 0)
				{
					getin.Block_Qty=ifnull(getin.Block_Qty,0) - ifnull(wovar.Issued_Quantity,0);
					getin.Total_Qty=ifnull(getin.Total_Qty,0) - ifnull(wovar.Issued_Quantity,0);
				}
				else if(getin.Block_Qty < wovar.Issued_Quantity && getin.Block_Qty > 0)
				{
					bal = ifnull(wovar.Issued_Quantity,0) - ifnull(wovar.Block_Qty,0);
					blk = ifnull(wovar.Block_Qty,0);
					getin.Available_Qty=ifnull(getin.Available_Qty,0) - bal;
					getin.Total_Qty=ifnull(getin.Total_Qty,0) - ifnull(wovar.Issued_Quantity,0);
					getin.Block_Qty=0;
				}
				else if(getin.Block_Qty == 0 || getin.Block_Qty == null)
				{
					if(getin.Available_Qty > 0 && getin.Available_Qty >= wovar.Issued_Quantity)
					{
						getin.Available_Qty=ifnull(getin.Available_Qty,0) - wovar.Issued_Quantity;
						getin.Total_Qty=ifnull(getin.Total_Qty,0) - ifnull(wovar.Issued_Quantity,0);
					}
					if(getin.Available_Qty > 0 && getin.Available_Qty < wovar.Issued_Quantity)
					{
						getin.Available_Qty=wovar.Issued_Quantity - ifnull(getin.Available_Qty,0);
						getin.Total_Qty=ifnull(wovar.Issued_Quantity,0) - ifnull(getin.Total_Qty,0);
					}
				}
			}
			if(getinv.count() == 0)
			{
				bal = 0;
				if(wovar.Issued_Quantity > wovar.Block_Qty && getin.Available_Qty > 0)
				{
					bal = ifnull(wovar.Issued_Quantity,0) - ifnull(wovar.Block_Qty,0);
					getin.Block_Qty=0;
					getin.Available_Qty=ifnull(getin.Available_Qty,0) - bal;
					getin.Total_Qty=ifnull(getin.Available_Qty,0);
				}
				if(wovar.Issued_Quantity > wovar.Required_Quantity)
				{
					blk = ifnull(wovar.Issued_Quantity,0) - ifnull(wovar.Required_Quantity,0);
					ins = insert into Inventory
					[
						Part_Description=wovar.Part_Description
						Part_No=wovar.Part_No
						Total_Qty=wovar.Required_Quantity
						Available_Qty=wovar.Issued_Quantity
						Block_Qty=blk
						UOM=wovar.Unit_of_Measurement
						Location_Name=143536000004382382
						Sub_Location=143536000004382454
						Added_User=zoho.loginuser
					];
				}
				else if(wovar.Issued_Quantity == wovar.Required_Quantity)
				{
					ins1 = insert into Inventory
					[
						Part_Description=wovar.Part_Description
						Part_No=wovar.Part_No
						Total_Qty=wovar.Required_Quantity
						Available_Qty=wovar.Issued_Quantity
						Block_Qty=0
						UOM=wovar.Unit_of_Measurement
						Location_Name=143536000004382382
						Sub_Location=143536000004382454
						Added_User=zoho.loginuser
					];
				}
				else if(wovar.Issued_Quantity < wovar.Required_Quantity)
				{
					ins2 = insert into Inventory
					[
						Part_Description=wovar.Part_Description
						Part_No=wovar.Part_No
						Total_Qty=wovar.Required_Quantity
						Available_Qty=wovar.Issued_Quantity
						Block_Qty=wovar.Balance_Quantity
						UOM=wovar.Unit_of_Measurement
						Location_Name=143536000004382382
						Sub_Location=143536000004382454
						Added_User=zoho.loginuser
					];
				}
			}
			else if(getinv.count() > 0)
			{
				sendmail
				[
					from :zoho.loginuserid
					to :"pooja.s@synprosoft.com"
					subject :"GIN Successful form submission - getinV"
					message :"Part No " + getin.Part_No.Part_No + "PRD WIP TOT QTY-" + getinv.Total_Qty + "PRD WIP AVL QTY-" + getinv.Available_Qty + "PRD WIP BLK QTY-" + getinv.Block_Qty + "ID-" + getin.ID + "getinv insert Count-" + getinv.count()
				]
				if(wovar.Required_Quantity == wovar.Issued_Quantity)
				{
					getinv.Available_Qty=ifnull(getinv.Available_Qty,0) + ifnull(wovar.Issued_Quantity,0);
					getinv.Total_Qty=ifnull(getinv.Total_Qty,0) + ifnull(wovar.Issued_Quantity,0);
				}
				//When Issued Qty is Greater than Reqquired Qty
				else if(wovar.Issued_Quantity > wovar.Required_Quantity)
				{
					// 					blk = ifnull(wovar.Issued_Quantity,0) - ifnull(wovar.Required_Quantity,0);
					// 					getinv.Total_Qty=ifnull(getinv.Total_Qty,0) + ifnull(wovar.Required_Quantity,0);
					// 					getinv.Available_Qty=ifnull(getinv.Available_Qty,0) + ifnull(wovar.Issued_Quantity,0);
					// 					getinv.Block_Qty=ifnull(getinv.Block_Qty,0) + blk;
					blk = ifnull(wovar.Issued_Quantity,0) + ifnull(wovar.Required_Quantity,0);
					getinv.Total_Qty=ifnull(getinv.Total_Qty,0) + blk;
					getinv.Available_Qty=ifnull(getinv.Available_Qty,0) + ifnull(wovar.Issued_Quantity,0);
					getinv.Block_Qty=ifnull(getinv.Block_Qty,0) + ifnull(wovar.Required_Quantity,0);
				}
				else if(wovar.Issued_Quantity < wovar.Required_Quantity)
				{
					getinv.Total_Qty=ifnull(getinv.Total_Qty,0) + ifnull(wovar.Required_Quantity,0);
					getinv.Available_Qty=ifnull(getinv.Available_Qty,0) + ifnull(wovar.Issued_Quantity,0);
					getinv.Block_Qty=ifnull(getinv.Block_Qty,0) + ifnull(wovar.Balance_Quantity,0);
				}
			}
			mat_isf_qty = ifnull(wovar.Issued_Quantity,0) + ifnull(wovar.Quantity_issued_so_far,0);
			fetch_mat_subform = Material_Request_Subform[ID == wovar.Material_Request_Subform_lu && Part_Description == wovar.Part_Description];
			fetch_mat_subform.Quantity_issued_so_far=mat_isf_qty;
			blnc_qty = ifnull(wovar.Balance_Quantity,0.0);
			fetch_mat_subform.Balance_Qty=blnc_qty;
			bat_no_list = List();
			iss_qty = wovar.Issued_Quantity;
			bat = Stock_Batch[Part_No == wovar.Part_No && Part_Description == wovar.Part_Description && Status != "Issued" && Location == wovar.Location && Warehouse == input.Warehouse && Sub_Location == wovar.Sub_Location && Racks_Bins == wovar.Racks_Bins];
			for each  i1 in bat
			{
				bat_no = Stock_Batch[ID == i1].Batch_No;
				bat_no_list.add(bat_no);
			}
			i = 0;
			for each  no in bat_no_list
			{
				batching = Stock_Batch[Batch_No == no];
				ava_qty = batching.Available_Quantity;
				i = i + 1;
				if(i == 1 && iss_qty > ava_qty)
				{
					batching.Status="Issued";
					batching.Issued_Qty_So_far=iss_qty;
					batching.Available_Quantity=0;
					bal_qty = iss_qty - ava_qty;
				}
				else if(i == 1 && iss_qty < ava_qty)
				{
					batching.Status="Partially Issued";
					batching.Issued_Qty_So_far=iss_qty;
					batching.Available_Quantity=ava_qty - iss_qty;
					bal_qty = 0;
				}
				else if(i == 1 && iss_qty == ava_qty)
				{
					batching.Status="Issued";
					batching.Issued_Qty_So_far=iss_qty;
					batching.Available_Quantity=0;
					bal_qty = 0;
				}
				else if(i > 1 && bal_qty > ava_qty)
				{
					batching.Status="Issued";
					batching.Issued_Qty_So_far=iss_qty;
					batching.Available_Quantity=0;
					bal_qty = bal_qty - ava_qty;
				}
				else if(i > 1 && bal_qty < ava_qty)
				{
					batching.Status="Partially Issued";
					batching.Issued_Qty_So_far=iss_qty;
					batching.Available_Quantity=ava_qty - bal_qty;
					bal_qty = 0;
				}
				else if(i > 1 && bal_qty == ava_qty)
				{
					batching.Status="Issued";
					batching.Issued_Qty_So_far=bal_qty;
					batching.Available_Quantity=0;
					bal_qty = 0;
				}
			}
			// Updating Stock value
			temp_issued_qty = rec.Issued_Quantity;
			ival = 0;
			bal = 0;
			if(wovar.Balance_Quantity < 1)
			{
				fetch_mat_subform.Status="Issued";
			}
			else
			{
				fetch_mat_subform.Status="Partially Issued";
			}
		}
	}
	//above closing parenthesis is for gin from work order if contidion.
	emptylist = List();
	if(Material_Request_RECID != emptylist || Material_Request_RECID != null && input.Form_Mode == "GIN against MRQ")
	{
		fet_Mrq_sts = Material_Request[ID == input.Material_Request_RECID];
		//For GIN Validtaions
		for each  rec in input.Item_Details
		{
			if(rec.Issued_Quantity != null || rec.Issued_Quantity != 0)
			{
				//Updating qty issued so far
				mat_isf_qty = ifnull(rec.Issued_Quantity,0) + ifnull(rec.Quantity_issued_so_far,0);
				//Updating Quantity_issued_so_far in Material Request Subform
				fetch_mat_subform = Material_Request_Subform[ID == rec.Material_Request_Subform_lu && Part_Description == rec.Part_Description];
				fetch_mat_subform.Quantity_issued_so_far=mat_isf_qty;
				//Updating blnc qty
				blnc_qty = ifnull(rec.Balance_Quantity,0.0);
				fetch_mat_subform.Balance_Qty=blnc_qty;

				//below is new code to handle when items are in multiple times with different places.
				getinventory = Inventory[Part_No == rec.Part_No] sort by Total_Qty desc;
				info getinventory;
				if(getinventory.count() > 0)
				{
					balqty = 0;
					i = 1;
					for each  inventrec in getinventory
					{
						info balqty;
						info i;
						//Issued Quantiy is less total qty
						if(rec.Issued_Quantity <= inventrec.Total_Qty && i == 1)
						{
							info "issued qty is less than total qty";
							inventrec.Total_Qty=ifnull(inventrec.Total_Qty,0.0) - ifnull(rec.Issued_Quantity,0.0);
							inventrec.Available_Qty=ifnull(inventrec.Available_Qty,0.0) - ifnull(rec.Issued_Quantity,0.0);
						}
						//Issued Quantity is more total qty
						else if(rec.Issued_Quantity > inventrec.Total_Qty && i == 1)
						{
							info "issued qty is more than total qty";
							balqty = ifnull(rec.Issued_Quantity,0.0) - ifnull(inventrec.Total_Qty,0.0);
							inventrec.Total_Qty=0;
							inventrec.Available_Qty=0;
						}
						//for first time it should not get inside the loop 
						if(balqty > 0 && i > 1)
						{
							info "balaance qty is more than zero";
							//Balance Qty is less 
							if(balqty <= inventrec.Total_Qty)
							{
								info "balance qty is less than total qty";
								inventrec.Total_Qty=ifnull(inventrec.Total_Qty,0.0) - ifnull(balqty,0.0);
								inventrec.Available_Qty=ifnull(inventrec.Available_Qty,0.0) - ifnull(balqty,0.0);
								balqty = 0;
							}
							//Balance Qty is More
							else if(balqty >= inventrec.Total_Qty)
							{
								info "balance qty is greater than total qty";
								balqty = ifnull(balqty,0.0) - ifnull(inventrec.Total_Qty,0.0);
								inventrec.Total_Qty=0;
								inventrec.Available_Qty=0;
							}
						}
						if(balqty == 0)
						{
							info "before break";
							break;
						}
						i = i + 1;
					}
				}
				//--
				//Subracting stock-batch
				// Basic
				/*bat = Stock_Batch[Part_No == rec.Part_No && Part_Description == rec.Part_Description && Status != "Issued" && Batch_No == rec.Batch_No.Batch_No];
			if(bat.Available_Quantity == rec.Issued_Quantity)
			{
				bat.Status="Issued";
			}
			if(bat.Available_Quantity > rec.Issued_Quantity)
			{
				bat.Status="Partially Issued";
				bat.Available_Quantity=bat.Available_Quantity - rec.Issued_Quantity;
			}*/
				// Advanced
				iss_qty = 0;
				ava_qty = 0;
				bal_qty = 0;
				//	if(rec.Specification == null || rec.Specification == "")
				//		{
				bat = Stock_Batch[Part_No == rec.Part_No && Part_Description == rec.Part_Description && Status != "Issued" && Location == rec.Location && Warehouse == input.Warehouse && Sub_Location == rec.Sub_Location && Racks_Bins == rec.Racks_Bins];
				//		}
				//		else
				//		{
				//			bat = Stock_Batch[Part_No == rec.Part_No && Part_Description == rec.Part_Description && Specification == rec.Specification && Status != "Issued" && Location == rec.Location && Warehouse == input.Warehouse && Sub_Location == rec.Sub_Location && Racks_Bins == rec.Racks_Bins];
				//		}
				bat_no_list = List();
				iss_qty = rec.Issued_Quantity;
				for each  i1 in bat
				{
					bat_no = Stock_Batch[ID == i1].Batch_No;
					bat_no_list.add(bat_no);
				}
				info bat_no_list;
				i = 0;
				for each  no in bat_no_list
				{
					batching = Stock_Batch[Batch_No == no];
					ava_qty = batching.Available_Quantity;
					i = i + 1;
					if(i == 1 && iss_qty > ava_qty)
					{
						batching.Status="Issued";
						batching.Issued_Qty_So_far=iss_qty;
						batching.Available_Quantity=0;
						bal_qty = iss_qty - ava_qty;
					}
					else if(i == 1 && iss_qty < ava_qty)
					{
						batching.Status="Partially Issued";
						batching.Issued_Qty_So_far=iss_qty;
						batching.Available_Quantity=ava_qty - iss_qty;
						bal_qty = 0;
					}
					else if(i == 1 && iss_qty == ava_qty)
					{
						batching.Status="Issued";
						batching.Issued_Qty_So_far=iss_qty;
						batching.Available_Quantity=0;
						bal_qty = 0;
					}
					else if(i > 1 && bal_qty > ava_qty)
					{
						batching.Status="Issued";
						batching.Issued_Qty_So_far=iss_qty;
						batching.Available_Quantity=0;
						bal_qty = bal_qty - ava_qty;
					}
					else if(i > 1 && bal_qty < ava_qty)
					{
						batching.Status="Partially Issued";
						batching.Issued_Qty_So_far=iss_qty;
						batching.Available_Quantity=ava_qty - bal_qty;
						bal_qty = 0;
					}
					else if(i > 1 && bal_qty == ava_qty)
					{
						batching.Status="Issued";
						batching.Issued_Qty_So_far=bal_qty;
						batching.Available_Quantity=0;
						bal_qty = 0;
					}
				}
				// Updating Stock value
				temp_issued_qty = rec.Issued_Quantity;
				ival = 0;
				bal = 0;

			}
			if(rec.Balance_Quantity == null || rec.Balance_Quantity == 0)
			{
				fetch_mat_subform.Status="Issued";
			}
			else
			{
				fetch_mat_subform.Status="Partially Issued";
			}
		}
	}
	else if(input.Form_Mode == "Direct GIN" || input.Form_Mode == "")
	{
		str = thisapp.Common.Number_Function_New("Material Request");
		gin_without_mrq = insert into Material_Request
		[
			Request_Date=zoho.currentdate
			Added_User=zoho.loginuser
			Request_Raised_By=input.Issued_By
			Warehouse=input.Warehouse
			Material_Type=input.Material_Request_Type
			Material_Request_No=str
			MR_Status="MRQ from GIN"
		];
		input.Material_Request_RECID = gin_without_mrq;
		Statusw = "";
		Balance_Qtyw = input.Item_Details.Balance_Quantity;
		if(Balance_Qtyw < 1)
		{
			Statusw = "Issued";
		}
		else
		{
			Statusw = "Partially Issued";
		}
		for each  recmrsf in input.Item_Details
		{
			insert into Material_Request_Subform
			[
				Part_Description=recmrsf.Part_No
				Part_No=recmrsf.Part_Description
				Added_User=zoho.loginuser
				Material_Type=recmrsf.Material_Type
				Department=input.Issued_Empolyee_Department
				UoM=recmrsf.Unit_of_Measurement
				Specification=recmrsf.Specification
				Stock_Qty=recmrsf.Stock_Quantity
				Required_Qty=recmrsf.Required_Quantity
				Balance_Qty=recmrsf.Balance_Quantity
				Status=Statusw
				Quantity_issued_so_far=recmrsf.Issued_Quantity
				Material_Req_Exis_ID=gin_without_mrq
			]
		}
		//For GIN Validtaions
		for each  rec in input.Item_Details
		{
			if(rec.Issued_Quantity != null || rec.Issued_Quantity != 0)
			{
				rec.Material_Request_No=str;

				//below is new code to handle when items are in multiple times with different places.
				getinventory = Inventory[Part_No == rec.Part_No] sort by Total_Qty desc;
				info getinventory;
				if(getinventory.count() > 0)
				{

					balqty = 0;
					i = 1;
					for each  inventrec in getinventory
					{
						//Issued Quantiy is less total qty
						if(rec.Issued_Quantity <= inventrec.Total_Qty && i == 1)
						{
							inventrec.Total_Qty=ifnull(inventrec.Total_Qty,0.0) - ifnull(rec.Issued_Quantity,0.0);
							inventrec.Available_Qty=ifnull(inventrec.Available_Qty,0.0) - ifnull(rec.Issued_Quantity,0.0);
						}
						//Issued Quantity is more total qty
						else if(rec.Issued_Quantity > inventrec.Total_Qty && i == 1)
						{
							balqty = ifnull(rec.Issued_Quantity,0.0) - ifnull(inventrec.Total_Qty,0.0);
							inventrec.Total_Qty=0;
							inventrec.Available_Qty=0;
						}
						//for first time it should not get inside the loop 
						if(balqty > 0 && i > 1)
						{
							info "balaance qty is more than zero";
							//Balance Qty is less 
							if(balqty <= inventrec.Total_Qty)
							{
								info "balance qty is less than total qty";
								inventrec.Total_Qty=ifnull(inventrec.Total_Qty,0.0) - ifnull(balqty,0.0);
								inventrec.Available_Qty=ifnull(inventrec.Available_Qty,0.0) - ifnull(balqty,0.0);
								balqty = 0;
							}
							//Balance Qty is More
							else if(balqty >= inventrec.Total_Qty)
							{
								info "balance qty is greater than total qty";
								balqty = ifnull(balqty,0.0) - ifnull(inventrec.Total_Qty,0.0);
								inventrec.Total_Qty=0;
								inventrec.Available_Qty=0;
							}
						}
						if(balqty == 0)
						{
							info "before break";
							break;
						}
						i = i + 1;
					}

				iss_qty = 0;
				ava_qty = 0;
				bal_qty = 0;
				bat = Stock_Batch[Part_No == rec.Part_No && Part_Description == rec.Part_Description && Status != "Issued" && Warehouse == input.Warehouse && Location == rec.Location && Sub_Location == rec.Sub_Location && Racks_Bins == rec.Racks_Bins];
				bat_no_list = List();
				iss_qty = rec.Issued_Quantity;
				for each  i1 in bat
				{
					bat_no = Stock_Batch[ID == i1].Batch_No;
					bat_no_list.add(bat_no);
				}
				info bat_no_list;
				i = 0;
				for each  no in bat_no_list
				{
					batching = Stock_Batch[Batch_No == no];
					ava_qty = batching.Available_Quantity;
					i = i + 1;
					if(i == 1 && iss_qty > ava_qty)
					{
						batching.Status="Issued";
						batching.Issued_Qty_So_far=iss_qty;
						batching.Available_Quantity=0;
						bal_qty = iss_qty - ava_qty;
					}
					else if(i == 1 && iss_qty < ava_qty)
					{
						batching.Status="Partially Issued";
						batching.Issued_Qty_So_far=iss_qty;
						batching.Available_Quantity=ava_qty - iss_qty;
						bal_qty = 0;
					}
					else if(i == 1 && iss_qty == ava_qty)
					{
						batching.Status="Issued";
						batching.Issued_Qty_So_far=iss_qty;
						batching.Available_Quantity=0;
						bal_qty = 0;
					}
					else if(i > 1 && bal_qty > ava_qty)
					{
						batching.Status="Issued";
						batching.Issued_Qty_So_far=iss_qty;
						batching.Available_Quantity=0;
						bal_qty = bal_qty - ava_qty;
					}
					else if(i > 1 && bal_qty < ava_qty)
					{
						batching.Status="Partially Issued";
						batching.Issued_Qty_So_far=iss_qty;
						batching.Available_Quantity=ava_qty - bal_qty;
						bal_qty = 0;
					}
					else if(i > 1 && bal_qty == ava_qty)
					{
						batching.Status="Issued";
						batching.Issued_Qty_So_far=bal_qty;
						batching.Available_Quantity=0;
						bal_qty = 0;
					}
				}
				// Updating Stock value
				temp_issued_qty = rec.Issued_Quantity;
				ival = 0;
				bal = 0;
				if(temp_issued_qty != 0)
				{

				}
			}
		}
	}
	//Insert / Update the Issued Details
	for each  Itemdetrec in input.Item_Details
	{
		insert into Inventory_Ageing
		[
			Added_User=zoho.loginuser
			Part_No=Itemdetrec.Part_No
			Part_Description=Itemdetrec.Part_Description
			Specification=Itemdetrec.Specification
			Issued_Stock=Itemdetrec.Issued_Quantity
			Stock_Added_Issued_Date=zoho.currentdate
		]
	}
	getdeptname = Department[ID == input.Issued_Empolyee_Department].Department_Name;
	//The code below is to get Project cost 
	posum = 0;
	fc = 0;
	for each  rec in input.Item_Details
	{
		fet_posub = Purchase_Order_Subform[Part_No == rec.Part_No];
		if(rec.Part_No == fet_posub.Part_No)
		{
			posum = posum + ifnull(fet_posub.Rate,0.00);
			finalcost = fet_posub.Rate * rec.Issued_Quantity;
		}
		else
		{
			fet_venSub = Vendor_Contract_Subform[Part_Description == rec.Part_Description].maximum(Unit_Price);
			posum = posum + ifnull(fet_venSub,0.00);
			finalcost = ifnull(fet_posub.Rate,0.0) * ifnull(rec.Issued_Quantity,0.0);
		}
		fc = fc + finalcost;
	}
	input.Project_Cost = fc;
	input.Project_Rate = posum;
	//below code is to update in zoho project form
	if(input.Project_Name.Project_Title != null)
	{
		Fet_ZohoProject = Zoho_Projects_Data[ID == input.Project_Name];
		if(Fet_ZohoProject.GIN_Item_Total_Amount == 0 || Fet_ZohoProject.GIN_Item_Total_Amount == null)
		{
			Fet_ZohoProject.GIN_Item_Total_Amount=ifnull(input.Project_Cost,0.00);
		}
		else
		{
			Fet_ZohoProject.GIN_Item_Total_Amount=ifnull(Fet_ZohoProject.GIN_Item_Total_Amount,0.00) + Ifnull(input.Project_Cost,0.00);
		}
	}
	//THE Below function write the record in stock ledger.
	thisapp.Stock_Ledger.Quantity_out_for_Stock_Ledger(input.ID);

	for each  itemrec in input.Item_Details
	{
		//if(itemrec.Part_No.Part_No == "100166" || itemrec.Part_No.Part_No == "100044")
		if(itemrec.Part_No.Part_No == "100166")
		{
			//thisapp.Books.Adjust_Item_Inventory_in_zbooks(itemrec.ID);
			//thisapp.Inventory.update_books_stock_details(itemrec.ID);
		}
	}
	if(var == 1)
	{
		openUrl("#Form:Alert_Messages?Status=" + "GIN" + "&Value=" + input.GIN_Number + "&zc_LoadIn=dialog","same window");
	}
	else
	{
		openUrl("#Form:GIN","same window");
	}
}
catch (e)
{
	sendmail
	[
		from :"erp@carrierwheels.com"
		to :"parthasarathy.m@synprosoft.com"
		subject :"GIN Created Or Edited Successful Form Submission try & catch" + input.ID
		message :e
	]
}
emptylist = List();
//move the status into form mode to handle.
if(input.Form_Mode == null || input.Form_Mode == "")
{
	input.Form_Mode = "Direct GIN";
	//info Form_Mode;
}
if(input.Status == "GIN against MRQ" && input.Material_Request_Subform_record_id != emptylist || input.Material_Request_Subform_record_id != null)
{
	input.Form_Mode = "GIN against MRQ";
	hide Item_Details.Available_Qty;
	hide Item_Details.Block_Qty;
	input.Status = "";
	matreqsf = Material_Request_Subform[ID == input.Material_Request_Subform_record_id];
	Material_Req_Exis_ID = matreqsf.Material_Req_Exis_ID;
	mat_req = Material_Request[ID == Material_Req_Exis_ID];
	input.Material_Request_RECID = Material_Req_Exis_ID;
	input.Warehouse = matreqsf.Material_Req_Exis_ID.Warehouse;
	input.Work_Order_No = matreqsf.Material_Req_Exis_ID.Work_Order_No;
	input.Finished_Good = mat_req.FG_Part_Description;
	mrn = mat_req.Material_Request_No;
	input.Project_Name = Zoho_Projects_Data[ID == mat_req.Project_Name].ID;
	input.Machine_Name = Machine_Master[ID == mat_req.Machine_Name].ID;
	input.Status = "Draft";
	input.Request_raised_By = mat_req.Request_Raised_By;
	//input.Department = Department[ID==mat_req.Department].Department_Name;
	input.Request_Date = mat_req.Request_Date;
	//info mat_req.Material_Type;
	input.Material_Request_Type = mat_req.Material_Type;
	//input.Project_Name = ifnull(mat_req.Project_Name,"");
	row1 = Goods_Issued_Note.Item_Details();
	i = 0;
	grstot = 0;
	for each  i1 in matreqsf
	{
		i = i + 1;
		//Store will issue Itmes from Satellite stores and engineering stores - erp channel - 14/12/2024 from user.
		//inv = Inventory[Part_No == i1.Part_No && Warehouse == input.Warehouse && Total_Qty > 0];
		inv = Inventory[Part_No == i1.Part_No && Warehouse == input.Warehouse && Total_Qty > 0 && Location_Name.Location__Name == "Satellite Stores" || Location_Name.Location__Name == "Engineering Stores"];
		//info inv;
		fet_stockvalue = Stock_Value[Part_No == i1.Part_No] sort by Unit_Price desc;
		row1.S_No=i;
		row1.Part_No=i1.Part_No;
		row1.Part_Description=i1.Part_Description;
		row1.Material_Type=i1.Material_Type;
		row1.Unit_of_Measurement=i1.UoM;
		row1.Required_Quantity=ifnull(i1.Required_Qty,0.00);
		row1.Quantity_issued_so_far=ifnull(i1.Quantity_issued_so_far,0);
		row1.Specification=i1.Specification;
		if(i1.Quantity_issued_so_far > 0 && i1.Required_Qty > 0)
		{
			if(i1.Quantity_issued_so_far > i1.Required_Qty)
			{
				row1.Issued_Quantity=ifnull(i1.Quantity_issued_so_far,0) - ifnull(i1.Required_Qty,0);
			}
		}
		else
		{
			row1.Issued_Quantity=ifnull(i1.Required_Qty,0);
		}
		//row1.Issued_Quantity=ifnull(i1.Required_Qty,0) - ifnull(i1.Quantity_issued_so_far,0);
		//row1.Sub_Total=row1.Issued_Quantity * row1.Rate;
		//new function is written to calculate the rate by Mr.Varun - dt 5/12/2023 - Mail on 5/12/2023
		//row1.Rate=fet_stockvalue.Unit_Price;
		getrate = thisapp.Stock_Value.Average_Stock_Value(row1.Part_No,row1.Issued_Quantity);
		row1.Rate=ifnull(getrate,0);
		if(row1.Issued_Quantity > 0 && row1.Rate > 0)
		{
			sub = ifnull(row1.Issued_Quantity,0) * ifnull(row1.Rate,0);
		}
		grstot = ifnull(grstot,0) + ifnull(sub,0);
		//row1.Sub_Total=sub;
		row1.Value=sub;
		row1.Balance_Quantity=0.00;
		row1.Stock_Quantity=ifnull(inv.Total_Qty,0.00);
		row1.Available_Qty=ifnull(inv.Available_Qty,0.00);
		row1.Block_Qty=ifnull(inv.Block_Qty,0.00);
		row1.Work_Order_No=i1.Work_Order_No;
		row1.Sales_Order_No=i1.Sales_Order_No;
		row1.Material_Request_No=Material_Req_Exis_ID.Material_Request_No;
		row1.Material_Request_Subform_lu=i1.ID;
		row1.Material_type_from_mrq=Material_Req_Exis_ID.Material_Type;
		row1.Location=inv.Location_Name.getall();
		row1.Sub_Location=inv.Sub_Location.getall();
		row1.Racks_Bins=inv.Rack_Number.getall();
		input.Item_Details.insert(row1);
	}
	input.Grand_Total1 = grstot;
	for each  row2 in input.Item_Details
	{
		if(row2.Racks_Bins != null)
		{
			ava = 0;
			for each  i1 in row2.Racks_Bins
			{
				inv2 = Inventory[Warehouse == input.Warehouse && Part_No == row2.Part_No && Location_Name == row2.Location && Sub_Location == row2.Sub_Location && Rack_Number == i1 && Total_Qty > 0];
				//info inv2;
				ava = ava + ifnull(inv2.Available_Qty,0.0);
			}
			row2.Stock_Quantity=ifnull(ava,0.00);
			row2.Qty_after_Issued=ifnull(row2.Stock_Quantity,0.0) - ifnull(row2.Issued_Quantity,0.0);
			//info row2.Qty_after_Issued;
		}
	}
	disable Request_raised_By;
	disable Request_Date;
	disable Material_Request_Type;
}
else if(input.Form_Mode == "GIN against WO")
{
	disable Item_Details.Available_Qty;
	disable Item_Details.Block_Qty;
	input.Status = "";
	matreqsf = Material_Request_Subform[ID == input.Material_Request_Subform_record_id];
	Material_Req_Exis_ID = matreqsf.Material_Req_Exis_ID;
	mat_req = Material_Request[ID == Material_Req_Exis_ID];
	input.Material_Request_RECID = Material_Req_Exis_ID;
	input.Warehouse = matreqsf.Material_Req_Exis_ID.Warehouse;
	input.Work_Order_No = matreqsf.Material_Req_Exis_ID.Work_Order_No;
	input.Finished_Good = mat_req.FG_Part_Description;
	mrn = mat_req.Material_Request_No;
	input.Project_Name = Zoho_Projects_Data[ID == mat_req.Project_Name].ID;
	input.Machine_Name = Machine_Master[ID == mat_req.Machine_Name].ID;
	input.Status = "Draft";
	input.Request_raised_By = mat_req.Request_Raised_By;
	input.Request_Date = mat_req.Request_Date;
	input.Material_Request_Type = mat_req.Material_Type;
	partno_list = List();
	qtylist = List();
	mymap = Map();
	qtymap = Map();
	for each  bomrec in matreqsf
	{
		partno_list.add(bomrec.Part_No);
		qtyvar = ifnull(qtymap.get(bomrec.Part_No),0) + bomrec.Required_Qty;
		qtymap.put(bomrec.Part_No,qtyvar);
		//partno_list.add(bomrec.Required_Qty);
	}
	partno_list.sort();
	i = 0;
	grstot = 0;
	for each  recpartlist in partno_list.distinct()
	{
		row1 = Goods_Issued_Note.Item_Details();
		mrqsflist = Material_Request_Subform[ID = input.Material_Request_Subform_record_id && Part_No == recpartlist];
		mymap.put("Partno",recpartlist);
		mymap.put("partdesc",mrqsflist.Part_Description);
		i = i + 1;
		getinv = Inventory[Part_No == mrqsflist.Part_No && Warehouse == input.Warehouse && Total_Qty > 0];
		getin = Inventory[Part_No == mrqsflist.Part_No && Location_Name.Location__Name != "Production WIP"].sum(Total_Qty);
		////Store will issue Itemss from Satellite stores and engineering stores - erp channel - 14/12/2024 from user.
		getstokqty = Inventory[Part_No == mrqsflist.Part_No && Warehouse == input.Warehouse && Total_Qty > 0 && Location_Name.Location__Name == "Satellite Stores" || Location_Name.Location__Name == "Engineering Stores"].sum(Total_Qty);
		//info "getstokqty " + getstokqty;
		fet_stockvalue = Stock_Value[Part_No == mrqsflist.Part_No] sort by Unit_Price desc;
		row1.S_No=i;
		row1.Part_No=recpartlist;
		row1.Part_Description=mrqsflist.Part_Description;
		row1.Material_Type=mrqsflist.Material_Type;
		row1.Unit_of_Measurement=mrqsflist.UoM;
		qtv = qtymap.get(mrqsflist.Part_No);
		//info "line 155 qty " + qtv;
		row1.Required_Quantity=qtv;
		row1.Quantity_issued_so_far=ifnull(mrqsflist.Quantity_issued_so_far,0);
		row1.Specification=mrqsflist.Specification;
		if(mrqsflist.Quantity_issued_so_far > 0 && mrqsflist.Required_Qty > 0)
		{
			if(mrqsflist.Quantity_issued_so_far > qtv)
			{
				row1.Issued_Quantity=ifnull(mrqsflist.Quantity_issued_so_far,0) - ifnull(qtv,0);
			}
			else if(mrqsflist.Quantity_issued_so_far < qtv)
			{
				row1.Issued_Quantity=ifnull(qtv,0) - ifnull(mrqsflist.Quantity_issued_so_far,0);
			}
		}
		else
		{
			row1.Issued_Quantity=ifnull(qtv,0);
		}
		getrate = thisapp.Stock_Value.Average_Stock_Value(row1.Part_No,row1.Issued_Quantity);
		if(getrate == null)
		{
			getrate = Stock_Value[Part_No == row1.Part_No && Unit_Price > 0].Unit_Price sort by Added_Time asc;
		}
		if(getrate > 0 || getrate != null)
		{
			row1.Rate=ifnull(getrate,0);
			sub = ifnull(row1.Issued_Quantity,0) * ifnull(row1.Rate,0);
		}
		grstot = ifnull(grstot,0) + ifnull(sub,0);
		//row1.Sub_Total=sub;
		row1.Value=sub;
		row1.Balance_Quantity=0.00;
		//Stock Quantity should be from engineering and satellite locations only - 16/12/2024
		//row1.Stock_Quantity=ifnull(getinv.Total_Qty,0.00);
		//	row1.Stock_Quantity=ifnull(getin,0);
		row1.Stock_Quantity=ifnull(getstokqty,0);
		row1.Available_Qty=ifnull(getinv.Available_Qty,0.00);
		row1.Block_Qty=ifnull(getinv.Block_Qty,0.00);
		row1.Work_Order_No=mrqsflist.Work_Order_No;
		row1.Sales_Order_No=mrqsflist.Sales_Order_No;
		row1.Material_Request_No=Material_Req_Exis_ID.Material_Request_No;
		row1.Material_Request_Subform_lu=mrqsflist.ID;
		row1.Material_type_from_mrq=Material_Req_Exis_ID.Material_Type;
		// 		row1.Location=getinv.Location_Name.getall();
		// 		row1.Sub_Location=getinv.Sub_Location.getall();
		// 		row1.Racks_Bins=getinv.Rack_Number.getall();
		input.Item_Details.insert(row1);
	}
	input.Grand_Total1 = grstot;
	for each  row2 in input.Item_Details
	{
		if(row2.Racks_Bins != null)
		{
			ava = 0;
			for each  mrqsflist in row2.Racks_Bins
			{
				////Store will issue Itemss from Satellite stores and engineering stores - erp channel - 14/12/2024 from user.
				//inv2 = Inventory[Warehouse == input.Warehouse && Part_No == row2.Part_No && Location_Name == row2.Location && Sub_Location == row2.Sub_Location && Rack_Number == mrqsflist && Total_Qty > 0];
				inv2 = Inventory[Warehouse == input.Warehouse && Part_No == row2.Part_No && Location_Name.Location__Name == "Satellite Stores" || Location_Name.Location__Name == "Engineering Stores" && Rack_Number == mrqsflist && Total_Qty > 0];
				//info inv2;
				ava = ava + ifnull(inv2.Available_Qty,0.0);
			}
			row2.Stock_Quantity=ifnull(ava,0.00);
			row2.Qty_after_Issued=ifnull(row2.Stock_Quantity,0.0) - ifnull(row2.Issued_Quantity,0.0);
			//info row2.Qty_after_Issued;
		}
	}
	disable Request_raised_By;
	disable Request_Date;
	disable Material_Request_Type;
}
getmrp = MRP[Work_Order_Subform_ID == input.ID];
getmrpsub = MRP_Subform_CWPL[MRP_Exis_ID == getmrp.ID];
fet_wosub = Work_Order_Subform[ID == input.ID];
fet_wo = Work_Order[ID == fet_wosub.Work_Order_Exis_ID];
fet_bom = Create_BOM[Part_No == fet_wosub.Part_No];
fetsubbom = BoM_FG_Subform[BOM_FG_Exis_ID == fet_bom.ID];
//info fetsubbom.count();
if(fetsubbom.count() == 0)
{
	openUrl("#Form:Alert_Messages?Status=MRPbom_Alert&Value=BoM not created! Create BoM for this Material. &zc_LoadIn=dialog","same window");
}
else if(getmrp.MRP_Status == null && fet_wosub.WO_Qty != 0)
{
	openUrl("#Form:MRP?Work_Order_Subform_ID=" + input.ID,"same window");
}
else if(getmrp.MRP_Status == "MRP Reverted")
{
	openUrl("#Form:MRP?Work_Order_Subform_ID=" + input.ID,"same window");
}
else if(fet_wosub.Work_Order_Status == "MRP Rejected")
{
	openUrl("#Form:MRP?Work_Order_Subform_ID=" + input.ID,"same window");
}
else if(getmrp.MRP_Status == "Draft")
{
	openUrl("#Form:MRP?recLinkID=" + getmrp.ID + "&viewLinkName=MRP_Report&Form_Mode=DraftMRP","same window");
}
else if(fet_wosub.WO_Qty <= 0)
{
	openUrl("#Form:Alert_Messages?Status=MRP_Alert&Value=Stock available for this WorkOrder. <br>Not Required MRP! &zc_LoadIn=dialog","same window");
}
else
{
	openUrl("#Form:MRP?Work_Order_Subform_ID=" + input.ID,"same window");
}
void Dispatch_Note.Dispatch(int ID)
{
	openUrl("#Form:Create_Dispatch_Note_Format?recLinkID=" + ID + "&viewLinkName=Dispatch_Note_Actual&Dispatch_Type=Actual","popup window");
}
for each  deliv in input.Despatch_Schedule
{
	if(deliv.Part_No == row.Part_No)
	{
		deliv.Full_Quantity=false;
	}
}
for each  r in input.Despatch_Schedule
{
	b = r.S_No - 1;
	r.S_No=b;
	if(r.S_No < row.S_No)
	{
		b = b + 1;
		r.S_No=b;
	}
}
for each  r in input.Item_Details
{
	b = ifnull(r.S_No,0) - 1;
	r.S_No=b;
	if(r.S_No < row.S_No)
	{
		b = b + 1;
		r.S_No=b;
	}
}
input.Gross_Total = ifnull(input.Gross_Total,0.0) - ifnull(row.Sub_Total,0.0);
input.Total_Quantity = ifnull(input.Total_Quantity,0.0) - ifnull(row.Qty,0.0);
if(input.Gross_Total == 0)
{
	input.Gross_Total = 0;
	input.Total_Quantity = null;
	input.Discount = null;
	input.Discount_Amount = 0;
	input.Discount_Amount = null;
	hide Discount_Amount;
	input.Discount_Percentage = null;
	hide Discount_Percentage;
	input.Final_Gross_Total = 0;
	input.Total_Taxes = null;
	input.Grand_Total = null;
	input.Gross_with_Discount = null;
	input.Gross_Value_Tax = null;
	input.Gross_Total_with_Discount = null;
	input.Packing_Forwarding = null;
	input.PF_Total_with_tax = null;
	input.PF_Tax_value = null;
}
for each  rec in input.Despatch_Schedule
{
	if(rec.Part_No == row.Part_No)
	{
		rec.Part_No=null;
		rec.Quantity=null;
		rec.Delivery_Date=null;
	}
}
itemlist = List();
qtyList = List();
dateList = List();
remarksList = List();
fullQtyList = List();
for each  rec in input.Despatch_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.Despatch_Schedule.clear();
i = 0;
s_no = 0;
for each  items in itemlist
{
	s_no = s_no + 1;
	row1 = Sales_Order.Despatch_Schedule();
	row1.S_No=s_no;
	row1.Part_No=items;
	row1.Quantity=qtyList.get(i);
	row1.Delivery_Date=dateList.get(i);
	row1.Remarks=remarksList.get(i);
	row1.Full_Quantity=fullQtyList.get(i);
	input.Despatch_Schedule.insert(row1);
	i = i + 1;
}
//Grand total adjustment
input.Grand_Total = ifnull(input.Grand_Total,0.0) - ifnull(row.Total_Amount,0.0);
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

star

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

@Pooja

star

Tue Jan 07 2025 14:42:20 GMT+0000 (Coordinated Universal Time)

@Pooja

star

Tue Jan 07 2025 14:41:36 GMT+0000 (Coordinated Universal Time)

@Pooja

star

Tue Jan 07 2025 14:40:50 GMT+0000 (Coordinated Universal Time)

@Pooja

star

Tue Jan 07 2025 14:40:02 GMT+0000 (Coordinated Universal Time)

@Pooja

star

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

@Pooja

star

Tue Jan 07 2025 14:36:50 GMT+0000 (Coordinated Universal Time)

@Pooja

star

Tue Jan 07 2025 14:34:10 GMT+0000 (Coordinated Universal Time)

@Pooja

star

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

@Pooja

star

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

@Pooja

star

Tue Jan 07 2025 14:27:58 GMT+0000 (Coordinated Universal Time)

@Pooja

star

Tue Jan 07 2025 14:27:23 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