/**
         *  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);
        }
        public JsonResult GetInOutLine(string param)
        {
            string retError = "";
            string retJSON  = "";

            if (Session["ctx"] != null)
            {
                VAdvantage.Utility.Ctx ctx         = Session["ctx"] as Ctx;
                string[] paramValue                = param.Split(',');
                Dictionary <String, String> retDic = new Dictionary <string, string>();
                int id;

                //Assign parameter value
                id = Util.GetValueOfInt(paramValue[0].ToString());
                MInOutLine Orig_InOutLine = new MInOutLine(ctx, id, null);
                retDic["MovementQty"]               = Orig_InOutLine.GetMovementQty().ToString();
                retDic["C_Project_ID"]              = Orig_InOutLine.GetC_Project_ID().ToString();
                retDic["C_Campaign_ID"]             = Orig_InOutLine.GetC_Campaign_ID().ToString();
                retDic["M_Product_ID"]              = Orig_InOutLine.GetM_Product_ID().ToString();
                retDic["M_AttributeSetInstance_ID"] = Orig_InOutLine.GetM_AttributeSetInstance_ID().ToString();
                retDic["C_UOM_ID"] = Orig_InOutLine.GetC_UOM_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));
        }
Beispiel #3
0
        public JsonResult GetMovementQty(string fields)
        {
            string retError = "";
            string retJSON  = "";

            if (Session["ctx"] != null)
            {
                VAdvantage.Utility.Ctx ctx = Session["ctx"] as Ctx;
                string[] paramValue        = fields.Split(',');
                int      inOutLine_ID;

                //Assign parameter value
                inOutLine_ID = Util.GetValueOfInt(paramValue[0].ToString());
                MInOutLine inOutLine = new MInOutLine(ctx, inOutLine_ID, null);
                var        retValue  = inOutLine.GetMovementQty();


                List <Decimal> retlst = new List <Decimal>();

                retlst.Add(retValue);

                //retVal.Add(notReserved);


                retJSON = JsonConvert.SerializeObject(retlst);
            }
            else
            {
                retError = "Session Expired";
            }
            return(Json(new { result = retJSON, error = retError }, JsonRequestBehavior.AllowGet));
        }
 /**
  *  After Delete
  *	@param success success
  *	@return success
  */
 protected override bool AfterDelete(bool success)
 {
     if (success)
     {
         //	Get Order and decrease invoices
         MInvoiceLine iLine          = new MInvoiceLine(GetCtx(), GetC_InvoiceLine_ID(), Get_TrxName());
         int          C_OrderLine_ID = iLine.GetC_OrderLine_ID();
         if (C_OrderLine_ID == 0)
         {
             MInOutLine ioLine = new MInOutLine(GetCtx(), GetM_InOutLine_ID(), Get_TrxName());
             C_OrderLine_ID = ioLine.GetC_OrderLine_ID();
         }
         //	No Order Found
         if (C_OrderLine_ID == 0)
         {
             return(success);
         }
         //	Find MatchPO
         MMatchPO[] mPO = MMatchPO.Get(GetCtx(), C_OrderLine_ID, GetC_InvoiceLine_ID(), Get_TrxName());
         for (int i = 0; i < mPO.Length; i++)
         {
             if (mPO[i].GetM_InOutLine_ID() == 0)
             {
                 mPO[i].Delete(true);
             }
             else
             {
                 mPO[i].SetC_InvoiceLine_ID(null);
                 mPO[i].Save();
             }
         }
     }
     return(success);
 }
        /**
         *  Set Value Name Description
         *	@param shipment shipment
         *	@param line line
         *	@param deliveryCount
         */
        public void SetValueNameDescription(MInOut shipment, MInOutLine line, int deliveryCount)
        {
            VAdvantage.Model.MProduct product = line.GetProduct();
            MBPartner partner = shipment.GetBPartner();

            SetValueNameDescription(shipment, deliveryCount, product, partner);
        }
        /// <summary>
        /// Load Document Details
        /// </summary>
        /// <returns>error message or null</returns>
        public override String LoadDocumentDetails()
        {
            SetC_Currency_ID(Doc.NO_CURRENCY);
            MMatchInv matchInv = (MMatchInv)GetPO();

            SetDateDoc(matchInv.GetDateTrx());
            SetQty(matchInv.GetQty());
            //	Invoice Info
            int C_InvoiceLine_ID = matchInv.GetC_InvoiceLine_ID();

            _invoiceLine = new MInvoiceLine(GetCtx(), C_InvoiceLine_ID, null);
            //		BP for NotInvoicedReceipts
            int C_BPartner_ID = _invoiceLine.GetParent().GetC_BPartner_ID();

            SetC_BPartner_ID(C_BPartner_ID);
            //
            int M_InOutLine_ID = matchInv.GetM_InOutLine_ID();

            _receiptLine = new MInOutLine(GetCtx(), M_InOutLine_ID, null);
            //
            _pc = new ProductCost(GetCtx(),
                                  GetM_Product_ID(), matchInv.GetM_AttributeSetInstance_ID(), null);
            _pc.SetQty(GetQty());

            return(null);
        }
        /// <summary>
        /// GetMInOutLine
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="fields"></param>
        /// <returns></returns>
        public Dictionary <string, string> GetMInOutLine(Ctx ctx, string fields)
        {
            string[] paramValue = fields.Split(',');
            //Assign parameter value
            int Orig_InOutLine_ID = Util.GetValueOfInt(paramValue[0].ToString());
            //End Assign parameter value
            MInOutLine ioLine = new MInOutLine(ctx, Orig_InOutLine_ID, null);
            Dictionary <string, string> result = new Dictionary <string, string>();

            result["M_Locator_ID"]              = ioLine.GetM_Locator_ID().ToString();
            result["MovementQty"]               = ioLine.GetMovementQty().ToString();
            result["C_Project_ID"]              = ioLine.GetC_Project_ID().ToString();
            result["C_Campaign_ID"]             = ioLine.GetC_Campaign_ID().ToString();
            result["M_Product_ID"]              = ioLine.GetM_Product_ID().ToString();
            result["M_AttributeSetInstance_ID"] = ioLine.GetM_AttributeSetInstance_ID().ToString();
            result["C_UOM_ID"]   = ioLine.GetC_UOM_ID().ToString();
            result["IsDropShip"] = ioLine.IsDropShip() ? "Y" : "N";

            // JID_1310: On Selection of Shipment line on Customer/Vendor RMA. System should check Total Delivred - Total Return Qty From Sales PO line and Balance  show in qty field
            decimal qtyRMA = Util.GetValueOfDecimal(DB.ExecuteScalar(@"SELECT SUM(QtyEntered) FROM C_Order o INNER JOIN C_OrderLine ol ON o.C_Order_ID = ol.C_Order_ID                            
                            WHERE ol.Orig_InOutLine_ID = " + Orig_InOutLine_ID
                                                                     + @" AND ol.Isactive = 'Y' AND o.docstatus NOT IN ('RE' , 'VO')", null, null));
            decimal QtyNotDelivered = ioLine.GetQtyEntered() - qtyRMA;

            result["QtyEntered"] = QtyNotDelivered.ToString();

            //retlst.Add(retValue);
            return(result);
        }
        /// <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);
        }
 /// <summary>
 ///     Get Shipment Line
 /// </summary>
 /// <returns>line</returns>
 public MInOutLine GetLine()
 {
     if (_line == null)
     {
         _line = new MInOutLine(GetCtx(), GetM_InOutLine_ID(), Get_TrxName());
     }
     return(_line);
 }
 /**
  *  Parent Constructor
  *	@param parent parent
  *	@param M_AttributeSetInstance_ID asi
  *	@param MovementQty qty
  */
 public MInOutLineMA(MInOutLine parent, int M_AttributeSetInstance_ID, Decimal MovementQty)
     : this(parent.GetCtx(), 0, parent.Get_TrxName())
 {
     SetClientOrg(parent);
     SetM_InOutLine_ID(parent.GetM_InOutLine_ID());
     //
     SetM_AttributeSetInstance_ID(M_AttributeSetInstance_ID);
     SetMovementQty(MovementQty);
 }
