/// <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;
        }
예제 #2
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());
        }
        /// <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());
        }
예제 #5
0
        /// <summary>
        /// Create Facts (the accounting logic) for
        ///  MXI.
        ///     (single line)
        ///  <pre>
        ///      NotInvoicedReceipts     DR			(Receipt Org)
        ///      InventoryClearing               CR
        ///      InvoicePV               DR      CR  (difference)
        ///  Commitment
        ///         Expense							CR
        ///         Offset					DR
        ///  </pre>
        /// </summary>
        /// <param name="as1"></param>
        /// <returns></returns>
        public override List <Fact> CreateFacts(MAcctSchema as1)
        {
            List <Fact> facts = new List <Fact>();

            //  Nothing to do
            if (GetM_Product_ID() == 0 ||                               //	no Product
                Env.Signum(GetQty().Value) == 0 ||
                Env.Signum(_receiptLine.GetMovementQty()) == 0)         //	Qty = 0
            {
                log.Fine("No Product/Qty - M_Product_ID=" + GetM_Product_ID()
                         + ",Qty=" + GetQty() + ",InOutQty=" + _receiptLine.GetMovementQty());
                return(facts);
            }
            MMatchInv matchInv = (MMatchInv)GetPO();

            //  create Fact Header
            Fact fact = new Fact(this, as1, Fact.POST_Actual);

            SetC_Currency_ID(as1.GetC_Currency_ID());

            /**	Needs to be handeled in PO Matching as1 no Receipt info
             * if (_pc.isService())
             * {
             *  log.Fine("Service - skipped");
             *  return fact;
             * }
             **/


            //  NotInvoicedReceipt      DR
            //  From Receipt
            Decimal  multiplier = Math.Abs(Decimal.Round(Decimal.Divide(GetQty().Value, _receiptLine.GetMovementQty()), 12, MidpointRounding.AwayFromZero));
            FactLine dr         = fact.CreateLine(null,
                                                  GetAccount(Doc.ACCTTYPE_NotInvoicedReceipts, as1),
                                                  as1.GetC_Currency_ID(), Env.ONE, null); // updated below

            if (dr == null)
            {
                _error = "No Product Costs";
                return(null);
            }
            dr.SetQty(GetQty());
            //	dr.setM_Locator_ID(_receiptLine.getM_Locator_ID());
            //	MInOut receipt = _receiptLine.getParent();
            //	dr.setLocationFromBPartner(receipt.getC_BPartner_Location_ID(), true);	//  from Loc
            //	dr.setLocationFromLocator(_receiptLine.getM_Locator_ID(), false);		//  to Loc
            Decimal temp = dr.GetAcctBalance();

            //	Set AmtAcctCr/Dr from Receipt (sets also Project)
            if (!dr.UpdateReverseLine(MInOut.Table_ID,          //	Amt updated
                                      _receiptLine.GetM_InOut_ID(), _receiptLine.GetM_InOutLine_ID(),
                                      multiplier))
            {
                _error = "Mat.Receipt not posted yet";
                return(null);
            }
            log.Fine("CR - Amt(" + temp + "->" + dr.GetAcctBalance()
                     + ") - " + dr.ToString());

            //  InventoryClearing               CR
            //  From Invoice
            MAccount expense = _pc.GetAccount(ProductCost.ACCTTYPE_P_InventoryClearing, as1);

            if (_pc.IsService())
            {
                expense = _pc.GetAccount(ProductCost.ACCTTYPE_P_Expense, as1);
            }
            Decimal LineNetAmt = _invoiceLine.GetLineNetAmt();

            multiplier = Math.Abs(Decimal.Round(Decimal.Divide(GetQty().Value, _invoiceLine.GetQtyInvoiced()), 12, MidpointRounding.AwayFromZero));
            if (multiplier.CompareTo(Env.ONE) != 0)
            {
                LineNetAmt = Decimal.Multiply(LineNetAmt, multiplier);
            }
            if (_pc.IsService())
            {
                LineNetAmt = dr.GetAcctBalance();       //	book out exact receipt amt
            }
            FactLine cr = null;

            if (as1.IsAccrual())
            {
                cr = fact.CreateLine(null, expense,
                                     as1.GetC_Currency_ID(), null, LineNetAmt); //	updated below
                if (cr == null)
                {
                    log.Fine("Line Net Amt=0 - M_Product_ID=" + GetM_Product_ID()
                             + ",Qty=" + GetQty() + ",InOutQty=" + _receiptLine.GetMovementQty());
                    facts.Add(fact);
                    return(facts);
                }
                cr.SetQty(Decimal.Negate(GetQty().Value));
                temp = cr.GetAcctBalance();
                //	Set AmtAcctCr/Dr from Invoice (sets also Project)
                if (as1.IsAccrual() && !cr.UpdateReverseLine(MInvoice.Table_ID,                 //	Amt updated
                                                             _invoiceLine.GetC_Invoice_ID(), _invoiceLine.GetC_InvoiceLine_ID(), multiplier))
                {
                    _error = "Invoice not posted yet";
                    return(null);
                }
                log.Fine("DR - Amt(" + temp + "->" + cr.GetAcctBalance()
                         + ") - " + cr.ToString());
            }
            else        //	Cash Acct
            {
                MInvoice invoice = _invoiceLine.GetParent();
                if (as1.GetC_Currency_ID() == invoice.GetC_Currency_ID())
                {
                    LineNetAmt = MConversionRate.Convert(GetCtx(), LineNetAmt,
                                                         invoice.GetC_Currency_ID(), as1.GetC_Currency_ID(),
                                                         invoice.GetDateAcct(), invoice.GetC_ConversionType_ID(),
                                                         invoice.GetAD_Client_ID(), invoice.GetAD_Org_ID());
                }
                cr = fact.CreateLine(null, expense,
                                     as1.GetC_Currency_ID(), null, LineNetAmt);

                cr.SetQty(Decimal.Negate(Decimal.Multiply(GetQty().Value, multiplier)));
            }
            cr.SetC_Activity_ID(_invoiceLine.GetC_Activity_ID());
            cr.SetC_Campaign_ID(_invoiceLine.GetC_Campaign_ID());
            cr.SetC_Project_ID(_invoiceLine.GetC_Project_ID());
            cr.SetC_UOM_ID(_invoiceLine.GetC_UOM_ID());
            cr.SetUser1_ID(_invoiceLine.GetUser1_ID());
            cr.SetUser2_ID(_invoiceLine.GetUser2_ID());


            //  Invoice Price Variance  difference
            Decimal ipv = Decimal.Negate(Decimal.Add(cr.GetAcctBalance(), dr.GetAcctBalance()));

            if (Env.Signum(ipv) != 0)
            {
                FactLine pv = fact.CreateLine(null,
                                              _pc.GetAccount(ProductCost.ACCTTYPE_P_IPV, as1),
                                              as1.GetC_Currency_ID(), ipv);
                pv.SetC_Activity_ID(_invoiceLine.GetC_Activity_ID());
                pv.SetC_Campaign_ID(_invoiceLine.GetC_Campaign_ID());
                pv.SetC_Project_ID(_invoiceLine.GetC_Project_ID());
                pv.SetC_UOM_ID(_invoiceLine.GetC_UOM_ID());
                pv.SetUser1_ID(_invoiceLine.GetUser1_ID());
                pv.SetUser2_ID(_invoiceLine.GetUser2_ID());
            }
            log.Fine("IPV=" + ipv + "; Balance=" + fact.GetSourceBalance());

            MInOut inOut       = _receiptLine.GetParent();
            bool   isReturnTrx = inOut.IsReturnTrx();

            if (!IsPosted())
            {
                //	Cost Detail Record - data from Expense/IncClearing (CR) record
                MCostDetail.CreateInvoice(as1, GetAD_Org_ID(),
                                          GetM_Product_ID(), matchInv.GetM_AttributeSetInstance_ID(),
                                          _invoiceLine.GetC_InvoiceLine_ID(), 0,                                                                                                                  //	No cost element
                                          Decimal.Negate(cr.GetAcctBalance()), isReturnTrx ? Decimal.Negate(Utility.Util.GetValueOfDecimal(GetQty())) : Utility.Util.GetValueOfDecimal(GetQty()), //	correcting
                                          GetDescription(), GetTrx(), GetRectifyingProcess());

                //  Update Costing
                UpdateProductInfo(as1.GetC_AcctSchema_ID(),
                                  MAcctSchema.COSTINGMETHOD_StandardCosting.Equals(as1.GetCostingMethod()));
            }
            //
            facts.Add(fact);

            /** Commitment release										****/
            if (as1.IsAccrual() && as1.IsCreateCommitment())
            {
                fact = Doc_Order.GetCommitmentRelease(as1, this,
                                                      Utility.Util.GetValueOfDecimal(GetQty()), _invoiceLine.GetC_InvoiceLine_ID(), Env.ONE);
                if (fact == null)
                {
                    return(null);
                }
                facts.Add(fact);
            }   //	Commitment

            return(facts);
        }
예제 #6
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());
        }
        /**
         *  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);
            }
        }
예제 #8
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());
        }
예제 #9
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());
        }
        /**
         *  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 += "??";
            }
        }
        /// <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"));
            }
        }
예제 #12
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);
                //---------------------------Column Added by Anuj------------------
                int _CountVA009 = Util.GetValueOfInt(DB.ExecuteScalar("SELECT COUNT(AD_MODULEINFO_ID) FROM AD_MODULEINFO WHERE PREFIX='VA009_'  AND IsActive = 'Y'"));
                if (_CountVA009 > 0)
                {
                    int _PaymentMethod_ID = order.GetVA009_PaymentMethod_ID();
                    if (_PaymentMethod_ID > 0)
                    {
                        _invoice.SetVA009_PaymentMethod_ID(_PaymentMethod_ID);
                    }
                }
                //-----------------Column Added by Anuj------------------

                int _CountVA026 = Util.GetValueOfInt(DB.ExecuteScalar("SELECT COUNT(AD_MODULEINFO_ID) FROM AD_MODULEINFO WHERE PREFIX='VA026_'  AND IsActive = 'Y'"));
                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 (!_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 (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 (!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());
        }