/// <summary> /// Load Document Details /// </summary> /// <returns>error message or null</returns> public override String LoadDocumentDetails() { SetC_Currency_ID(NO_CURRENCY); MInOut inout = (MInOut)GetPO(); SetDateDoc(inout.GetMovementDate()); // _MatchRequirementR = X_AD_ClientInfo.MATCHREQUIREMENTR_None; if (!inout.IsSOTrx()) { _MatchRequirementR = MClientInfo.Get(GetCtx(), inout.GetAD_Client_ID()) .GetMatchRequirementR(); String mr = inout.GetMatchRequirementR(); if (mr == null) { inout.SetMatchRequirementR(_MatchRequirementR); } else { _MatchRequirementR = mr; } } // Contained Objects _lines = LoadLines(inout); log.Fine("Lines=" + _lines.Length); if (_matchProblem == null || _matchProblem.Length == 0) { return(null); } return(_matchProblem.Substring(1).Trim()); }
//Get UOM Conversion public Dictionary <string, object> GetUOMConversion(Ctx ctx, string fields) { Dictionary <string, object> retValue = null; string[] paramString = fields.Split(','); MInOut inout = new MInOut(ctx, Util.GetValueOfInt(paramString[0]), null); int M_Product_ID = Util.GetValueOfInt(paramString[1]); int C_UOM_ID = Util.GetValueOfInt(paramString[2]); try { int uom = Util.GetValueOfInt(DB.ExecuteScalar("SELECT vdr.C_UOM_ID FROM M_Product p LEFT JOIN M_Product_Po vdr ON p.M_Product_ID= vdr.M_Product_ID WHERE p.M_Product_ID=" + M_Product_ID + " AND vdr.C_BPartner_ID = " + inout.GetC_BPartner_ID(), null, null)); if (C_UOM_ID != 0) { if (C_UOM_ID != uom && uom != 0) { retValue = new Dictionary <string, object>(); retValue["multiplyrate"] = Util.GetValueOfDecimal(DB.ExecuteScalar("SELECT trunc(multiplyrate,4) FROM C_UOM_Conversion WHERE C_UOM_ID = " + C_UOM_ID + " AND C_UOM_To_ID = " + uom + " AND M_Product_ID= " + M_Product_ID + " AND IsActive='Y'")); if (Util.GetValueOfDecimal(retValue["multiplyrate"]) <= 0) { retValue["multiplyrate"] = Util.GetValueOfDecimal(DB.ExecuteScalar("SELECT trunc(multiplyrate,4) FROM C_UOM_Conversion WHERE C_UOM_ID = " + C_UOM_ID + " AND C_UOM_To_ID = " + uom + " AND IsActive='Y'")); } retValue["uom"] = uom; } } } catch (Exception e) { } return(retValue); }
/** * Parent Constructor * @param ship shipment * @param confirmType confirmation type */ public MInOutConfirm(MInOut ship, String confirmType) : this(ship.GetCtx(), 0, ship.Get_TrxName()) { SetClientOrg(ship); SetM_InOut_ID(ship.GetM_InOut_ID()); SetConfirmType(confirmType); }
/** * Set Value Name Description * @param shipment shipment * @param line line * @param deliveryCount */ public void SetValueNameDescription(MInOut shipment, MInOutLine line, int deliveryCount) { MProduct product = line.GetProduct(); MBPartner partner = shipment.GetBPartner(); SetValueNameDescription(shipment, deliveryCount, product, partner); }
/** * Create Confirmation or return existing one * @param ship shipment * @param confirmType confirmation type * @param checkExisting if false, new confirmation is created * @return Confirmation */ public static MInOutConfirm Create(MInOut ship, String confirmType, Boolean checkExisting) { if (checkExisting) { MInOutConfirm[] confirmations = ship.GetConfirmations(false); for (int i = 0; i < confirmations.Length; i++) { MInOutConfirm confirm = confirmations[i]; if (confirm.GetConfirmType().Equals(confirmType)) { _log.Info("create - existing: " + confirm); return(confirm); } } } MInOutConfirm confirm1 = new MInOutConfirm(ship, confirmType); confirm1.Save(ship.Get_TrxName()); MInOutLine[] shipLines = ship.GetLines(false); for (int i = 0; i < shipLines.Length; i++) { MInOutLine sLine = shipLines[i]; MInOutLineConfirm cLine = new MInOutLineConfirm(confirm1); cLine.SetInOutLine(sLine); cLine.Save(ship.Get_TrxName()); } _log.Info("New: " + confirm1); return(confirm1); }
/// <summary> /// Complete Shipment /// </summary> private void CompleteShipment() { if (_shipment != null) { // Fails if there is a confirmation if (!_shipment.ProcessIt(_docAction)) { _shipment.Get_TrxName().Rollback(); log.Warning("Failed: " + _shipment); } _shipment.Save(); // if (_msg != null) { MOrder OrderDoc = new MOrder(GetCtx(), _shipment.GetC_Order_ID(), _shipment.Get_TrxName()); AddLog(_shipment.GetM_InOut_ID(), _shipment.GetMovementDate(), null, (_msg + " " + (_shipment.GetProcessMsg() != "" ? (_shipment.GetProcessMsg() + " " + (!_consolidateDocument ? OrderDoc.GetDocumentNo() : " ")) : _shipment.GetDocumentNo()))); } else { AddLog(_shipment.GetM_InOut_ID(), _shipment.GetMovementDate(), null, _shipment.GetDocumentNo()); } _created++; _map = new Dictionary <SParameter, MStorage[]>(); if (_lastPP != null && _lastStorages != null) { _map.Add(_lastPP, _lastStorages); } _shipment.Get_TrxName().Commit(); } _shipment = null; _line = 0; }
/** * Set Value, Name, Description * @param shipment shipment * @param deliveryCount count * @param product product * @param partner partner */ public void SetValueNameDescription(MInOut shipment, int deliveryCount, MProduct product, MBPartner partner) { String documentNo = "_" + shipment.GetDocumentNo(); if (deliveryCount > 1) { documentNo += "_" + deliveryCount; } // Value String value = partner.GetValue() + "_" + product.GetValue(); if (value.Length > 40 - documentNo.Length) { value = value.Substring(0, 40 - documentNo.Length) + documentNo; } // Change to set Value from Document Sequence // SetValue(value); // Change to set only name of product as value in Asset // Name MProduct.afterSave // String name = partner.GetName() + " - " + product.GetName(); String name = product.GetName(); if (name.Length > 60) { name = name.Substring(0, 60); } SetName(name); // Description String description = product.GetDescription(); SetDescription(description); }
/// <summary> /// Shipment Constructor /// </summary> /// <param name="shipment">shipment</param> /// <param name="shipper">shipper</param> public MPackage(MInOut shipment, MShipper shipper) : this(shipment.GetCtx(), 0, shipment.Get_TrxName()) { SetClientOrg(shipment); SetM_InOut_ID(shipment.GetM_InOut_ID()); SetM_Shipper_ID(shipper.GetM_Shipper_ID()); }
/// <summary> /// Process /// </summary> /// <returns>message</returns> protected override String DoIt() { log.Info("doIt - M_InOut_ID=" + _M_InOut_ID + ", M_Shipper_ID=" + _M_Shipper_ID); if (_M_InOut_ID == 0) { throw new Exception("No Shipment"); } if (_M_Shipper_ID == 0) { throw new Exception("No Shipper"); } string sql = "select M_Inout_ID from M_InoutConfirm where M_InoutConfirm_ID = " + _M_InOut_ID; int _M_Shipment_ID = Util.GetValueOfInt(DB.ExecuteScalar(sql, null, null)); MInOut shipment = new MInOut(GetCtx(), _M_Shipment_ID, null); if (shipment.Get_ID() != _M_Shipment_ID) { throw new Exception("Cannot find Shipment ID=" + _M_InOut_ID); } MShipper shipper = new MShipper(GetCtx(), _M_Shipper_ID, Get_TrxName()); if (shipper.Get_ID() != _M_Shipper_ID) { throw new Exception("Cannot find Shipper ID=" + _M_InOut_ID); } MPackage pack = MPackage.Create(shipment, shipper, null); return(pack.GetDocumentNo()); }
/// <summary> /// Load Invoice Line /// </summary> /// <param name="inout">shipment/receipt</param> /// <returns>DocLine Array</returns> private DocLine[] LoadLines(MInOut inout) { List <DocLine> list = new List <DocLine>(); MInOutLine[] lines = inout.GetLines(false); for (int i = 0; i < lines.Length; i++) { MInOutLine line = lines[i]; if (line.IsDescription() || line.GetM_Product_ID() == 0 || Env.Signum(line.GetMovementQty()) == 0) { log.Finer("Ignored: " + line); continue; } // PO Matching if (_MatchRequirementR.Equals(X_M_InOut.MATCHREQUIREMENTR_PurchaseOrder) || _MatchRequirementR.Equals(X_M_InOut.MATCHREQUIREMENTR_PurchaseOrderAndInvoice)) { Decimal poDiff = line.GetMatchPODifference(); if (Env.Signum(poDiff) != 0) { _matchProblem += "; Line=" + line.GetLine() + " PO Match diff=" + poDiff; } else if (!line.IsMatchPOPosted()) { _matchProblem += "; PO Match not posted for Line=" + line.GetLine(); } } // Inv Matching else if (_MatchRequirementR.Equals(X_M_InOut.MATCHREQUIREMENTR_Invoice) || _MatchRequirementR.Equals(X_M_InOut.MATCHREQUIREMENTR_PurchaseOrderAndInvoice)) { Decimal invDiff = line.GetMatchInvDifference(); if (Env.Signum(invDiff) != 0) { _matchProblem += "; Line=" + line.GetLine() + " PO Match diff=" + invDiff; } else if (!line.IsMatchInvPosted()) { _matchProblem += "; Inv Match not posted for Line=" + line.GetLine(); } } DocLine docLine = new DocLine(line, this); Decimal Qty = line.GetMovementQty(); docLine.SetQty(Qty, GetDocumentType().Equals(MDocBaseType.DOCBASETYPE_MATERIALDELIVERY)); // sets Trx and Storage Qty // log.Fine(docLine.ToString()); list.Add(docLine); } // Return Array DocLine[] dls = new DocLine[list.Count]; dls = list.ToArray(); return(dls); }
/* Get Parent * @return parent */ public MInOut GetParent() { if (_parent == null) { _parent = new MInOut(GetCtx(), GetM_InOut_ID(), Get_TrxName()); } return(_parent); }
// Added by Bharat on 30 Jan 2018 to Get Inco Term public int GetIncoTerm(Ctx ctx, string fields) { string[] paramValue = fields.Split(','); bool isSOTrx = false; int incoTerm_ID = 0, referenceID = 0; string tableName = "", refColumn = "", qry = ""; isSOTrx = Util.GetValueOfBool(paramValue[0]); tableName = Util.GetValueOfString(paramValue[1]); refColumn = Util.GetValueOfString(paramValue[2]); referenceID = Util.GetValueOfInt(paramValue[3]); if (tableName == "C_Order") { if (referenceID > 0) { MOrder ord = new MOrder(ctx, referenceID, null); incoTerm_ID = ord.GetC_IncoTerm_ID(); } } else if (tableName == "C_Invoice") { if (isSOTrx && referenceID > 0) { MOrder ord = new MOrder(ctx, referenceID, null); incoTerm_ID = ord.GetC_IncoTerm_ID(); } else if (!isSOTrx && referenceID > 0 && refColumn == "C_Order_ID") { MOrder ord = new MOrder(ctx, referenceID, null); incoTerm_ID = ord.GetC_IncoTerm_ID(); } else if (!isSOTrx && referenceID > 0 && refColumn == "M_InOut_ID") { MInOut inOut = new MInOut(ctx, referenceID, null); incoTerm_ID = inOut.GetC_IncoTerm_ID(); } } else if (tableName == "M_InOut") { if (isSOTrx && referenceID > 0) { MOrder ord = new MOrder(ctx, referenceID, null); incoTerm_ID = ord.GetC_IncoTerm_ID(); } else if (!isSOTrx && referenceID > 0 && refColumn == "C_Order_ID") { MOrder ord = new MOrder(ctx, referenceID, null); incoTerm_ID = ord.GetC_IncoTerm_ID(); } else if (!isSOTrx && referenceID > 0 && refColumn == "C_Invoice_ID") { MInvoice inv = new MInvoice(ctx, referenceID, null); incoTerm_ID = inv.GetC_IncoTerm_ID(); } } return(incoTerm_ID); }
/** * Parent Constructor * @param inout parent */ public MInOutLine(MInOut inout) : this(inout.GetCtx(), 0, inout.Get_TrxName()) { SetClientOrg(inout); SetM_InOut_ID(inout.GetM_InOut_ID()); SetM_Warehouse_ID(inout.GetM_Warehouse_ID()); SetC_Project_ID(inout.GetC_Project_ID()); _parent = inout; }
/// <summary> /// Create Invoice. /// </summary> /// <returns>document no</returns> protected override String DoIt() { //log.info("M_InOut_ID=" + _M_InOut_ID // + ", M_PriceList_ID=" + _M_PriceList_ID // + ", InvoiceDocumentNo=" + _InvoiceDocumentNo); if (_M_InOut_ID == 0) { throw new ArgumentException("No Shipment"); } // MInOut ship = new MInOut(GetCtx(), _M_InOut_ID, null); if (ship.Get_ID() == 0) { throw new ArgumentException("Shipment not found"); } if (!MInOut.DOCSTATUS_Completed.Equals(ship.GetDocStatus())) { throw new ArgumentException("Shipment not completed"); } MInvoice invoice = new MInvoice(ship, null); if (ship.IsReturnTrx()) { invoice.SetC_DocTypeTarget_ID(ship.IsSOTrx() ? MDocBaseType.DOCBASETYPE_ARCREDITMEMO : MDocBaseType.DOCBASETYPE_APCREDITMEMO); } if (_M_PriceList_ID != 0) { invoice.SetM_PriceList_ID(_M_PriceList_ID); } if (_InvoiceDocumentNo != null && _InvoiceDocumentNo.Length > 0) { invoice.SetDocumentNo(_InvoiceDocumentNo); } if (!invoice.Save()) { throw new ArgumentException("Cannot save Invoice"); } MInOutLine[] shipLines = ship.GetLines(false); for (int i = 0; i < shipLines.Length; i++) { MInOutLine sLine = shipLines[i]; MInvoiceLine line = new MInvoiceLine(invoice); line.SetShipLine(sLine); line.SetQtyEntered(sLine.GetQtyEntered()); line.SetQtyInvoiced(sLine.GetMovementQty()); if (!line.Save()) { throw new ArgumentException("Cannot save Invoice Line"); } } return(invoice.GetDocumentNo()); }
/// <summary> /// Create Confirmation /// </summary> /// <returns>document no</returns> protected override String DoIt() { //log.info("M_InOut_ID=" + _M_InOut_ID + ", Type=" + _ConfirmType); MInOut shipment = new MInOut(GetCtx(), _M_InOut_ID, null); if (shipment.Get_ID() == 0) { throw new ArgumentException("Not found M_InOut_ID=" + _M_InOut_ID); } // MInOutConfirm[] confirmations = shipment.GetConfirmations(false); MInOutConfirm confirm = null; int count = 0; if (confirmations != null && confirmations.Length > 0) { for (Int32 i = 0; i < confirmations.Length; i++) { confirm = null; count += 1; confirm = confirmations[i]; if (confirm.GetDocStatus() == "VO") { if (count == confirmations.Length) { confirm = MInOutConfirm.Create(shipment, _ConfirmType, false); break; } } if (confirm.GetDocStatus() == "DR") { confirm = MInOutConfirm.Create(shipment, _ConfirmType, true); break; } } } else { confirm = MInOutConfirm.Create(shipment, _ConfirmType, true); } //throw new Exception("Cannot create Confirmation for " + shipment.GetDocumentNo()); if (confirm == null) { throw new Exception("Cannot create Confirmation for " + shipment.GetDocumentNo()); } if (shipment.GetDocStatus() == "DR") //To set docstatus for MR in InProgress state when shipment/MR is in Drafted state { shipment.SetDocStatus("IP"); shipment.FreezeDoc(); } // return("Open Shipment Confirmation Number generated: " + confirm.GetDocumentNo()); }
/** * Complete Invoice */ private void CompleteInvoice() { if (_invoice != null) { if (!_invoice.ProcessIt(_docAction)) { log.Warning("completeInvoice - failed: " + _invoice); } _invoice.Save(); // AddLog(_invoice.GetC_Invoice_ID(), Convert.ToDateTime(_invoice.GetDateInvoiced()), null, _invoice.GetDocumentNo()); _created++; } _invoice = null; _ship = null; _line = 0; }
/// <summary> /// Create Confirmation /// </summary> /// <returns>document no</returns> protected override String DoIt() { //log.info("M_InOut_ID=" + _M_InOut_ID + ", Type=" + _ConfirmType); MInOut shipment = new MInOut(GetCtx(), _M_InOut_ID, null); if (shipment.Get_ID() == 0) { throw new ArgumentException("Not found M_InOut_ID=" + _M_InOut_ID); } // MInOutConfirm confirm = MInOutConfirm.Create(shipment, _ConfirmType, true); if (confirm == null) { throw new Exception("Cannot create Confirmation for " + shipment.GetDocumentNo()); } // return("Open Shipment Confirmation Number generated: " + confirm.GetDocumentNo()); }
private static VLogger _log = VLogger.GetVLogger(typeof(MPackage).FullName); //Arpit public static MPackage Create(MInOut shipment, MShipper shipper, DateTime?shipDate, Trx trxName) { MPackage retValue = new MPackage(shipment, shipper); if (shipDate != null) { retValue.SetShipDate(shipDate); } //Edited : Arpit Rai, 13 Sept,2017 DateTime?moveDate = Convert.ToDateTime(shipment.GetMovementDate()); String documentNo = shipment.GetDocumentNo(); retValue.SetDateAcct(DateTime.Now.Date); retValue.SetAD_Client_ID(shipment.GetAD_Client_ID()); retValue.SetAD_Org_ID(shipment.GetAD_Org_ID()); if (!retValue.Save(trxName)) { trxName.Rollback(); _log.Log(Level.SEVERE, "Error While Generating Package"); } //Arpit // Lines MInOutLine[] lines = shipment.GetLines(false); for (int i = 0; i < lines.Length; i++) { MInOutLine sLine = lines[i]; MPackageLine pLine = new MPackageLine(retValue); //Arpit //pLine.SetInOutLine(sLine); //Changes in Below Method to create Lines and their values from Shipment/MR Lines to Package Lines pLine.SetInOutLine(sLine, moveDate, documentNo, retValue.GetAD_Client_ID(), retValue.GetAD_Org_ID()); if (!pLine.Save(trxName)) { trxName.Rollback(); _log.Log(Level.SEVERE, "Error While Generating Package Lines"); } //Arpit } // lines return(retValue); }
/// <summary> /// Create one Package for Shipment /// </summary> /// <param name="shipment">shipment</param> /// <param name="shipper">shipper</param> /// <param name="shipDate">null for today</param> /// <returns>package</returns> public static MPackage Create(MInOut shipment, MShipper shipper, DateTime?shipDate) { MPackage retValue = new MPackage(shipment, shipper); if (shipDate != null) { retValue.SetShipDate(shipDate); } retValue.Save(); // Lines MInOutLine[] lines = shipment.GetLines(false); for (int i = 0; i < lines.Length; i++) { MInOutLine sLine = lines[i]; MPackageLine pLine = new MPackageLine(retValue); pLine.SetInOutLine(sLine); pLine.Save(); } // lines return(retValue); }
/// <summary> /// GetInOut /// </summary> /// <param name="ctx"></param> /// <param name="param"></param> /// <returns></returns> public Dictionary <String, String> GetInOut(Ctx ctx, string param) { string[] paramValue = param.Split(','); int Orig_InOut_ID; //Assign parameter value Orig_InOut_ID = Util.GetValueOfInt(paramValue[0].ToString()); MInOut io = new MInOut(ctx, Orig_InOut_ID, null); //End Assign parameter Dictionary <String, String> retDic = new Dictionary <string, string>(); retDic["C_Project_ID"] = io.GetC_Project_ID().ToString(); retDic["C_Campaign_ID"] = io.GetC_Campaign_ID().ToString(); retDic["C_Activity_ID"] = io.GetC_Activity_ID().ToString(); retDic["AD_OrgTrx_ID"] = io.GetAD_OrgTrx_ID().ToString(); retDic["User1_ID"] = io.GetUser1_ID().ToString(); retDic["User2_ID"] = io.GetUser2_ID().ToString(); return(retDic); }
public JsonResult GetInOut(string param) { string retError = ""; string retJSON = ""; if (Session["ctx"] != null) { VAdvantage.Utility.Ctx ctx = Session["ctx"] as Ctx; string[] paramValue = param.Split(','); int Orig_InOut_ID; //Assign parameter value Orig_InOut_ID = Util.GetValueOfInt(paramValue[0].ToString()); MInOut io = new MInOut(ctx, Orig_InOut_ID, null); Dictionary <String, String> retDic = new Dictionary <string, string>(); // Reset Orig Shipment retDic["C_Project_ID"] = io.GetC_Project_ID().ToString(); retDic["C_Campaign_ID"] = io.GetC_Campaign_ID().ToString(); retDic["C_Activity_ID"] = io.GetC_Activity_ID().ToString(); retDic["AD_OrgTrx_ID"] = io.GetAD_OrgTrx_ID().ToString(); retDic["User1_ID"] = io.GetUser1_ID().ToString(); retDic["User2_ID"] = io.GetUser2_ID().ToString(); //retlst.Add(retValue); //retVal.Add(notReserved); retJSON = JsonConvert.SerializeObject(retDic); } else { retError = "Session Expired"; } return(Json(new { result = retJSON, error = retError }, JsonRequestBehavior.AllowGet)); }
/// <summary> /// Complete Shipment /// </summary> private void CompleteShipment() { if (_shipment != null) { // Fails if there is a confirmation if (!_shipment.ProcessIt(_docAction)) { log.Warning("Failed: " + _shipment); } _shipment.Save(); // AddLog(_shipment.GetM_InOut_ID(), _shipment.GetMovementDate(), null, _shipment.GetDocumentNo()); _created++; _map = new Dictionary <SParameter, MStorage[]>(); if (_lastPP != null && _lastStorages != null) { _map.Add(_lastPP, _lastStorages); } } _shipment = null; _line = 0; }
/// <summary> /// Before Delete /// </summary> /// <returns>true if acct was deleted</returns> protected override bool BeforeDelete() { if (IsPosted()) { if (!MPeriod.IsOpen(GetCtx(), GetDateTrx(), MDocBaseType.DOCBASETYPE_MATCHPO)) { return(false); } SetPosted(false); return(true);// MFactAcct.Delete(Table_ID, Get_ID(), Get_Trx()) >= 0; } //JID_0162: System should allow to delete the Matched PO of PO and MR with complete status only. if (GetC_OrderLine_ID() != 0) { MOrderLine line = new MOrderLine(GetCtx(), GetC_OrderLine_ID(), Get_TrxName()); MOrder ord = new MOrder(GetCtx(), line.GetC_Order_ID(), Get_TrxName()); if (ord.GetDocStatus() != DocumentEngine.ACTION_COMPLETE) { log.SaveError("Error", Msg.GetMsg(GetCtx(), "Order/ShipmentNotCompleted")); return(false); } } if (GetM_InOutLine_ID() != 0) { MInOutLine line = new MInOutLine(GetCtx(), GetM_InOutLine_ID(), Get_TrxName()); MInOut ino = new MInOut(GetCtx(), line.GetM_InOut_ID(), Get_TrxName()); if (ino.GetDocStatus() != DocumentEngine.ACTION_COMPLETE) { log.SaveError("Error", Msg.GetMsg(GetCtx(), "Order/ShipmentNotCompleted")); return(false); } } return(true); }
/** * Shipment Constructor * @param shipment shipment * @param shipLine shipment line * @param deliveryCount 0 or number of delivery */ public MAsset(MInOut shipment, MInOutLine shipLine, int deliveryCount) : this(shipment.GetCtx(), 0, shipment.Get_TrxName()) { SetClientOrg(shipment); SetValueNameDescription(shipment, shipLine, deliveryCount); // Header // SetIsOwned(true); SetC_BPartner_ID(shipment.GetC_BPartner_ID()); SetC_BPartner_Location_ID(shipment.GetC_BPartner_Location_ID()); SetAD_User_ID(shipment.GetAD_User_ID()); SetM_Locator_ID(shipLine.GetM_Locator_ID()); SetIsInPosession(true); SetAssetServiceDate(shipment.GetDateAcct()); // Line MProduct product = shipLine.GetProduct(); SetM_Product_ID(product.GetM_Product_ID()); SetA_Asset_Group_ID(product.GetA_Asset_Group_ID()); //////////////////////////////* //Changes for vafam // SetAssetServiceDate(shipment.GetMovementDate()); //SetGuaranteeDate(TimeUtil.AddDays(shipment.GetMovementDate(), product.GetGuaranteeDays())); MAssetGroup _assetGroup = new MAssetGroup(GetCtx(), GetA_Asset_Group_ID(), shipment.Get_TrxName()); if (_assetGroup.IsOwned()) { SetIsOwned(true); //SetC_BPartner_ID(0); } if (_assetGroup.IsDepreciated()) { SetIsDepreciated(true); SetIsFullyDepreciated(false); } //Change by Sukhwinder for setting Asset type and amortization template on Asset window, MANTIS ID:1762 int countVA038 = Util.GetValueOfInt(DB.ExecuteScalar("SELECT COUNT(AD_MODULEINFO_ID) FROM AD_MODULEINFO WHERE PREFIX='VA038_' ")); int countVAFAM = Util.GetValueOfInt(DB.ExecuteScalar("SELECT COUNT(AD_MODULEINFO_ID) FROM AD_MODULEINFO WHERE PREFIX='VAFAM_' ")); if (countVA038 > 0) { Set_Value("VA038_AmortizationTemplate_ID", Utility.Util.GetValueOfInt(_assetGroup.Get_Value("VA038_AmortizationTemplate_ID"))); } if (countVAFAM > 0) { Set_Value("VAFAM_AssetType", _assetGroup.Get_Value("VAFAM_AssetType").ToString()); Set_Value("VAFAM_DepreciationType_ID", Utility.Util.GetValueOfInt(_assetGroup.Get_Value("VAFAM_DepreciationType_ID"))); } //////////////////////////////////// // Guarantee & Version SetGuaranteeDate(TimeUtil.AddDays(shipment.GetMovementDate(), product.GetGuaranteeDays())); SetVersionNo(product.GetVersionNo()); if (shipLine.GetM_AttributeSetInstance_ID() != 0) // Instance { MAttributeSetInstance asi = new MAttributeSetInstance(GetCtx(), shipLine.GetM_AttributeSetInstance_ID(), Get_TrxName()); SetM_AttributeSetInstance_ID(asi.GetM_AttributeSetInstance_ID()); SetLot(asi.GetLot()); SetSerNo(asi.GetSerNo()); } SetHelp(shipLine.GetDescription()); // Qty int units = product.GetSupportUnits(); if (units == 0) { units = 1; } if (deliveryCount != 0) // one asset per UOM { SetQty(shipLine.GetMovementQty(), units); } else { SetQty((Decimal)units); } SetM_InOutLine_ID(shipLine.GetM_InOutLine_ID()); // Activate MAssetGroup ag = MAssetGroup.Get(GetCtx(), GetA_Asset_Group_ID()); if (!ag.IsCreateAsActive()) { SetIsActive(false); } }
/** * Create Invoice Line from Shipment * @param order order * @param ship shipment header * @param sLine shipment line */ private void CreateLine(MOrder order, MInOut ship, MInOutLine sLine) { if (_invoice == null) { _invoice = new MInvoice(order, 0, _DateInvoiced); if (!_invoice.Save()) { throw new Exception("Could not create Invoice (s)"); } } #region Comment Create Shipment Comment Line // Create Shipment Comment Line //if (_ship == null // || _ship.GetM_InOut_ID() != ship.GetM_InOut_ID()) //{ // MDocType dt = MDocType.Get(GetCtx(), ship.GetC_DocType_ID()); // if (_bp == null || _bp.GetC_BPartner_ID() != ship.GetC_BPartner_ID()) // { // _bp = new MBPartner(GetCtx(), ship.GetC_BPartner_ID(), Get_TrxName()); // } // // Reference: Delivery: 12345 - 12.12.12 // MClient client = MClient.Get(GetCtx(), order.GetAD_Client_ID()); // String AD_Language = client.GetAD_Language(); // if (client.IsMultiLingualDocument() && _bp.GetAD_Language() != null) // { // AD_Language = _bp.GetAD_Language(); // } // if (AD_Language == null) // { // // MessageBox.Show("Set base Language"); // //AD_Language = Language.getBaseAD_Language(); // } // //java.text.SimpleDateFormat format = DisplayType.getDateFormat // // (DisplayType.Date, Language.getLanguage(AD_Language)); // //String reference = dt.GetPrintName(_bp.GetAD_Language()) // // + ": " + ship.GetDocumentNo() // // + " - " + format.format(ship.GetMovementDate()); // String reference = dt.GetPrintName(_bp.GetAD_Language()) // + ": " + ship.GetDocumentNo() // + " - " + ship.GetMovementDate(); // _ship = ship; // // // MInvoiceLine line = new MInvoiceLine(_invoice); // line.SetIsDescription(true); // line.SetDescription(reference); // line.SetLine(_line + sLine.GetLine() - 2); // if (!line.Save()) // { // throw new Exception("Could not create Invoice Comment Line (sh)"); // } // // Optional Ship Address if not Bill Address // if (order.GetBill_Location_ID() != ship.GetC_BPartner_Location_ID()) // { // MLocation addr = MLocation.GetBPLocation(GetCtx(), ship.GetC_BPartner_Location_ID(), null); // line = new MInvoiceLine(_invoice); // line.SetIsDescription(true); // line.SetDescription(addr.ToString()); // line.SetLine(_line + sLine.GetLine() - 1); // if (!line.Save()) // { // throw new Exception("Could not create Invoice Comment Line 2 (sh)"); // } // } //} #endregion // MInvoiceLine line1 = new MInvoiceLine(_invoice); line1.SetShipLine(sLine); line1.SetQtyEntered(sLine.GetQtyEntered()); line1.SetQtyInvoiced(sLine.GetMovementQty()); line1.SetLine(_line + sLine.GetLine()); line1.SetM_AttributeSetInstance_ID(sLine.GetM_AttributeSetInstance_ID()); if (!line1.Save()) { throw new Exception("Could not create Invoice Line (s)"); } // Link sLine.SetIsInvoiced(true); if (!sLine.Save()) { throw new Exception("Could not update Shipment Line"); } log.Fine(line1.ToString()); }
/** * Generate Shipments * @param pstmt order query * @return info */ private String Generate(IDataReader idr) { DataTable dt = new DataTable(); try { dt.Load(idr); idr.Close(); foreach (DataRow dr in dt.Rows)// while (dr.next ()) { MOrder order = new MOrder(GetCtx(), dr, Get_TrxName()); // New Invoice Location if (!_ConsolidateDocument || (_invoice != null && (_invoice.GetC_BPartner_Location_ID() != order.GetBill_Location_ID() || _invoice.GetC_PaymentTerm_ID() != order.GetC_PaymentTerm_ID()))) { CompleteInvoice(); } bool completeOrder = MOrder.INVOICERULE_AfterOrderDelivered.Equals(order.GetInvoiceRule()); // Schedule After Delivery bool doInvoice = false; if (MOrder.INVOICERULE_CustomerScheduleAfterDelivery.Equals(order.GetInvoiceRule())) { _bp = new MBPartner(GetCtx(), order.GetBill_BPartner_ID(), null); if (_bp.GetC_InvoiceSchedule_ID() == 0) { log.Warning("BPartner has no Schedule - set to After Delivery"); order.SetInvoiceRule(MOrder.INVOICERULE_AfterDelivery); order.Save(); } else { MInvoiceSchedule ins = MInvoiceSchedule.Get(GetCtx(), _bp.GetC_InvoiceSchedule_ID(), Get_TrxName()); if (ins.CanInvoice(order.GetDateOrdered(), order.GetGrandTotal())) { doInvoice = true; } else { continue; } } } // Schedule // After Delivery if (doInvoice || MOrder.INVOICERULE_AfterDelivery.Equals(order.GetInvoiceRule())) { MInOut shipment = null; MInOutLine[] shipmentLines = order.GetShipmentLines(); for (int i = 0; i < shipmentLines.Length; i++) { MInOutLine shipLine = shipmentLines[i]; if (shipLine.IsInvoiced()) { continue; } if (shipment == null || shipment.GetM_InOut_ID() != shipLine.GetM_InOut_ID()) { shipment = new MInOut(GetCtx(), shipLine.GetM_InOut_ID(), Get_TrxName()); } if (!shipment.IsComplete() || // ignore incomplete or reversals shipment.GetDocStatus().Equals(MInOut.DOCSTATUS_Reversed)) { continue; } // CreateLine(order, shipment, shipLine); } // shipment lines _line += 1000; } // After Order Delivered, Immediate else { MOrderLine[] oLines = order.GetLines(true, null); for (int i = 0; i < oLines.Length; i++) { MOrderLine oLine = oLines[i]; Decimal toInvoice = Decimal.Subtract(oLine.GetQtyOrdered(), oLine.GetQtyInvoiced()); if (toInvoice.CompareTo(Env.ZERO) == 0 && oLine.GetM_Product_ID() != 0) { continue; } // bool fullyDelivered = oLine.GetQtyOrdered().CompareTo(oLine.GetQtyDelivered()) == 0; // Complete Order if (completeOrder && !fullyDelivered) { log.Fine("Failed CompleteOrder - " + oLine); completeOrder = false; break; } // Immediate else if (MOrder.INVOICERULE_Immediate.Equals(order.GetInvoiceRule())) { log.Fine("Immediate - ToInvoice=" + toInvoice + " - " + oLine); Decimal qtyEntered = toInvoice; // Correct UOM for QtyEntered if (oLine.GetQtyEntered().CompareTo(oLine.GetQtyOrdered()) != 0) { qtyEntered = Decimal.Round(Decimal.Divide(Decimal.Multiply( toInvoice, oLine.GetQtyEntered()), oLine.GetQtyOrdered()), 12, MidpointRounding.AwayFromZero); } // if (oLine.IsContract() == false) { CreateLine(order, oLine, toInvoice, qtyEntered); log.Info("ID " + oLine.Get_ID() + "Qty Ordered " + oLine.GetQtyOrdered() + " Qty Invoiced " + oLine.GetQtyInvoiced()); } } else { log.Fine("Failed: " + order.GetInvoiceRule() + " - ToInvoice=" + toInvoice + " - " + oLine); } } // for all order lines if (MOrder.INVOICERULE_Immediate.Equals(order.GetInvoiceRule())) { _line += 1000; } } // Complete Order successful if (completeOrder && MOrder.INVOICERULE_AfterOrderDelivered.Equals(order.GetInvoiceRule())) { MInOut[] shipments = order.GetShipments(true); for (int i = 0; i < shipments.Length; i++) { MInOut ship = shipments[i]; if (!ship.IsComplete() || // ignore incomplete or reversals ship.GetDocStatus().Equals(MInOut.DOCSTATUS_Reversed)) { continue; } MInOutLine[] shipLines = ship.GetLines(false); for (int j = 0; j < shipLines.Length; j++) { MInOutLine shipLine = shipLines[j]; if (!order.IsOrderLine(shipLine.GetC_OrderLine_ID())) { continue; } if (!shipLine.IsInvoiced()) { CreateLine(order, ship, shipLine); } } // lines _line += 1000; } // all shipments } // complete Order } // for all orders } catch (Exception e) { if (idr != null) { idr.Close(); } log.Log(Level.SEVERE, "", e); } finally { if (idr != null) { idr.Close(); } dt = null; } CompleteInvoice(); return("@Created@ = " + _created); }
public bool SetProductQty(int recordID, string keyColName, List <string> product, List <string> attribute, List <string> qty, List <string> qtybook, List <string> oline_ID, int ordID, List <string> locID, int lineID, VAdvantage.Utility.Ctx ctx) { if (keyColName.ToUpper().Trim() == "C_ORDER_ID") { MOrder ord = new MOrder(ctx, recordID, null); for (int i = 0; i < product.Count; i++) { MOrderLine oline = new MOrderLine(ctx, lineID, null); oline.SetAD_Client_ID(ord.GetAD_Client_ID()); oline.SetAD_Org_ID(ord.GetAD_Org_ID()); oline.SetM_Product_ID(Util.GetValueOfInt(product[i])); oline.SetQty(Util.GetValueOfDecimal(qty[i])); oline.SetC_Order_ID(recordID); if (Util.GetValueOfInt(attribute[i]) != 0) { oline.SetM_AttributeSetInstance_ID(Util.GetValueOfInt(attribute[i])); } if (!ord.IsSOTrx()) { MProduct pro = new MProduct(ctx, oline.GetM_Product_ID(), null); String qryUom = "SELECT vdr.C_UOM_ID FROM M_Product p LEFT JOIN M_Product_Po vdr ON p.M_Product_ID= vdr.M_Product_ID WHERE p.M_Product_ID=" + oline.GetM_Product_ID() + " AND vdr.C_BPartner_ID = " + ord.GetC_BPartner_ID(); int uom = Util.GetValueOfInt(DB.ExecuteScalar(qryUom)); if (pro.GetC_UOM_ID() != 0) { if (pro.GetC_UOM_ID() != uom && uom != 0) { decimal?Res = Util.GetValueOfDecimal(DB.ExecuteScalar("SELECT trunc(multiplyrate,4) FROM C_UOM_Conversion WHERE C_UOM_ID = " + pro.GetC_UOM_ID() + " AND C_UOM_To_ID = " + uom + " AND M_Product_ID= " + oline.GetM_Product_ID() + " AND IsActive='Y'")); if (Res > 0) { oline.SetQtyEntered(oline.GetQtyEntered() * Res); //OrdQty = MUOMConversion.ConvertProductTo(GetCtx(), _M_Product_ID, UOM, OrdQty); } else { decimal?res = Util.GetValueOfDecimal(DB.ExecuteScalar("SELECT trunc(multiplyrate,4) FROM C_UOM_Conversion WHERE C_UOM_ID = " + pro.GetC_UOM_ID() + " AND C_UOM_To_ID = " + uom + " AND IsActive='Y'")); if (res > 0) { oline.SetQtyEntered(oline.GetQtyEntered() * res); //OrdQty = MUOMConversion.Convert(GetCtx(), prdUOM, UOM, OrdQty); } } oline.SetC_UOM_ID(uom); } else { oline.SetC_UOM_ID(pro.GetC_UOM_ID()); } } } if (!oline.Save()) { } } } else if (keyColName.ToUpper().Trim() == "C_INVOICE_ID") { MInvoice inv = new MInvoice(ctx, recordID, null); for (int i = 0; i < product.Count; i++) { MInvoiceLine invline = new MInvoiceLine(ctx, lineID, null); invline.SetAD_Client_ID(inv.GetAD_Client_ID()); invline.SetAD_Org_ID(inv.GetAD_Org_ID()); invline.SetM_Product_ID(Util.GetValueOfInt(product[i])); invline.SetQty(Util.GetValueOfDecimal(qty[i])); invline.SetC_Invoice_ID(recordID); if (Util.GetValueOfInt(attribute[i]) != 0) { invline.SetM_AttributeSetInstance_ID(Util.GetValueOfInt(attribute[i])); } if (!inv.IsSOTrx()) { MProduct pro = new MProduct(ctx, invline.GetM_Product_ID(), null); String qryUom = "SELECT vdr.C_UOM_ID FROM M_Product p LEFT JOIN M_Product_Po vdr ON p.M_Product_ID= vdr.M_Product_ID WHERE p.M_Product_ID=" + invline.GetM_Product_ID() + " AND vdr.C_BPartner_ID = " + inv.GetC_BPartner_ID(); int uom = Util.GetValueOfInt(DB.ExecuteScalar(qryUom)); if (pro.GetC_UOM_ID() != 0) { if (pro.GetC_UOM_ID() != uom && uom != 0) { decimal?Res = Util.GetValueOfDecimal(DB.ExecuteScalar("SELECT trunc(multiplyrate,4) FROM C_UOM_Conversion WHERE C_UOM_ID = " + pro.GetC_UOM_ID() + " AND C_UOM_To_ID = " + uom + " AND M_Product_ID= " + invline.GetM_Product_ID() + " AND IsActive='Y'")); if (Res > 0) { invline.SetQtyEntered(invline.GetQtyEntered() * Res); //OrdQty = MUOMConversion.ConvertProductTo(GetCtx(), _M_Product_ID, UOM, OrdQty); } else { decimal?res = Util.GetValueOfDecimal(DB.ExecuteScalar("SELECT trunc(multiplyrate,4) FROM C_UOM_Conversion WHERE C_UOM_ID = " + pro.GetC_UOM_ID() + " AND C_UOM_To_ID = " + uom + " AND IsActive='Y'")); if (res > 0) { invline.SetQtyEntered(invline.GetQtyEntered() * res); //OrdQty = MUOMConversion.Convert(GetCtx(), prdUOM, UOM, OrdQty); } } invline.SetC_UOM_ID(uom); } else { invline.SetC_UOM_ID(pro.GetC_UOM_ID()); } } } if (!invline.Save()) { } } } else if (keyColName.ToUpper().Trim() == "M_INOUT_ID") { MInOut inv = new MInOut(ctx, recordID, null); if (ordID > 0) { inv.SetC_Order_ID(ordID); } if (inv.Save()) { for (int i = 0; i < product.Count; i++) { MInOutLine ioline = new MInOutLine(ctx, lineID, null); ioline.SetAD_Client_ID(inv.GetAD_Client_ID()); ioline.SetAD_Org_ID(inv.GetAD_Org_ID()); ioline.SetM_Product_ID(Util.GetValueOfInt(product[i])); ioline.SetQty(Util.GetValueOfDecimal(qty[i])); ioline.SetM_InOut_ID(recordID); ioline.SetC_OrderLine_ID(Util.GetValueOfInt(oline_ID[i])); ioline.SetM_Locator_ID(Util.GetValueOfInt(locID[i])); if (Util.GetValueOfInt(attribute[i]) != 0) { ioline.SetM_AttributeSetInstance_ID(Util.GetValueOfInt(attribute[i])); } if (!inv.IsSOTrx()) { MProduct pro = new MProduct(ctx, ioline.GetM_Product_ID(), null); String qryUom = "SELECT vdr.C_UOM_ID FROM M_Product p LEFT JOIN M_Product_Po vdr ON p.M_Product_ID= vdr.M_Product_ID WHERE p.M_Product_ID=" + ioline.GetM_Product_ID() + " AND vdr.C_BPartner_ID = " + inv.GetC_BPartner_ID(); int uom = Util.GetValueOfInt(DB.ExecuteScalar(qryUom)); if (pro.GetC_UOM_ID() != 0) { if (pro.GetC_UOM_ID() != uom && uom != 0) { decimal?Res = Util.GetValueOfDecimal(DB.ExecuteScalar("SELECT trunc(multiplyrate,4) FROM C_UOM_Conversion WHERE C_UOM_ID = " + pro.GetC_UOM_ID() + " AND C_UOM_To_ID = " + uom + " AND M_Product_ID= " + ioline.GetM_Product_ID() + " AND IsActive='Y'")); if (Res > 0) { ioline.SetQtyEntered(ioline.GetQtyEntered() * Res); //OrdQty = MUOMConversion.ConvertProductTo(GetCtx(), _M_Product_ID, UOM, OrdQty); } else { decimal?res = Util.GetValueOfDecimal(DB.ExecuteScalar("SELECT trunc(multiplyrate,4) FROM C_UOM_Conversion WHERE C_UOM_ID = " + pro.GetC_UOM_ID() + " AND C_UOM_To_ID = " + uom + " AND IsActive='Y'")); if (res > 0) { ioline.SetQtyEntered(ioline.GetQtyEntered() * res); //OrdQty = MUOMConversion.Convert(GetCtx(), prdUOM, UOM, OrdQty); } } ioline.SetC_UOM_ID(uom); } else { ioline.SetC_UOM_ID(pro.GetC_UOM_ID()); } } } if (!ioline.Save()) { } } } } else if (keyColName.ToUpper().Trim() == "M_PACKAGE_ID") { MPackage pkg = new MPackage(ctx, recordID, null); for (int i = 0; i < product.Count; i++) { MPackageLine mline = new MPackageLine(ctx, lineID, null); mline.SetAD_Client_ID(pkg.GetAD_Client_ID()); mline.SetAD_Org_ID(pkg.GetAD_Org_ID()); mline.SetM_Product_ID(Util.GetValueOfInt(product[i])); mline.SetQty(Util.GetValueOfDecimal(qty[i])); if (Util.GetValueOfInt(oline_ID[i]) > 0) { mline.SetM_MovementLine_ID(Util.GetValueOfInt(oline_ID[i])); MMovementLine mov = new MMovementLine(ctx, Util.GetValueOfInt(oline_ID[i]), null); mline.SetDTD001_TotalQty(mov.GetMovementQty()); } if (Util.GetValueOfInt(attribute[i]) != 0) { mline.SetM_AttributeSetInstance_ID(Util.GetValueOfInt(attribute[i])); } mline.SetM_Package_ID(recordID); if (!mline.Save()) { } } } else if (keyColName.ToUpper().Trim() == "M_INVENTORY_ID") { MInventory inv = new MInventory(ctx, recordID, null); for (int i = 0; i < product.Count; i++) { MInventoryLine invline = new MInventoryLine(ctx, lineID, null); invline.SetAD_Client_ID(inv.GetAD_Client_ID()); invline.SetAD_Org_ID(inv.GetAD_Org_ID()); invline.SetM_Locator_ID(Util.GetValueOfInt(locID[i])); invline.SetM_Product_ID(Util.GetValueOfInt(product[i])); invline.SetQtyCount(Util.GetValueOfDecimal(qty[i])); invline.SetQtyBook(Util.GetValueOfDecimal(qtybook[i])); invline.SetAsOnDateCount(Util.GetValueOfDecimal(qty[i])); invline.SetOpeningStock(Util.GetValueOfDecimal(qtybook[i])); invline.SetM_Inventory_ID(recordID); if (Util.GetValueOfInt(attribute[i]) != 0) { invline.SetM_AttributeSetInstance_ID(Util.GetValueOfInt(attribute[i])); } else { invline.SetM_AttributeSetInstance_ID(0); } if (!invline.Save()) { } } } return(true); }
/// <summary> /// Create Invoice. /// </summary> /// <returns>document no</returns> protected override String DoIt() { StringBuilder invDocumentNo = new StringBuilder(); int count = Util.GetValueOfInt(DB.ExecuteScalar(" SELECT Count(*) FROM M_Inout WHERE ISSOTRX='Y' AND M_Inout_ID=" + GetRecord_ID())); MInOut ship = null; bool isAllownonItem = Util.GetValueOfString(GetCtx().GetContext("$AllowNonItem")).Equals("Y"); if (count > 0) { if (_M_InOut_ID == 0) { throw new ArgumentException("No Shipment"); } // ship = new MInOut(GetCtx(), _M_InOut_ID, Get_Trx()); if (ship.Get_ID() == 0) { throw new ArgumentException("Shipment not found"); } if (!MInOut.DOCSTATUS_Completed.Equals(ship.GetDocStatus())) { // JID_0750: done by Bharat on 05 Feb 2019 if Customer Return document and status is not complete it should give message "Customer Return Not Completed". if (ship.IsReturnTrx()) { throw new ArgumentException("Customer Return Not Completed"); } else { throw new ArgumentException("Shipment Not Completed"); } } } else { if (_M_InOut_ID == 0) { throw new ArgumentException("No Material Receipt"); } // ship = new MInOut(GetCtx(), _M_InOut_ID, Get_Trx()); if (ship.Get_ID() == 0) { throw new ArgumentException("Material Receipt not found"); } if (!MInOut.DOCSTATUS_Completed.Equals(ship.GetDocStatus())) { // JID_0750: done by Bharat on 05 Feb 2019 if Return to vendor document and status is not complete it should give message "Return To Vendor Not Completed". if (ship.IsReturnTrx()) { throw new ArgumentException("Return To Vendor Not Completed"); } else { throw new ArgumentException("Material Receipt Not Completed"); } } } // When record contain more than single order and order having different Payment term or Price List then not to generate invoices // JID_0976 - For conversion Type if (ship.GetC_Order_ID() > 0 && Util.GetValueOfInt(DB.ExecuteScalar(@"SELECT COUNT(DISTINCT c_order.m_pricelist_id) + count(distinct c_order.c_paymentterm_id) + count(distinct COALESCE( c_order.C_ConversionType_ID , " + MConversionType.GetDefault(GetAD_Client_ID()) + @")) as recordcount FROM m_inoutline INNER JOIN c_orderline ON m_inoutline.c_orderline_id = c_orderline.c_orderline_id INNER JOIN c_order ON c_order.c_order_id = c_orderline.c_order_id WHERE m_inoutline.m_inout_id = " + _M_InOut_ID + @" GROUP BY m_inoutline.m_inout_id ", null, Get_Trx())) > 3) { if (ship.IsSOTrx()) { //Different Payment Terms, Price list found against the selected orders, use "Generate Invoice" process to create multiple invoices. throw new ArgumentException(Msg.GetMsg(GetCtx(), "VIS_SoDifferentPayAndPrice")); } else { //Different Payment Terms, Price list found against the selected orders throw new ArgumentException(Msg.GetMsg(GetCtx(), "VIS_DifferentPayAndPrice")); } } // Create Invoice Header MInvoice invoice = new MInvoice(ship, null); //Payment Management int _CountVA009 = Env.IsModuleInstalled("VA009_") ? 1 : 0; // Amortization int _CountVA038 = Env.IsModuleInstalled("VA038_") ? 1 : 0; if (_CountVA009 > 0) { int _PaymentMethod_ID = Util.GetValueOfInt(DB.ExecuteScalar("Select VA009_PaymentMethod_ID From C_Order Where C_Order_ID=" + ship.GetC_Order_ID(), null, Get_Trx())); // during consolidation, payment method need to set that is defined on selected business partner. // If not defined on BP then it will set from order int bpPamentMethod_ID = Util.GetValueOfInt(DB.ExecuteScalar(@"SELECT " + (ship.IsSOTrx() ? " VA009_PaymentMethod_ID " : " VA009_PO_PaymentMethod_ID ") + @" FROM C_BPartner WHERE C_BPartner_ID = " + ship.GetC_BPartner_ID(), null, Get_Trx())); if (bpPamentMethod_ID != 0) { _PaymentMethod_ID = bpPamentMethod_ID; } if (_PaymentMethod_ID > 0) { invoice.SetVA009_PaymentMethod_ID(_PaymentMethod_ID); } } // Letter Of Credit int _CountVA026 = Env.IsModuleInstalled("VA026_") ? 1 : 0; if (_CountVA026 > 0) { int VA026_LCDetail_ID = Util.GetValueOfInt(DB.ExecuteScalar("Select VA026_LCDetail_ID From C_Order Where C_Order_ID=" + ship.GetC_Order_ID(), null, Get_Trx())); if (VA026_LCDetail_ID > 0) { invoice.SetVA026_LCDetail_ID(VA026_LCDetail_ID); } } //end if (ship.IsReturnTrx()) { if (!ship.IsSOTrx()) { // Purchase Return // set target document from documnet type window -- based on documnet type available on material receipt / return to vendor // JID_0779: Create AP Credit memo if we run the Generate TO process from Returm to Vendor window. //if (invoice.GetC_DocTypeTarget_ID() == 0) //{ if (_C_DocType_ID > 0) { invoice.SetC_DocTypeTarget_ID(_C_DocType_ID); } else { int C_DocTypeTarget_ID = DB.GetSQLValue(null, "SELECT C_DocTypeInvoice_ID FROM C_DocType WHERE C_DocType_ID=@param1", ship.GetC_DocType_ID()); if (C_DocTypeTarget_ID > 0) { invoice.SetC_DocTypeTarget_ID(C_DocTypeTarget_ID); } else { invoice.SetC_DocTypeTarget_ID(ship.IsSOTrx() ? MDocBaseType.DOCBASETYPE_ARCREDITMEMO : MDocBaseType.DOCBASETYPE_APCREDITMEMO); } } invoice.SetIsReturnTrx(ship.IsReturnTrx()); invoice.SetIsSOTrx(ship.IsSOTrx()); } else { // Sales Return if (_C_DocType_ID > 0) { invoice.SetC_DocTypeTarget_ID(_C_DocType_ID); } else { if (ship.GetC_Order_ID() >= 0) { int C_DocType_ID = Util.GetValueOfInt(DB.ExecuteScalar("Select C_DocType_ID From C_Order Where C_Order_ID=" + ship.GetC_Order_ID(), null, Get_Trx())); MDocType dt = MDocType.Get(GetCtx(), C_DocType_ID); if (dt.GetC_DocTypeInvoice_ID() != 0) { invoice.SetC_DocTypeTarget_ID(dt.GetC_DocTypeInvoice_ID(), true); } else { invoice.SetC_DocTypeTarget_ID(ship.IsSOTrx() ? MDocBaseType.DOCBASETYPE_ARCREDITMEMO : MDocBaseType.DOCBASETYPE_APCREDITMEMO); } } else { invoice.SetC_DocTypeTarget_ID(ship.IsSOTrx() ? MDocBaseType.DOCBASETYPE_ARCREDITMEMO : MDocBaseType.DOCBASETYPE_APCREDITMEMO); } } } } if (_M_PriceList_ID != 0) { invoice.SetM_PriceList_ID(_M_PriceList_ID); } //Set InvoiceDocumentNo to InvoiceReference if (_InvoiceDocumentNo != null && _InvoiceDocumentNo.Length > 0) { invoice.Set_Value("InvoiceReference", _InvoiceDocumentNo); } //Set TargetDoctype if (_C_DocType_ID > 0 && !ship.IsReturnTrx()) { invoice.Set_Value("C_DocTypeTarget_ID", _C_DocType_ID); } // Added by Bharat on 30 Jan 2018 to set Inco Term from Order if (invoice.Get_ColumnIndex("C_IncoTerm_ID") > 0) { invoice.SetC_IncoTerm_ID(ship.GetC_IncoTerm_ID()); } //To get Payment Rule and set the Payment method if (invoice.GetPaymentRule() != "") { invoice.SetPaymentMethod(invoice.GetPaymentRule()); } if (!invoice.Save()) { //SI_0708 - message was not upto the mark ValueNamePair pp = VAdvantage.Logging.VLogger.RetrieveError(); if (pp != null) { throw new ArgumentException("Cannot save Invoice. " + pp.GetName()); } throw new ArgumentException("Cannot save Invoice"); } MInOutLine[] shipLines = ship.GetLines(false); DateTime? AmortStartDate = null; DateTime? AmortEndDate = null; count = 0; DataSet ds = null; DataSet dsDoc = null; for (int i = 0; i < shipLines.Length; i++) { MInOutLine sLine = shipLines[i]; // Changes done by Bharat on 06 July 2017 restrict to create invoice if Invoice already created against that for same quantity string sql = @"SELECT ml.QtyEntered - SUM(COALESCE(li.QtyEntered,0)) as QtyEntered, ml.MovementQty- SUM(COALESCE(li.QtyInvoiced, 0)) as QtyInvoiced" + " FROM M_InOutLine ml INNER JOIN C_InvoiceLine li ON li.M_InOutLine_ID = ml.M_InOutLine_ID INNER JOIN C_Invoice ci ON ci.C_Invoice_ID = li.C_Invoice_ID " + " WHERE ci.DocStatus NOT IN ('VO', 'RE') AND ml.M_InOutLine_ID =" + sLine.GetM_InOutLine_ID() + " GROUP BY ml.MovementQty, ml.QtyEntered"; ds = DB.ExecuteDataset(sql, null, Get_Trx()); if (ds != null && ds.Tables[0].Rows.Count > 0) { decimal qtyEntered = Util.GetValueOfDecimal(ds.Tables[0].Rows[0]["QtyEntered"]); decimal qtyInvoiced = Util.GetValueOfDecimal(ds.Tables[0].Rows[0]["QtyInvoiced"]); if (qtyEntered <= 0) { // Getting document number Count if Invoice already generated for Material Receipt string StrSql = "SELECT ci.DocumentNo,li.M_InOutLine_ID FROM C_InvoiceLine li INNER JOIN C_Invoice ci ON ci.C_Invoice_ID = li.C_Invoice_ID " + " WHERE ci.DocStatus NOT IN ('VO', 'RE') AND li.M_InOutLine_ID = " + sLine.GetM_InOutLine_ID(); dsDoc = DB.ExecuteDataset(StrSql, null, Get_Trx()); if (dsDoc != null && dsDoc.Tables[0].Rows.Count > 0) { for (int j = 0; j < dsDoc.Tables[0].Rows.Count; j++) { // JID_1358: Need to show document number in message if Invoice already generated for Material Receipt string no = invDocumentNo.ToString(); if (invDocumentNo.Length > 0 && no != Util.GetValueOfString(dsDoc.Tables[0].Rows[j]["DocumentNo"])) { invDocumentNo.Append(", " + Util.GetValueOfString(dsDoc.Tables[0].Rows[j]["DocumentNo"])); } else { invDocumentNo.Clear(); invDocumentNo.Append(Util.GetValueOfString(dsDoc.Tables[0].Rows[j]["DocumentNo"])); } ds.Dispose(); log.Info("Invoice Line already exist for Receipt Line ID - " + sLine.GetM_InOutLine_ID()); continue; } dsDoc.Dispose(); } } else { MInvoiceLine line = new MInvoiceLine(invoice); line.SetShipLine(sLine); line.SetQtyEntered(qtyEntered); line.SetQtyInvoiced(qtyInvoiced); // Change By Mohit Amortization process ------------- if (_CountVA038 > 0) { if (line.GetM_Product_ID() > 0) { //MProduct pro = new MProduct(GetCtx(), sLine.GetM_Product_ID(), Get_TrxName()); int VA038_AmortizationTemplate_ID = Util.GetValueOfInt(DB.ExecuteScalar(@"SELECT VA038_AmortizationTemplate_ID FROM M_Product WHERE M_Product_ID = " + sLine.GetM_Product_ID(), null, Get_Trx())); if (VA038_AmortizationTemplate_ID > 0) { line.Set_Value("VA038_AmortizationTemplate_ID", VA038_AmortizationTemplate_ID); DataSet amrtDS = DB.ExecuteDataset("SELECT VA038_AmortizationType,VA038_AmortizationPeriod,VA038_TermSource,VA038_PeriodType,Name FROM VA038_AmortizationTemplate WHERE IsActive='Y' AND VA038_AMORTIZATIONTEMPLATE_ID=" + VA038_AmortizationTemplate_ID); AmortStartDate = null; AmortEndDate = null; if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_TermSource"]) == "A") { AmortStartDate = invoice.GetDateAcct(); } if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_TermSource"]) == "T") { AmortStartDate = invoice.GetDateInvoiced(); } if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_PeriodType"]) == "M") { AmortEndDate = AmortStartDate.Value.AddMonths(Util.GetValueOfInt(amrtDS.Tables[0].Rows[0]["VA038_AmortizationPeriod"])); } if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_PeriodType"]) == "Y") { AmortEndDate = AmortStartDate.Value.AddYears(Util.GetValueOfInt(amrtDS.Tables[0].Rows[0]["VA038_AmortizationPeriod"])); } line.Set_Value("FROMDATE", AmortStartDate); line.Set_Value("EndDate", AmortEndDate); if (amrtDS != null) { amrtDS.Dispose(); } } } if (line.GetC_Charge_ID() > 0) { //MCharge charge = new MCharge(GetCtx(), sLine.GetC_Charge_ID(), Get_TrxName()); int VA038_AmortizationTemplate_ID = Util.GetValueOfInt(DB.ExecuteScalar(@"SELECT VA038_AmortizationTemplate_ID FROM C_Charge WHERE C_Charge_ID = " + sLine.GetC_Charge_ID(), null, Get_Trx())); if (VA038_AmortizationTemplate_ID > 0) { line.Set_Value("VA038_AmortizationTemplate_ID", VA038_AmortizationTemplate_ID); DataSet amrtDS = DB.ExecuteDataset("SELECT VA038_AmortizationType,VA038_AmortizationPeriod,VA038_TermSource,VA038_PeriodType,Name FROM VA038_AmortizationTemplate WHERE IsActive='Y' AND VA038_AMORTIZATIONTEMPLATE_ID=" + VA038_AmortizationTemplate_ID); AmortStartDate = null; AmortEndDate = null; if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_TermSource"]) == "A") { AmortStartDate = invoice.GetDateAcct(); } if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_TermSource"]) == "T") { AmortStartDate = invoice.GetDateInvoiced(); } if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_PeriodType"]) == "M") { AmortEndDate = AmortStartDate.Value.AddMonths(Util.GetValueOfInt(amrtDS.Tables[0].Rows[0]["VA038_AmortizationPeriod"])); } if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_PeriodType"]) == "Y") { AmortEndDate = AmortStartDate.Value.AddYears(Util.GetValueOfInt(amrtDS.Tables[0].Rows[0]["VA038_AmortizationPeriod"])); } line.Set_Value("FROMDATE", AmortStartDate); line.Set_Value("EndDate", AmortEndDate); if (amrtDS != null) { amrtDS.Dispose(); } } } } // End Change Amortization process-------------- if (!line.Save()) { //SI_0708 - message was not upto the mark ValueNamePair pp = VAdvantage.Logging.VLogger.RetrieveError(); if (pp != null) { throw new ArgumentException("Cannot save Invoice Line. " + pp.GetName()); } throw new ArgumentException("Cannot save Invoice Line"); } count++; } ds.Dispose(); } else { MInvoiceLine line = new MInvoiceLine(invoice); // JID_1850 Avoid the duplicate charge line if (sLine.GetC_Charge_ID() > 0 && (!isAllownonItem || _GenerateCharges)) { continue; } line.SetShipLine(sLine); line.SetQtyEntered(sLine.GetQtyEntered()); line.SetQtyInvoiced(sLine.GetMovementQty()); line.Set_ValueNoCheck("IsDropShip", sLine.Get_Value("IsDropShip")); //Arpit Rai 20-Sept-2017 // Change By Mohit Amortization process ------------- if (_CountVA038 > 0) { if (line.GetM_Product_ID() > 0) { //MProduct pro = new MProduct(GetCtx(), sLine.GetM_Product_ID(), Get_TrxName()); int VA038_AmortizationTemplate_ID = Util.GetValueOfInt(DB.ExecuteScalar(@"SELECT VA038_AmortizationTemplate_ID FROM M_Product WHERE M_Product_ID = " + sLine.GetM_Product_ID(), null, Get_Trx())); if (VA038_AmortizationTemplate_ID > 0) { line.Set_Value("VA038_AmortizationTemplate_ID", VA038_AmortizationTemplate_ID); DataSet amrtDS = DB.ExecuteDataset("SELECT VA038_AmortizationType,VA038_AmortizationPeriod,VA038_TermSource,VA038_PeriodType,Name FROM VA038_AmortizationTemplate WHERE IsActive='Y' AND VA038_AMORTIZATIONTEMPLATE_ID=" + VA038_AmortizationTemplate_ID); AmortStartDate = null; AmortEndDate = null; if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_TermSource"]) == "A") { AmortStartDate = invoice.GetDateAcct(); } if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_TermSource"]) == "T") { AmortStartDate = invoice.GetDateInvoiced(); } if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_PeriodType"]) == "M") { AmortEndDate = AmortStartDate.Value.AddMonths(Util.GetValueOfInt(amrtDS.Tables[0].Rows[0]["VA038_AmortizationPeriod"])); } if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_PeriodType"]) == "Y") { AmortEndDate = AmortStartDate.Value.AddYears(Util.GetValueOfInt(amrtDS.Tables[0].Rows[0]["VA038_AmortizationPeriod"])); } line.Set_Value("FROMDATE", AmortStartDate); line.Set_Value("EndDate", AmortEndDate); if (amrtDS != null) { amrtDS.Dispose(); } } } if (line.GetC_Charge_ID() > 0) { //MCharge charge = new MCharge(GetCtx(), sLine.GetC_Charge_ID(), Get_TrxName()); int VA038_AmortizationTemplate_ID = Util.GetValueOfInt(DB.ExecuteScalar(@"SELECT VA038_AmortizationTemplate_ID FROM C_Charge WHERE C_Charge_ID = " + sLine.GetC_Charge_ID(), null, Get_Trx())); if (VA038_AmortizationTemplate_ID > 0) { line.Set_Value("VA038_AmortizationTemplate_ID", VA038_AmortizationTemplate_ID); DataSet amrtDS = DB.ExecuteDataset("SELECT VA038_AmortizationType,VA038_AmortizationPeriod,VA038_TermSource,VA038_PeriodType,Name FROM VA038_AmortizationTemplate WHERE IsActive='Y' AND VA038_AMORTIZATIONTEMPLATE_ID=" + VA038_AmortizationTemplate_ID); AmortStartDate = null; AmortEndDate = null; if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_TermSource"]) == "A") { AmortStartDate = invoice.GetDateAcct(); } if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_TermSource"]) == "T") { AmortStartDate = invoice.GetDateInvoiced(); } if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_PeriodType"]) == "M") { AmortEndDate = AmortStartDate.Value.AddMonths(Util.GetValueOfInt(amrtDS.Tables[0].Rows[0]["VA038_AmortizationPeriod"])); } if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_PeriodType"]) == "Y") { AmortEndDate = AmortStartDate.Value.AddYears(Util.GetValueOfInt(amrtDS.Tables[0].Rows[0]["VA038_AmortizationPeriod"])); } line.Set_Value("FROMDATE", AmortStartDate); line.Set_Value("EndDate", AmortEndDate); if (amrtDS != null) { amrtDS.Dispose(); } } } } // End Change Amortization process-------------- if (!line.Save()) { //SI_0708 - message was not upto the mark ValueNamePair pp = VAdvantage.Logging.VLogger.RetrieveError(); if (pp != null) { throw new ArgumentException("Cannot save Invoice Line. " + pp.GetName()); } throw new ArgumentException("Cannot save Invoice Line"); } count++; } } #region [Enhancement for Charges Distribution/Generation by Sukhwinder on 13 December 2017] if (_GenerateCharges && count > 0) { StringBuilder OrderSql = new StringBuilder(); OrderSql.Append(" SELECT CO.C_ORDER_ID, " + " SUM(ML.QTYENTERED) AS MRLINEQTY, " + " SUM(OL.QTYENTERED) AS ORDERQTY " + " FROM M_INOUTLINE ML " + " INNER JOIN C_ORDERLINE OL " + " ON OL.C_ORDERLINE_ID = ML.C_ORDERLINE_ID " + " INNER JOIN C_ORDER CO " + " ON CO.C_ORDER_ID = OL.C_ORDER_ID " + " WHERE ML.M_INOUT_ID = " + _M_InOut_ID + " AND (OL.C_CHARGE_ID IS NULL " + " OR OL.C_CHARGE_ID = 0) " + " GROUP BY CO.C_ORDER_ID "); DataSet OrderDS = DB.ExecuteDataset(OrderSql.ToString(), null, Get_Trx()); if (OrderDS != null && OrderDS.Tables[0].Rows.Count > 0) { StringBuilder ChargesSql = new StringBuilder(); for (int index = 0; index < OrderDS.Tables[0].Rows.Count; index++) { ds = null; ChargesSql.Clear(); ChargesSql.Append(" SELECT C_CHARGE_ID, " + " C_ORDERLINE_ID, " + " C_ORDER_ID, " + " C_CURRENCY_ID, " + " PRICEENTERED, " + " PRICEACTUAL, " + " LINENETAMT, " + " QTYENTERED, " + " C_UOM_ID, " + " C_Tax_ID, " + " IsDropShip " + " FROM C_ORDERLINE " + " WHERE C_ORDER_ID IN " + " ( " + Util.GetValueOfInt(OrderDS.Tables[0].Rows[index]["C_ORDER_ID"]) + " ) " + " AND C_CHARGE_ID IS NOT NULL " + " AND C_CHARGE_ID > 0 "); ds = DB.ExecuteDataset(ChargesSql.ToString(), null, Get_Trx()); if (ds != null && ds.Tables[0].Rows.Count > 0) { for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { MInvoiceLine line = new MInvoiceLine(invoice); line.SetQty(1); line.SetQtyEntered(1); line.SetQtyInvoiced(1); line.SetOrderLine(new MOrderLine(GetCtx(), Util.GetValueOfInt(ds.Tables[0].Rows[i]["C_ORDERLINE_ID"]), Get_Trx())); line.SetC_Charge_ID(Util.GetValueOfInt(ds.Tables[0].Rows[i]["C_CHARGE_ID"])); line.SetC_UOM_ID(Util.GetValueOfInt(ds.Tables[0].Rows[i]["C_UOM_ID"])); line.SetC_Tax_ID(Util.GetValueOfInt(ds.Tables[0].Rows[i]["C_TAX_ID"])); decimal SumOfQty = 0; if (Util.GetValueOfInt(OrderDS.Tables[0].Rows[index]["ORDERQTY"]) == 0) { SumOfQty = 1; } else { SumOfQty = Util.GetValueOfInt(OrderDS.Tables[0].Rows[index]["ORDERQTY"]); } decimal amt = (Util.GetValueOfDecimal(ds.Tables[0].Rows[i]["LINENETAMT"]) / SumOfQty) * Util.GetValueOfInt(OrderDS.Tables[0].Rows[index]["MRLINEQTY"]); line.SetPrice(Decimal.Round(amt, 3)); line.SetPriceActual(Decimal.Round(amt, 3)); line.SetPriceEntered(Decimal.Round(amt, 3)); line.SetLineNetAmt(Decimal.Round(amt, 3)); line.Set_ValueNoCheck("IsDropShip", Util.GetValueOfString(ds.Tables[0].Rows[i]["ISDROPSHIP"])); if (_CountVA038 > 0) { if (line.GetC_Charge_ID() > 0) { MCharge charge = new MCharge(GetCtx(), line.GetC_Charge_ID(), Get_TrxName()); if (Util.GetValueOfInt(charge.Get_Value("VA038_AmortizationTemplate_ID")) > 0) { line.Set_Value("VA038_AmortizationTemplate_ID", Util.GetValueOfInt(charge.Get_Value("VA038_AmortizationTemplate_ID"))); DataSet amrtDS = DB.ExecuteDataset("SELECT VA038_AmortizationType,VA038_AmortizationPeriod,VA038_TermSource,VA038_PeriodType,Name FROM VA038_AmortizationTemplate WHERE IsActive='Y' AND VA038_AMORTIZATIONTEMPLATE_ID=" + Util.GetValueOfInt(charge.Get_Value("VA038_AmortizationTemplate_ID"))); AmortStartDate = null; AmortEndDate = null; if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_TermSource"]) == "A") { AmortStartDate = invoice.GetDateAcct(); } if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_TermSource"]) == "T") { AmortStartDate = invoice.GetDateInvoiced(); } if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_PeriodType"]) == "M") { AmortEndDate = AmortStartDate.Value.AddMonths(Util.GetValueOfInt(amrtDS.Tables[0].Rows[0]["VA038_AmortizationPeriod"])); } if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_PeriodType"]) == "Y") { AmortEndDate = AmortStartDate.Value.AddYears(Util.GetValueOfInt(amrtDS.Tables[0].Rows[0]["VA038_AmortizationPeriod"])); } line.Set_Value("FROMDATE", AmortStartDate); line.Set_Value("EndDate", AmortEndDate); if (amrtDS != null) { amrtDS.Dispose(); } } } } if (!line.Save()) { //SI_0708 - message was not upto the mark ValueNamePair pp = VAdvantage.Logging.VLogger.RetrieveError(); if (pp != null) { throw new ArgumentException("Cannot save Invoice Line. " + pp.GetName()); } throw new ArgumentException("Cannot save Invoice Line"); } } } } } } #endregion if (count > 0) { return(invoice.GetDocumentNo()); } else { //Get_Trx().Rollback(); throw new ArgumentException(Msg.GetMsg(GetCtx(), "InvoiceExist") + ": " + invDocumentNo.ToString()); } }
/// <summary> /// Create Shipment /// </summary> /// <returns>info</returns> protected override String DoIt() { //log.info("C_Invoice_ID=" + _C_Invoice_ID // + ", M_Warehouse_ID=" + _M_Warehouse_ID // + ", C_DocType_ID=" + _C_DocType_ID); if (_C_Invoice_ID == 0) { throw new ArgumentException("@NotFound@ @C_Invoice_ID@"); } if (_M_Warehouse_ID == 0) { throw new ArgumentException("@NotFound@ @M_Warehouse_ID@"); } // MInvoice invoice = new MInvoice(GetCtx(), _C_Invoice_ID, Get_Trx()); if (invoice.Get_ID() == 0) { throw new ArgumentException("@NotFound@ @C_Invoice_ID@"); } if (!MInvoice.DOCSTATUS_Completed.Equals(invoice.GetDocStatus())) { throw new ArgumentException("@InvoiceCreateDocNotCompleted@"); } MDocType dt = MDocType.Get(GetCtx(), _C_DocType_ID); if (invoice.IsSOTrx() != dt.IsSOTrx() || invoice.IsReturnTrx() != dt.IsReturnTrx()) { throw new ArgumentException("@C_DocType_ID@ <> @C_Invoice_ID@"); } //*****************************Vikas 1 Dec 2015 ********************************* //Case Msg Not Showing Proper MInOut ship = null; MOrder ord = new MOrder(GetCtx(), invoice.GetC_Order_ID(), null); if (ord.GetC_BPartner_ID() > 0) { ship = new MInOut(invoice, _C_DocType_ID, null, _M_Warehouse_ID); // Change by Mohit Asked by Amardeep sir 02/03/2016 ship.SetPOReference(invoice.GetPOReference()); // End if (!ship.Save()) { return(GetRetrievedError(ship, "@SaveError@ Receipt")); // throw new ArgumentException("@SaveError@ Receipt"); } } else { return(GetRetrievedError(ship, "InvoiceNotLinkedWithPO")); //throw new ArgumentException("@InvoiceNotLinkedWithPO@"); } /* * MInOut ship = new MInOut(invoice, _C_DocType_ID, null, _M_Warehouse_ID); * if (!ship.Save()) * { * throw new ArgumentException("@SaveError@ Receipt"); * } */ //************************END***************************************** MInvoiceLine[] invoiceLines = invoice.GetLines(false); for (int i = 0; i < invoiceLines.Length; i++) { MInvoiceLine invoiceLine = invoiceLines[i]; MProduct product = invoiceLine.GetProduct(); // Nothing to Deliver // Get the lines of Invoice based on the setting taken on Tenant to allow non item Product if (Util.GetValueOfString(GetCtx().GetContext("$AllowNonItem")).Equals("N") && ((product != null && product.GetProductType() != MProduct.PRODUCTTYPE_Item) || invoiceLine.GetC_Charge_ID() != 0)) { continue; } MInOutLine sLine = new MInOutLine(ship); //JID_1679 Generate Receipt from Invoice(Vendor) for remaining quantity //decimal movementqty = 0; //if (invoiceLine.GetC_OrderLine_ID() != 0) //{ // decimal? res = 0; // movementqty = Util.GetValueOfDecimal(DB.ExecuteScalar(@" select (QtyOrdered-sum(MovementQty)) from C_OrderLine ol Inner join M_InOutLine il on il.C_orderline_ID= ol.C_Orderline_Id " // + " WHERE il.C_OrderLine_ID =" + invoiceLine.GetC_OrderLine_ID() + "group by QtyOrdered", null, Get_Trx())); // // in case of partial receipt // if (invoiceLine.GetQtyInvoiced() > movementqty && movementqty != 0) // { // if (product.GetC_UOM_ID() != invoiceLine.GetC_UOM_ID()) // { // res = MUOMConversion.ConvertProductTo(GetCtx(), product.GetM_Product_ID(), invoiceLine.GetC_UOM_ID(), movementqty); // } // sLine.SetInvoiceLine(invoiceLine, 0, // Locator // invoice.IsSOTrx() ? (movementqty) : Env.ZERO); // sLine.SetQtyEntered(res == 0 ? (movementqty) : res); // sLine.SetMovementQty(movementqty); // } // // if QtyInvoiced is less or No Material receipt is found against the order // else // { // sLine.SetInvoiceLine(invoiceLine, 0, // Locator // invoice.IsSOTrx() ? invoiceLine.GetQtyInvoiced() : Env.ZERO); // sLine.SetQtyEntered(invoiceLine.GetQtyEntered()); // sLine.SetMovementQty(invoiceLine.GetQtyInvoiced()); // } //} //else //{ sLine.SetInvoiceLine(invoiceLine, 0, // Locator invoice.IsSOTrx() ? invoiceLine.GetQtyInvoiced() : Env.ZERO); sLine.SetQtyEntered(invoiceLine.GetQtyEntered()); sLine.SetMovementQty(invoiceLine.GetQtyInvoiced()); //} if (invoice.IsCreditMemo()) { sLine.SetQtyEntered(Decimal.Negate(sLine.GetQtyEntered())); //.negate()); sLine.SetMovementQty(Decimal.Negate(sLine.GetMovementQty())); //.negate()); } if (!sLine.Save()) { ship.Get_Trx().Rollback(); //if (movementqty == 0) //{ // _processMsg += ", LineNo: " + invoiceLine.GetLine() + Msg.GetMsg(GetCtx(), "MRIsAlreadyCreated"); // return _processMsg; //} //else //{ return(GetRetrievedError(sLine, "@SaveError@ @M_InOutLine_ID@")); //} // throw new ArgumentException("@SaveError@ @M_InOutLine_ID@"); } invoiceLine.SetM_InOutLine_ID(sLine.GetM_InOutLine_ID()); // _processMsg+= ", LineNo: "+invoiceLine.GetLine()+Msg.GetMsg(GetCtx(), "MRCreatedWithDocNo" + ship.GetDocumentNo()); if (!invoiceLine.Save()) { return(GetRetrievedError(invoiceLine, "@SaveError@ @C_InvoiceLine_ID@")); //throw new ArgumentException("@SaveError@ @C_InvoiceLine_ID@"); } } return(ship.GetDocumentNo()); }
/// <summary> /// Create Facts (the accounting logic) for /// MXI. /// (single line) /// <pre> /// NotInvoicedReceipts DR (Receipt Org) /// InventoryClearing CR /// InvoicePV DR CR (difference) /// Commitment /// Expense CR /// Offset DR /// </pre> /// </summary> /// <param name="as1"></param> /// <returns></returns> public override List <Fact> CreateFacts(MAcctSchema as1) { List <Fact> facts = new List <Fact>(); // Nothing to do if (GetM_Product_ID() == 0 || // no Product Env.Signum(GetQty().Value) == 0 || Env.Signum(_receiptLine.GetMovementQty()) == 0) // Qty = 0 { log.Fine("No Product/Qty - M_Product_ID=" + GetM_Product_ID() + ",Qty=" + GetQty() + ",InOutQty=" + _receiptLine.GetMovementQty()); return(facts); } MMatchInv matchInv = (MMatchInv)GetPO(); // create Fact Header Fact fact = new Fact(this, as1, Fact.POST_Actual); SetC_Currency_ID(as1.GetC_Currency_ID()); /** Needs to be handeled in PO Matching as1 no Receipt info * if (_pc.isService()) * { * log.Fine("Service - skipped"); * return fact; * } **/ // NotInvoicedReceipt DR // From Receipt Decimal multiplier = Math.Abs(Decimal.Round(Decimal.Divide(GetQty().Value, _receiptLine.GetMovementQty()), 12, MidpointRounding.AwayFromZero)); FactLine dr = fact.CreateLine(null, GetAccount(Doc.ACCTTYPE_NotInvoicedReceipts, as1), as1.GetC_Currency_ID(), Env.ONE, null); // updated below if (dr == null) { _error = "No Product Costs"; return(null); } dr.SetQty(GetQty()); // dr.setM_Locator_ID(_receiptLine.getM_Locator_ID()); // MInOut receipt = _receiptLine.getParent(); // dr.setLocationFromBPartner(receipt.getC_BPartner_Location_ID(), true); // from Loc // dr.setLocationFromLocator(_receiptLine.getM_Locator_ID(), false); // to Loc Decimal temp = dr.GetAcctBalance(); // Set AmtAcctCr/Dr from Receipt (sets also Project) if (!dr.UpdateReverseLine(MInOut.Table_ID, // Amt updated _receiptLine.GetM_InOut_ID(), _receiptLine.GetM_InOutLine_ID(), multiplier)) { _error = "Mat.Receipt not posted yet"; return(null); } log.Fine("CR - Amt(" + temp + "->" + dr.GetAcctBalance() + ") - " + dr.ToString()); // InventoryClearing CR // From Invoice MAccount expense = _pc.GetAccount(ProductCost.ACCTTYPE_P_InventoryClearing, as1); if (_pc.IsService()) { expense = _pc.GetAccount(ProductCost.ACCTTYPE_P_Expense, as1); } Decimal LineNetAmt = _invoiceLine.GetLineNetAmt(); multiplier = Math.Abs(Decimal.Round(Decimal.Divide(GetQty().Value, _invoiceLine.GetQtyInvoiced()), 12, MidpointRounding.AwayFromZero)); if (multiplier.CompareTo(Env.ONE) != 0) { LineNetAmt = Decimal.Multiply(LineNetAmt, multiplier); } if (_pc.IsService()) { LineNetAmt = dr.GetAcctBalance(); // book out exact receipt amt } FactLine cr = null; if (as1.IsAccrual()) { cr = fact.CreateLine(null, expense, as1.GetC_Currency_ID(), null, LineNetAmt); // updated below if (cr == null) { log.Fine("Line Net Amt=0 - M_Product_ID=" + GetM_Product_ID() + ",Qty=" + GetQty() + ",InOutQty=" + _receiptLine.GetMovementQty()); facts.Add(fact); return(facts); } cr.SetQty(Decimal.Negate(GetQty().Value)); temp = cr.GetAcctBalance(); // Set AmtAcctCr/Dr from Invoice (sets also Project) if (as1.IsAccrual() && !cr.UpdateReverseLine(MInvoice.Table_ID, // Amt updated _invoiceLine.GetC_Invoice_ID(), _invoiceLine.GetC_InvoiceLine_ID(), multiplier)) { _error = "Invoice not posted yet"; return(null); } log.Fine("DR - Amt(" + temp + "->" + cr.GetAcctBalance() + ") - " + cr.ToString()); } else // Cash Acct { MInvoice invoice = _invoiceLine.GetParent(); if (as1.GetC_Currency_ID() == invoice.GetC_Currency_ID()) { LineNetAmt = MConversionRate.Convert(GetCtx(), LineNetAmt, invoice.GetC_Currency_ID(), as1.GetC_Currency_ID(), invoice.GetDateAcct(), invoice.GetC_ConversionType_ID(), invoice.GetAD_Client_ID(), invoice.GetAD_Org_ID()); } cr = fact.CreateLine(null, expense, as1.GetC_Currency_ID(), null, LineNetAmt); cr.SetQty(Decimal.Negate(Decimal.Multiply(GetQty().Value, multiplier))); } cr.SetC_Activity_ID(_invoiceLine.GetC_Activity_ID()); cr.SetC_Campaign_ID(_invoiceLine.GetC_Campaign_ID()); cr.SetC_Project_ID(_invoiceLine.GetC_Project_ID()); cr.SetC_UOM_ID(_invoiceLine.GetC_UOM_ID()); cr.SetUser1_ID(_invoiceLine.GetUser1_ID()); cr.SetUser2_ID(_invoiceLine.GetUser2_ID()); // Invoice Price Variance difference Decimal ipv = Decimal.Negate(Decimal.Add(cr.GetAcctBalance(), dr.GetAcctBalance())); if (Env.Signum(ipv) != 0) { FactLine pv = fact.CreateLine(null, _pc.GetAccount(ProductCost.ACCTTYPE_P_IPV, as1), as1.GetC_Currency_ID(), ipv); pv.SetC_Activity_ID(_invoiceLine.GetC_Activity_ID()); pv.SetC_Campaign_ID(_invoiceLine.GetC_Campaign_ID()); pv.SetC_Project_ID(_invoiceLine.GetC_Project_ID()); pv.SetC_UOM_ID(_invoiceLine.GetC_UOM_ID()); pv.SetUser1_ID(_invoiceLine.GetUser1_ID()); pv.SetUser2_ID(_invoiceLine.GetUser2_ID()); } log.Fine("IPV=" + ipv + "; Balance=" + fact.GetSourceBalance()); MInOut inOut = _receiptLine.GetParent(); bool isReturnTrx = inOut.IsReturnTrx(); if (!IsPosted()) { // Cost Detail Record - data from Expense/IncClearing (CR) record MCostDetail.CreateInvoice(as1, GetAD_Org_ID(), GetM_Product_ID(), matchInv.GetM_AttributeSetInstance_ID(), _invoiceLine.GetC_InvoiceLine_ID(), 0, // No cost element Decimal.Negate(cr.GetAcctBalance()), isReturnTrx ? Decimal.Negate(Utility.Util.GetValueOfDecimal(GetQty())) : Utility.Util.GetValueOfDecimal(GetQty()), // correcting GetDescription(), GetTrx(), GetRectifyingProcess()); // Update Costing UpdateProductInfo(as1.GetC_AcctSchema_ID(), MAcctSchema.COSTINGMETHOD_StandardCosting.Equals(as1.GetCostingMethod())); } // facts.Add(fact); /** Commitment release ****/ if (as1.IsAccrual() && as1.IsCreateCommitment()) { fact = Doc_Order.GetCommitmentRelease(as1, this, Utility.Util.GetValueOfDecimal(GetQty()), _invoiceLine.GetC_InvoiceLine_ID(), Env.ONE); if (fact == null) { return(null); } facts.Add(fact); } // Commitment return(facts); }