Beispiel #11
0
        /// <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>
        ///      Process Confirmation Line.
        ///     - Update InOut Line
        /// </summary>
        /// <param name="isSOTrx">sales order</param>
        /// <param name="confirmType">type</param>
        /// <returns>success</returns>
        public Boolean ProcessLine(bool isSOTrx, String confirmType)
        {
            MInOutLine line = GetLine();

            //	Customer
            if (MInOutConfirm.CONFIRMTYPE_CustomerConfirmation.Equals(confirmType))
            {
                line.SetConfirmedQty(GetConfirmedQty());
            }

            //	Drop Ship
            else if (MInOutConfirm.CONFIRMTYPE_DropShipConfirm.Equals(confirmType))
            {
            }

            //	Pick or QA
            else if (MInOutConfirm.CONFIRMTYPE_PickQAConfirm.Equals(confirmType))
            {
                line.SetTargetQty(GetTargetQty());
                line.SetMovementQty(GetConfirmedQty()); //	Entered NOT changed
                line.SetPickedQty(GetConfirmedQty());
                //
                line.SetScrappedQty(GetScrappedQty());
            }

            //	Ship or Receipt
            else if (MInOutConfirm.CONFIRMTYPE_ShipReceiptConfirm.Equals(confirmType))
            {
                line.SetTargetQty(GetTargetQty());
                Decimal qty         = GetConfirmedQty();
                Boolean isReturnTrx = line.GetParent().IsReturnTrx();

                /* In PO receipts and SO Returns, we have the responsibility
                 * for scrapped quantity
                 */
                if ((!isSOTrx && !isReturnTrx) || (isSOTrx && isReturnTrx))
                {
                    qty = Decimal.Add(qty, GetScrappedQty());
                }
                line.SetMovementQty(qty);                               //	Entered NOT changed
                //
                line.SetScrappedQty(GetScrappedQty());
                // vikas 12/28/2015 Mantis Issue (0000335)
                line.SetConfirmedQty(GetConfirmedQty());
            }
            //	Vendor
            else if (MInOutConfirm.CONFIRMTYPE_VendorConfirmation.Equals(confirmType))
            {
                line.SetConfirmedQty(GetConfirmedQty());
            }

            return(line.Save(Get_TrxName()));
        }
Beispiel #13
0
 /// <summary>
 /// Shipment Line Constructor
 /// </summary>
 /// <param name="sLine">shipment line</param>
 /// <param name="dateTrx">optional date</param>
 /// <param name="qty">matched quantity</param>
 public MMatchPO(MInOutLine sLine, DateTime?dateTrx, Decimal qty)
     : this(sLine.GetCtx(), 0, sLine.Get_Trx())
 {
     SetClientOrg(sLine);
     SetM_InOutLine_ID(sLine.GetM_InOutLine_ID());
     SetC_OrderLine_ID(sLine.GetC_OrderLine_ID());
     if (dateTrx != null)
     {
         SetDateTrx(dateTrx);
     }
     SetM_Product_ID(sLine.GetM_Product_ID());
     SetM_AttributeSetInstance_ID(sLine.GetM_AttributeSetInstance_ID());
     SetQty(qty);
     SetProcessed(true);         //	auto
 }
        /**
         *  Set Qty based on product * shipment line if exists
         */
        public void SetQty()
        {
            //	UPDATE M_Product SET SupportUnits=1 WHERE SupportUnits IS NULL OR SupportUnits<1;
            //	UPDATE A_Asset a SET Qty = (SELECT l.MovementQty * p.SupportUnits FROM M_InOutLine l, M_Product p WHERE a.M_InOutLine_ID=l.M_InOutLine_ID AND a.M_Product_ID=p.M_Product_ID) WHERE a.M_Product_ID IS NOT NULL AND a.M_InOutLine_ID IS NOT NULL;
            Decimal Qty = Env.ONE;

            if (GetM_InOutLine_ID() != 0)
            {
                MInOutLine line = new MInOutLine(GetCtx(), GetM_InOutLine_ID(), Get_TrxName());
                Qty = line.GetMovementQty();
            }
            int     multiplier = GetProduct().GetSupportUnits();
            Decimal mm         = new Decimal(multiplier);

            base.SetQty(Decimal.Multiply(Qty, mm));
        }
Beispiel #15
0
        /// <summary>
        /// GetMInOutLine
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="fields"></param>
        /// <returns></returns>
        public Dictionary <string, string> GetMInOutLine(Ctx ctx, string fields)
        {
            string[] paramValue = fields.Split(',');
            //Assign parameter value
            int Orig_InOutLine_ID = Util.GetValueOfInt(paramValue[0].ToString());
            //End Assign parameter value
            MInOutLine ioLine = new MInOutLine(ctx, Orig_InOutLine_ID, null);
            Dictionary <string, string> result = new Dictionary <string, string>();

            result["M_Locator_ID"]              = ioLine.GetM_Locator_ID().ToString();
            result["MovementQty"]               = ioLine.GetMovementQty().ToString();
            result["C_Project_ID"]              = ioLine.GetC_Project_ID().ToString();
            result["C_Campaign_ID"]             = ioLine.GetC_Campaign_ID().ToString();
            result["M_Product_ID"]              = ioLine.GetM_Product_ID().ToString();
            result["M_AttributeSetInstance_ID"] = ioLine.GetM_AttributeSetInstance_ID().ToString();
            result["C_UOM_ID"] = ioLine.GetC_UOM_ID().ToString();
            //retlst.Add(retValue);
            return(result);
        }
        /// <summary>
        /// Set Shipment Line
        /// </summary>
        /// <param name="line">shipment line</param>
        public void SetInOutLine(MInOutLine line)
        {
            SetM_InOutLine_ID(line.GetM_InOutLine_ID());
            SetTargetQty(line.GetMovementQty());        //	Confirmations in Storage UOM
            SetConfirmedQty(GetTargetQty());            //	suggestion

            // Enhaced by Siddaraju 2-12-2016 only for gulf oil
            if (Util.GetValueOfInt(DB.ExecuteScalar("SELECT COUNT(*) FROM AD_ModuleInfo WHERE IsActive = 'Y' AND  Prefix LIKE 'GOM01_'", null, null)) > 0)
            {
                _M_Product_ID = line.GetM_Product_ID();
                if (_M_Product_ID > 0)
                {
                    MProduct Prod1 = new MProduct(GetCtx(), _M_Product_ID, Get_TrxName());
                    SetGOM01_ItemName(Prod1.GetName());
                    SetGOM01_ItemDescription(Prod1.GetDescription());
                    SetGOM01_ItemCode(Prod1.GetValue());
                }
            }
            //end
            _line = line;
        }
 /**
  *  Before Save
  *	@param newRecord new
  *	@return true
  */
 protected override bool BeforeSave(bool newRecord)
 {
     //	Set Trx Date
     if (GetDateTrx() == null)
     {
         SetDateTrx(new DateTime(CommonFunctions.CurrentTimeMillis()));
     }
     //	Set Acct Date
     if (GetDateAcct() == null)
     {
         DateTime?ts = GetNewerDateAcct();
         if (ts == null)
         {
             ts = GetDateTrx();
         }
         SetDateAcct(ts);
     }
     if (GetM_AttributeSetInstance_ID() == 0 && GetM_InOutLine_ID() != 0)
     {
         MInOutLine iol = new MInOutLine(GetCtx(), GetM_InOutLine_ID(), Get_TrxName());
         SetM_AttributeSetInstance_ID(iol.GetM_AttributeSetInstance_ID());
     }
     return(true);
 }
Beispiel #18
0
        /// <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, null);

            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@");
            }
            //
            MInOut ship = new MInOut(invoice, _C_DocType_ID, null, _M_Warehouse_ID);

            if (!ship.Save())
            {
                throw new ArgumentException("@SaveError@ Receipt");
            }
            //
            MInvoiceLine[] invoiceLines = invoice.GetLines(false);
            for (int i = 0; i < invoiceLines.Length; i++)
            {
                MInvoiceLine invoiceLine = invoiceLines[i];
                MInOutLine   sLine       = new MInOutLine(ship);
                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())
                {
                    throw new ArgumentException("@SaveError@ @M_InOutLine_ID@");
                }
                //
                invoiceLine.SetM_InOutLine_ID(sLine.GetM_InOutLine_ID());
                if (!invoiceLine.Save())
                {
                    throw new ArgumentException("@SaveError@ @C_InvoiceLine_ID@");
                }
            }
            return(ship.GetDocumentNo());
        }
Beispiel #19
0
        /**
         *  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());
        }
Beispiel #20
0
        /**
         *  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());
        }
Beispiel #24
0
        /// <summary>
        /// Create Invoice Line from Shipment
        /// </summary>
        /// <param name="order">order</param>
        /// <param name="ship">shipment header</param>
        /// <param name="sLine">shipment line</param>
        private void CreateLine(MOrder order, MInOut ship, MInOutLine sLine)
        {
            if (_invoice == null)
            {
                _invoice = new MInvoice(order, 0, _DateInvoiced);
                int _CountVA009 = Env.IsModuleInstalled("VA009_") ? 1 : 0;
                if (_CountVA009 > 0)
                {
                    int _PaymentMethod_ID = order.GetVA009_PaymentMethod_ID();
                    // 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
                    // during sale cycle -- VA009_PaymentMethod_ID
                    // during purchase cycle -- VA009_PO_PaymentMethod_ID
                    int bpPamentMethod_ID = Util.GetValueOfInt(DB.ExecuteScalar(@"SELECT " + (order.IsSOTrx() ? " VA009_PaymentMethod_ID " : " VA009_PO_PaymentMethod_ID ") +
                                                                                @" FROM C_BPartner WHERE C_BPartner_ID = " + order.GetC_BPartner_ID(), null, Get_Trx()));

                    if (_ConsolidateDocument && bpPamentMethod_ID != 0)
                    {
                        _PaymentMethod_ID = bpPamentMethod_ID;
                    }
                    if (_PaymentMethod_ID > 0)
                    {
                        _invoice.SetVA009_PaymentMethod_ID(_PaymentMethod_ID);
                    }
                }

                int _CountVA026 = Env.IsModuleInstalled("VA026_") ? 1 : 0;
                if (_CountVA026 > 0)
                {
                    _invoice.SetVA026_LCDetail_ID(order.GetVA026_LCDetail_ID());
                }

                // Added by Bharat on 29 Jan 2018 to set Inco Term from Order
                if (_invoice.Get_ColumnIndex("C_IncoTerm_ID") > 0)
                {
                    _invoice.SetC_IncoTerm_ID(order.GetC_IncoTerm_ID());
                }

                if (Env.IsModuleInstalled("VA077_"))
                {
                    //.setva077
                    _invoice.Set_Value("VA077_AdditionalAnnualCharge", order.Get_Value("VA077_AdditionalAnnualCharge"));
                    _invoice.Set_Value("VA077_ChangeStartDate", order.Get_Value("VA077_ChangeStartDate"));
                    _invoice.Set_Value("VA077_ContractCPEndDate", order.Get_Value("VA077_ContractCPEndDate"));
                    _invoice.Set_Value("VA077_ContractCPStartDate", order.Get_Value("VA077_ContractCPStartDate"));
                    _invoice.Set_Value("VA077_HistoricContractDate", order.Get_Value("VA077_HistoricContractDate"));
                    _invoice.Set_Value("VA077_IsLegalEntity", order.Get_Value("VA077_IsLegalEntity"));
                    _invoice.Set_Value("VA077_MarginPercent", order.Get_Value("VA077_MarginPercent"));
                    _invoice.Set_Value("VA077_NewAnnualContractTotal", order.Get_Value("VA077_NewAnnualContractTotal"));
                    _invoice.Set_Value("VA077_OldAnnualContractTotal", order.Get_Value("VA077_OldAnnualContractTotal"));
                    _invoice.Set_Value("VA077_PartialAmtCatchUp", order.Get_Value("VA077_PartialAmtCatchUp"));
                    _invoice.Set_Value("VA077_SalesCoWorker", order.Get_Value("VA077_SalesCoWorker"));
                    _invoice.Set_Value("VA077_SalesCoWorkerPer", order.Get_Value("VA077_SalesCoWorkerPer"));
                    _invoice.Set_Value("VA077_TotalMarginAmt", order.Get_Value("VA077_TotalMarginAmt"));
                    _invoice.Set_Value("VA077_TotalPurchaseAmt", order.Get_Value("VA077_TotalPurchaseAmt"));
                    _invoice.Set_Value("VA077_TotalSalesAmt", order.Get_Value("VA077_TotalSalesAmt"));
                }

                if (!_invoice.Save())
                {
                    ValueNamePair pp = VAdvantage.Logging.VLogger.RetrieveError();
                    if (pp != null)
                    {
                        throw new ArgumentException("Could not create Invoice (s). " + pp.GetName());
                    }
                    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 (sLine.GetA_Asset_ID() > 0)
            {
                line1.SetA_Asset_ID(sLine.GetA_Asset_ID());
                if (line1.Get_ColumnIndex("VAFAM_AssetCost") > 0)
                {
                    int         PAcctSchema_ID = 0;
                    int         pCurrency_ID   = 0;
                    MAcctSchema as1            = MClient.Get(GetCtx(), GetAD_Client_ID()).GetAcctSchema();
                    if (as1 != null)
                    {
                        PAcctSchema_ID = as1.GetC_AcctSchema_ID();
                        pCurrency_ID   = as1.GetC_Currency_ID();
                    }
                    decimal LineNetAmt = Decimal.Multiply(line1.GetPriceActual(), line1.GetQtyEntered());
                    decimal AssetCost  = GetAssetCost(sLine.GetA_Asset_ID(), sLine.GetM_Product_ID(), PAcctSchema_ID);
                    AssetCost = Decimal.Multiply(AssetCost, line1.GetQtyEntered());
                    if (LineNetAmt > 0)
                    {
                        LineNetAmt = MConversionRate.Convert(GetCtx(), LineNetAmt, _invoice.GetC_Currency_ID(), pCurrency_ID, _invoice.GetAD_Client_ID(), _invoice.GetAD_Org_ID());
                    }
                    decimal Diff = LineNetAmt - AssetCost;
                    line1.Set_Value("VAFAM_AssetCost", AssetCost);
                    line1.Set_Value("VAFAM_Difference", Diff);
                }
            }



            if (Env.IsModuleInstalled("VA077_"))
            {
                //invoice line
                line1.Set_Value("VA077_CNAutodesk", sLine.Get_Value("VA077_CNAutodesk"));
                line1.Set_Value("VA077_Duration", sLine.Get_Value("VA077_Duration"));
                line1.Set_Value("VA077_MarginAmt", sLine.Get_Value("VA077_MarginAmt"));
                line1.Set_Value("VA077_MarginPercent", sLine.Get_Value("VA077_MarginPercent"));
                line1.Set_Value("VA077_OldSN", sLine.Get_Value("VA077_OldSN"));
                line1.Set_Value("VA077_ProductInfo", sLine.Get_Value("VA077_ProductInfo"));
                line1.Set_Value("VA077_PurchasePrice", sLine.Get_Value("VA077_PurchasePrice"));
                line1.Set_Value("VA077_RegEmail", sLine.Get_Value("VA077_RegEmail"));
                line1.Set_Value("VA077_SerialNo", sLine.Get_Value("VA077_SerialNo"));
                line1.Set_Value("VA077_UpdateFromVersn", sLine.Get_Value("VA077_UpdateFromVersn"));
                line1.Set_Value("VA077_UserRef_ID", sLine.Get_Value("VA077_UserRef_ID"));
                line1.Set_Value("VA077_EndDate", sLine.Get_Value("VA077_EndDate"));
                line1.Set_Value("VA077_StartDate", sLine.Get_Value("VA077_StartDate"));
            }



            if (!line1.Save())
            {
                ValueNamePair pp = VAdvantage.Logging.VLogger.RetrieveError();
                if (pp != null)
                {
                    throw new ArgumentException("Could not create Invoice Line (s). " + pp.GetName());
                }
                throw new Exception("Could not create Invoice Line (s)");
            }
            //	Link
            sLine.SetIsInvoiced(true);
            if (!sLine.Save())
            {
                ValueNamePair pp = VAdvantage.Logging.VLogger.RetrieveError();
                if (pp != null)
                {
                    throw new ArgumentException("Could not update Shipment Line. " + pp.GetName());
                }
                throw new Exception("Could not update Shipment Line");
            }

            log.Fine(line1.ToString());
        }
Beispiel #25
0
        /// <summary>
        /// Generate Invoices
        /// </summary>
        /// <param name="idr">pstmt order query</param>
        /// <returns>info</returns>
        //private String Generate(IDataReader idr)
        private String Generate(DataTable dt)
        {
            //JID_1139 Avoided the duplicate charge line created Invoice(customer)
            bool isAllownonItem = Util.GetValueOfString(GetCtx().GetContext("$AllowNonItem")).Equals("Y");

            foreach (DataRow dr in dt.Rows)
            {
                MOrder order = new MOrder(GetCtx(), dr, Get_TrxName());

                // Credit Limit check
                MBPartner bp = MBPartner.Get(GetCtx(), order.GetC_BPartner_ID());
                if (bp.GetCreditStatusSettingOn() == "CH")
                {
                    decimal creditLimit = bp.GetSO_CreditLimit();
                    string  creditVal   = bp.GetCreditValidation();
                    if (creditLimit != 0)
                    {
                        decimal creditAvlb = creditLimit - bp.GetSO_CreditUsed();
                        if (creditAvlb <= 0)
                        {
                            if (creditVal == "C" || creditVal == "D" || creditVal == "F")
                            {
                                AddLog(Msg.GetMsg(GetCtx(), "StopInvoice") + bp.GetName());
                                continue;
                            }
                            else if (creditVal == "I" || creditVal == "J" || creditVal == "L")
                            {
                                if (_msg != null)
                                {
                                    _msg.Clear();
                                }
                                _msg.Append(Msg.GetMsg(GetCtx(), "WarningInvoice") + bp.GetName());
                                //AddLog(Msg.GetMsg(GetCtx(), "WarningInvoice") + bp.GetName());
                            }
                        }
                    }
                }
                // JID_0161 // change here now will check credit settings on field only on Business Partner Header // Lokesh Chauhan 15 July 2019
                else if (bp.GetCreditStatusSettingOn() == X_C_BPartner.CREDITSTATUSSETTINGON_CustomerLocation)
                {
                    MBPartnerLocation bpl = new MBPartnerLocation(GetCtx(), order.GetC_BPartner_Location_ID(), null);
                    //MBPartner bpartner = MBPartner.Get(GetCtx(), order.GetC_BPartner_ID());
                    //if (bpl.GetCreditStatusSettingOn() == "CL")
                    //{
                    decimal creditLimit = bpl.GetSO_CreditLimit();
                    string  creditVal   = bpl.GetCreditValidation();
                    if (creditLimit != 0)
                    {
                        decimal creditAvlb = creditLimit - bpl.GetSO_CreditUsed();
                        if (creditAvlb <= 0)
                        {
                            if (creditVal == "C" || creditVal == "D" || creditVal == "F")
                            {
                                AddLog(Msg.GetMsg(GetCtx(), "StopInvoice") + bp.GetName() + " " + bpl.GetName());
                                continue;
                            }
                            else if (creditVal == "I" || creditVal == "J" || creditVal == "L")
                            {
                                if (_msg != null)
                                {
                                    _msg.Clear();
                                }
                                _msg.Append(Msg.GetMsg(GetCtx(), "WarningInvoice") + bp.GetName() + " " + bpl.GetName());
                                //AddLog(Msg.GetMsg(GetCtx(), "WarningInvoice") + bp.GetName() + " " + bpl.GetName());
                            }
                        }
                    }
                    //}
                }
                // Credit Limit End

                //	New Invoice Location
                // JID_1237 : While creating invoice need to consolidate order on the basis of Org, Payment Term, BP Location (Bill to Location) and Pricelist.
                if (!_ConsolidateDocument ||
                    (_invoice != null &&
                     (_invoice.GetC_BPartner_Location_ID() != order.GetBill_Location_ID() ||
                      _invoice.GetC_PaymentTerm_ID() != order.GetC_PaymentTerm_ID() ||
                      _invoice.GetM_PriceList_ID() != order.GetM_PriceList_ID() ||
                      _invoice.GetAD_Org_ID() != order.GetAD_Org_ID() ||
                      ((_invoice.GetC_ConversionType_ID() != 0 ? _invoice.GetC_ConversionType_ID() : defaultConversionType)
                       != (order.GetC_ConversionType_ID() != 0 ? order.GetC_ConversionType_ID() : defaultConversionType))
                     )))
                {
                    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();
                    MOrderLine[] oLines        = order.GetLines(true, null);
                    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;
                        }
                        //JID_1139 Avoided the duplicate charge records
                        if (shipLine.GetM_Product_ID() > 0 || isAllownonItem)
                        {
                            CreateLine(order, shipment, shipLine);
                        }
                    }//	shipment lines

                    //JID_1139 Avoided the duplicate charge records
                    if (!isAllownonItem)
                    {
                        for (int i = 0; i < oLines.Length; i++)
                        {
                            MOrderLine oLine = oLines[i];
                            if (oLine.GetC_Charge_ID() > 0)
                            {
                                Decimal toInvoice = Decimal.Subtract(oLine.GetQtyOrdered(), oLine.GetQtyInvoiced());
                                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);
                                }
                                //JID_1139_1 avoided the charge line with 0 qty inserted
                                if (oLine.IsContract() == false && oLine.GetQtyOrdered() > oLine.GetQtyInvoiced())
                                {
                                    CreateLine(order, oLine, toInvoice, qtyEntered);
                                    log.Info("ID " + oLine.Get_ID() + "Qty Ordered " + oLine.GetQtyOrdered() + " Qty Invoiced " + oLine.GetQtyInvoiced());
                                }
                            }
                        }
                    }
                }
                //	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;
                        //JID_1136: While creating the Invoices against the charge system should not check the Ordered qty= Delivered qty. need to check this only in case of products
                        if (completeOrder && oLine.GetC_Charge_ID() > 0)
                        {
                            fullyDelivered = true;
                            if (oLine.GetC_Charge_ID() > 0)
                            {
                                log.Fine("After Order Delivery - 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 && !isAllownonItem)
                                {
                                    CreateLine(order, oLine, toInvoice, qtyEntered);
                                    log.Info("ID " + oLine.Get_ID() + "Qty Ordered " + oLine.GetQtyOrdered() + " Qty Invoiced " + oLine.GetQtyInvoiced());
                                }
                            }
                        }

                        //	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

            CompleteInvoice();
            return("@Created@ = " + _created);
        }
        /// <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);
            //  Message Display Wrong  Done  Vikas and Assigned by Gurinder
            int    count = Util.GetValueOfInt(DB.ExecuteScalar(" SELECT  Count(*)  FROM M_Inout WHERE  ISSOTRX='Y' AND  M_Inout_ID=" + GetRecord_ID()));
            MInOut ship  = null;

            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()))
                {
                    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()))
                {
                    throw new ArgumentException("Material Receipt not completed");
                }
            }
            //***********************END*****************************//
            MInvoice invoice = new MInvoice(ship, null);
            //-------------Column Added by Anuj----------------------
            //int _CountVA009 = Util.GetValueOfInt(DB.ExecuteScalar("SELECT COUNT(AD_MODULEINFO_ID) FROM AD_MODULEINFO WHERE PREFIX='VA009_'  AND IsActive = 'Y'"));
            int _CountVA009 = Env.IsModuleInstalled("VA009_") ? 1 : 0;

            // Code by Mohit Amortization process
            //int _CountVA038 = Util.GetValueOfInt(DB.ExecuteScalar("SELECT COUNT(AD_MODULEINFO_ID) FROM AD_MODULEINFO WHERE PREFIX='VA038_'  AND IsActive = 'Y'"));
            int _CountVA038 = Env.IsModuleInstalled("VA038_") ? 1 : 0;

            // End Amortization Code

            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()));
                if (_PaymentMethod_ID > 0)
                {
                    invoice.SetVA009_PaymentMethod_ID(_PaymentMethod_ID);
                }
            }
            //-------------Column Added by Anuj----------------------

            // added by Amit 26-may-2016
            //int _CountVA026 = Util.GetValueOfInt(DB.ExecuteScalar("SELECT COUNT(AD_MODULEINFO_ID) FROM AD_MODULEINFO WHERE PREFIX='VA026_'  AND IsActive = 'Y'"));
            int _CountVA026 = Env.IsModuleInstalled("VA026_") ? 1 : 0;

            if (_CountVA026 > 0)
            {
                MOrder order = new MOrder(GetCtx(), ship.GetC_Order_ID(), Get_Trx());
                if (order != null && order.GetC_Order_ID() > 0)
                {
                    invoice.SetVA026_LCDetail_ID(order.GetVA026_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
                    if (invoice.GetC_DocTypeTarget_ID() == 0)
                    {
                        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 (ship.GetC_Order_ID() >= 0)
                    {
                        MOrder   order = new MOrder(GetCtx(), ship.GetC_Order_ID(), Get_Trx());
                        MDocType dt    = MDocType.Get(GetCtx(), order.GetC_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);
            }
            if (_InvoiceDocumentNo != null && _InvoiceDocumentNo.Length > 0)
            {
                invoice.SetDocumentNo(_InvoiceDocumentNo);
            }

            // 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());
            }

            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");
                //return GetReterivedError(invoice, "Cannot save Invoice");
            }
            MInOutLine[] shipLines      = ship.GetLines(false);
            DateTime?    AmortStartDate = null;
            DateTime?    AmortEndDate   = null;

            count = 0;
            DataSet ds = 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][0]);
                    decimal qtyInvoiced = Util.GetValueOfDecimal(ds.Tables[0].Rows[0][1]);
                    if (qtyEntered <= 0)
                    {
                        ds.Dispose();
                        log.Info("Invoice Line already exist for Receipt Line ID - " + sLine.GetM_InOutLine_ID());
                        continue;
                    }
                    else
                    {
                        MInvoiceLine line = new MInvoiceLine(invoice);
                        line.SetShipLine(sLine);
                        //line.SetQtyEntered(sLine.GetQtyEntered());
                        //line.SetQtyInvoiced(sLine.GetMovementQty());
                        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());
                                if (Util.GetValueOfInt(pro.Get_Value("VA038_AmortizationTemplate_ID")) > 0)
                                {
                                    line.Set_Value("VA038_AmortizationTemplate_ID", Util.GetValueOfInt(pro.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(pro.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.GetC_Charge_ID() > 0)
                            {
                                MCharge charge = new MCharge(GetCtx(), sLine.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();
                                    }
                                }
                            }
                        }
                        // End Change Amortization process--------------
                        if (!line.Save())
                        {
                            //return GetReterivedError(line, "Cannot save Invoice Line");
                            //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);
                    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());
                            if (Util.GetValueOfInt(pro.Get_Value("VA038_AmortizationTemplate_ID")) > 0)
                            {
                                line.Set_Value("VA038_AmortizationTemplate_ID", Util.GetValueOfInt(pro.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(pro.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.GetC_Charge_ID() > 0)
                        {
                            MCharge charge = new MCharge(GetCtx(), sLine.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();
                                }
                            }
                        }
                    }
                    // End Change Amortization process--------------
                    if (!line.Save())
                    {
                        //return GetReterivedError(line, "Cannot save Invoice Line");
                        //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,       "
                                + "   SUM(OL.QTYENTERED *OL.PRICEENTERED) AS LINEAMT, "
                                + "      SUM(ML.QTYENTERED*OL.PRICEENTERED) AS MRLINEVALUE "
                                + "  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;
                                decimal SumOfvalue = 0;
                                decimal sototval   = 0;

                                string sql = "SELECT SUM(OL.QTYENTERED *OL.PRICEENTERED) AS LINEAMT from C_ORDER CO,C_ORDERLINE OL WHERE CO.C_ORDER_ID=OL.C_ORDER_ID  AND (OL.C_CHARGE_ID IS NULL OR OL.C_CHARGE_ID    = 0) and CO.C_ORDER_ID  =" + ship.GetC_Order_ID();
                                sototval = VAdvantage.Utility.Util.GetValueOfDecimal(DB.ExecuteScalar(sql));



                                if (Util.GetValueOfInt(OrderDS.Tables[0].Rows[index]["ORDERQTY"]) == 0)
                                {
                                    SumOfQty = 1;
                                }
                                else
                                {
                                    SumOfQty   = Util.GetValueOfInt(OrderDS.Tables[0].Rows[index]["ORDERQTY"]);
                                    SumOfvalue = Util.GetValueOfDecimal(OrderDS.Tables[0].Rows[index]["LINEAMT"]);
                                }
                                //decimal amt = (Util.GetValueOfDecimal(ds.Tables[0].Rows[i]["LINENETAMT"]) / SumOfQty) * Util.GetValueOfInt(OrderDS.Tables[0].Rows[index]["MRLINEQTY"]);
                                decimal amt = (Util.GetValueOfDecimal(ds.Tables[0].Rows[i]["LINENETAMT"]) / sototval) * Util.GetValueOfInt(OrderDS.Tables[0].Rows[index]["MRLINEVALUE"]);

                                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())
                                {
                                    //return GetReterivedError(line, "Cannot save Invoice Line");
                                    //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();
                return(Msg.GetMsg(GetCtx(), "InvoiceExist"));
            }
        }
        /**
         *  Split Shipment into confirmed and dispute
         *	@param original original shipment
         *	@param C_DocType_ID target DocType
         *	@param confirmLines confirm lines
         */
        private void SplitInOut(MInOut original, int C_DocType_ID, MInOutLineConfirm[] confirmLines)
        {
            MInOut split = new MInOut(original, C_DocType_ID, original.GetMovementDate());

            split.AddDescription("Splitted from " + original.GetDocumentNo());
            split.SetIsInDispute(true);
            // new 13 jan
            int _count = Util.GetValueOfInt(DB.ExecuteScalar("SELECT count(*) FROM AD_Column clm INNER JOIN ad_table tbl on (tbl.ad_table_id=clm.ad_table_id) where tbl.tablename='M_InOutLineConfirm' and clm.columnname = 'M_Locator_ID' "));

            //nnayak : Change for bug 1431337
            split.SetRef_InOut_ID(original.Get_ID());

            if (!split.Save(Get_TrxName()))
            {
                throw new Exception("Cannot save Split");
            }
            original.AddDescription("Split: " + split.GetDocumentNo());
            if (!original.Save(Get_TrxName()))
            {
                throw new Exception("Cannot update original Shipment");
            }

            //	Go through confirmations
            for (int i = 0; i < confirmLines.Length; i++)
            {
                MInOutLineConfirm confirmLine   = confirmLines[i];
                Decimal           differenceQty = confirmLine.GetDifferenceQty();
                if (differenceQty.CompareTo(Env.ZERO) == 0)
                {
                    continue;
                }
                //
                MInOutLine oldLine = confirmLine.GetLine();
                log.Fine("Qty=" + differenceQty + ", Old=" + oldLine);
                //
                MInOutLine splitLine = new MInOutLine(split);
                splitLine.SetC_OrderLine_ID(oldLine.GetC_OrderLine_ID());
                splitLine.SetC_UOM_ID(oldLine.GetC_UOM_ID());
                splitLine.SetDescription(oldLine.GetDescription());
                splitLine.SetIsDescription(oldLine.IsDescription());
                splitLine.SetLine(oldLine.GetLine());
                splitLine.SetM_AttributeSetInstance_ID(oldLine.GetM_AttributeSetInstance_ID());
                //new 13 jan vikas ,assigne by surya sir
                if (_count > 0)
                {
                    if (confirmLine.GetM_Locator_ID() > 0)
                    {
                        splitLine.SetM_Locator_ID(confirmLine.GetM_Locator_ID());
                    }
                    else
                    {
                        splitLine.SetM_Locator_ID(oldLine.GetM_Locator_ID());
                    }
                }
                else
                {
                    splitLine.SetM_Locator_ID(oldLine.GetM_Locator_ID());
                }
                //End
                //  splitLine.SetM_Locator_ID(oldLine.GetM_Locator_ID());

                splitLine.SetM_Product_ID(oldLine.GetM_Product_ID());
                splitLine.SetM_Warehouse_ID(oldLine.GetM_Warehouse_ID());
                splitLine.SetRef_InOutLine_ID(oldLine.GetRef_InOutLine_ID());
                splitLine.AddDescription("Split: from " + oldLine.GetMovementQty());
                //	Qtys
                splitLine.SetQty(differenceQty);                //	Entered/Movement
                if (!splitLine.Save(Get_TrxName()))
                {
                    throw new Exception("Cannot save Split Line");
                }
                //	Old
                oldLine.AddDescription("Splitted: from " + oldLine.GetMovementQty());
                oldLine.SetQty(Decimal.Subtract(oldLine.GetMovementQty(), differenceQty));
                if (!oldLine.Save(Get_TrxName()))
                {
                    throw new Exception("Cannot save Splited Line");
                }
                //	Update Confirmation Line
                confirmLine.SetTargetQty(Decimal.Subtract(confirmLine.GetTargetQty(), differenceQty));
                confirmLine.SetDifferenceQty(Env.ZERO);
                if (!confirmLine.Save(Get_TrxName()))
                {
                    throw new Exception("Cannot save Split Confirmation");
                }
            }   //	for all confirmations

            _processMsg = "Split @M_InOut_ID@=" + split.GetDocumentNo()
                          + " - @M_InOutConfirm_ID@=";

            //	Create Dispute Confirmation
            split.ProcessIt(DocActionVariables.ACTION_PREPARE);
            //	split.createConfirmation();
            split.Save(Get_TrxName());
            MInOutConfirm[] splitConfirms = split.GetConfirmations(true);
            if (splitConfirms.Length > 0)
            {
                int index = 0;
                if (splitConfirms[index].IsProcessed())
                {
                    if (splitConfirms.Length > 1)
                    {
                        index++;        //	try just next
                    }
                    if (splitConfirms[index].IsProcessed())
                    {
                        _processMsg += splitConfirms[index].GetDocumentNo() + " processed??";
                        return;
                    }
                }
                splitConfirms[index].SetIsInDispute(true);
                splitConfirms[index].Save(Get_TrxName());
                _processMsg += splitConfirms[index].GetDocumentNo();
                //	Set Lines to unconfirmed
                MInOutLineConfirm[] splitConfirmLines = splitConfirms[index].GetLines(false);
                for (int i = 0; i < splitConfirmLines.Length; i++)
                {
                    MInOutLineConfirm splitConfirmLine = splitConfirmLines[i];
                    splitConfirmLine.SetScrappedQty(Env.ZERO);
                    splitConfirmLine.SetConfirmedQty(Env.ZERO);
                    splitConfirmLine.Save(Get_TrxName());
                }
            }
            else
            {
                _processMsg += "??";
            }
        }
        /**
         *  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
            VAdvantage.Model.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_' "));

            Set_Value("VAFAM_AssetType", _assetGroup.Get_Value("VAFAM_AssetType").ToString());
            if (countVA038 > 0)
            {
                Set_Value("VA038_AmortizationTemplate_ID", VAdvantage.Utility.Util.GetValueOfInt(_assetGroup.Get_Value("VA038_AmortizationTemplate_ID")));
            }
            Set_Value("VAFAM_DepreciationType_ID", VAdvantage.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);
            }
        }
Beispiel #29
0
        /// <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, null);

            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);
                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())
                {
                    return(GetRetrievedError(sLine, "@SaveError@ @M_InOutLine_ID@"));
                    //throw new ArgumentException("@SaveError@ @M_InOutLine_ID@");
                }
                //
                invoiceLine.SetM_InOutLine_ID(sLine.GetM_InOutLine_ID());
                if (!invoiceLine.Save())
                {
                    return(GetRetrievedError(invoiceLine, "@SaveError@ @C_InvoiceLine_ID@"));
                    //throw new ArgumentException("@SaveError@ @C_InvoiceLine_ID@");
                }
            }
            return(ship.GetDocumentNo());
        }
        /**
         *  Create Difference Document
         *  @param inout shipment/receipt
         *	@param confirm confirm line
         *	@return true if created
         */
        private bool CreateDifferenceDoc(MInOut inout, MInOutLineConfirm confirm)
        {
            if (_processMsg == null)
            {
                _processMsg = "";
            }
            else if (_processMsg.Length > 0)
            {
                _processMsg += "; ";
            }
            //	Credit Memo if linked Document
            if (Env.Signum(confirm.GetDifferenceQty()) != 0 &&
                !inout.IsSOTrx() && !inout.IsReturnTrx() && inout.GetRef_InOut_ID() != 0)
            {
                log.Info("Difference=" + confirm.GetDifferenceQty());
                if (_creditMemo == null)
                {
                    _creditMemo = new MInvoice(inout, null);
                    _creditMemo.SetDescription(Msg.Translate(GetCtx(),
                                                             "M_InOutConfirm_ID") + " " + GetDocumentNo());
                    _creditMemo.SetC_DocTypeTarget_ID(MDocBaseType.DOCBASETYPE_APCREDITMEMO);
                    if (!_creditMemo.Save(Get_TrxName()))
                    {
                        _processMsg += "Credit Memo not created";
                        return(false);
                    }
                    SetC_Invoice_ID(_creditMemo.GetC_Invoice_ID());
                }
                MInvoiceLine line = new MInvoiceLine(_creditMemo);
                line.SetShipLine(confirm.GetLine());
                line.SetQty(confirm.GetDifferenceQty());        //	Entered/Invoiced
                if (!line.Save(Get_TrxName()))
                {
                    _processMsg += "Credit Memo Line not created";
                    return(false);
                }
                confirm.SetC_InvoiceLine_ID(line.GetC_InvoiceLine_ID());
            }

            //	Create Inventory Difference
            if (Env.Signum(confirm.GetScrappedQty()) != 0)
            {
                log.Info("Scrapped=" + confirm.GetScrappedQty());
                if (_inventory == null)
                {
                    MWarehouse wh = MWarehouse.Get(GetCtx(), inout.GetM_Warehouse_ID());
                    _inventory = new MInventory(wh);
                    _inventory.SetDescription(Msg.Translate(GetCtx(),
                                                            "M_InOutConfirm_ID") + " " + GetDocumentNo());
                    //vikas  new 13 jan 2016 1
                    _inventory.SetIsInternalUse(true);
                    if (_inventory.GetC_DocType_ID() == 0)
                    {
                        MDocType[] types = MDocType.GetOfDocBaseType(GetCtx(), MDocBaseType.DOCBASETYPE_MATERIALPHYSICALINVENTORY);
                        if (types.Length > 0)
                        {
                            // Get Internal Use Inv Doc Type
                            for (int i = 0; i < types.Length; i++)
                            {
                                int _count = Util.GetValueOfInt(DB.ExecuteScalar("SELECT Count(*) FROM C_DocType WHERE IsActive='Y' AND  IsInternalUse='Y' AND C_DocType_ID=" + types[i].GetC_DocType_ID()));
                                if (_count > 0)
                                {
                                    _inventory.SetC_DocType_ID(types[i].GetC_DocType_ID());
                                    break;
                                }
                            }
                        }
                        else
                        {
                            log.SaveError("Error", Msg.ParseTranslation(GetCtx(), "@NotFound@ @C_DocType_ID@"));
                            return(false);
                        }
                    }
                    // 13 jan End
                    if (!_inventory.Save(Get_TrxName()))
                    {
                        _processMsg += "Inventory not created";
                        return(false);
                    }
                    SetM_Inventory_ID(_inventory.GetM_Inventory_ID());
                }
                MInOutLine     ioLine = confirm.GetLine();
                MInventoryLine line   = new MInventoryLine(_inventory,
                                                           ioLine.GetM_Locator_ID(), ioLine.GetM_Product_ID(),
                                                           ioLine.GetM_AttributeSetInstance_ID(),
                                                           confirm.GetScrappedQty(), Env.ZERO);
                //new 15 jan
                line.SetQtyInternalUse(line.GetQtyBook());
                line.SetQtyBook(0);
                line.SetIsInternalUse(true);
                Tuple <String, String, String> mInfo = null;
                if (Env.HasModulePrefix("DTD001_", out mInfo))
                {
                    int _charge = Util.GetValueOfInt(DB.ExecuteScalar("SELECT C_Charge_ID FROM C_Charge WHERE isactive='Y' AND  DTD001_ChargeType='INV'"));
                    line.SetC_Charge_ID(_charge);
                }
                // End
                if (!line.Save(Get_TrxName()))
                {
                    _processMsg += "Inventory Line not created";
                    return(false);
                }
                confirm.SetM_InventoryLine_ID(line.GetM_InventoryLine_ID());
            }

            //
            if (!confirm.Save(Get_TrxName()))
            {
                _processMsg += "Confirmation Line not saved";
                return(false);
            }
            return(true);
        }