// when doc type = Warehouse Order / Credit Order / POS Order / Prepay order --- and payment term is advance -- then system return false
        public bool checkAdvancePaymentTerm(Ctx ctx, string fields)
        {
            string[] paramValue = fields.Split(',');
            bool     isAdvancePayTerm = true;
            int      documnetType_Id = 0, PaymentTerm_Id = 0;

            documnetType_Id = Util.GetValueOfInt(paramValue[0]);
            PaymentTerm_Id  = Util.GetValueOfInt(paramValue[1]);

            // when document type is not --  Warehouse Order / Credit Order / POS Order / Prepay order, then true
            MDocType doctype = MDocType.Get(ctx, documnetType_Id);

            if (!(doctype.GetDocSubTypeSO() == X_C_DocType.DOCSUBTYPESO_PrepayOrder ||
                  doctype.GetDocSubTypeSO() == X_C_DocType.DOCSUBTYPESO_OnCreditOrder ||
                  doctype.GetDocSubTypeSO() == X_C_DocType.DOCSUBTYPESO_WarehouseOrder ||
                  doctype.GetDocSubTypeSO() == X_C_DocType.DOCSUBTYPESO_POSOrder))
            {
                isAdvancePayTerm = true;
            }
            // check payment term is Advance, then return False
            else if (Util.GetValueOfString(DB.ExecuteScalar(@"SELECT VA009_Advance FROM C_PaymentTerm
                                            WHERE C_PaymentTerm_ID = " + PaymentTerm_Id, null, null)).Equals("Y"))
            {
                isAdvancePayTerm = false;
            }
            // check any payment term schedule is Advance, then return False
            else if (Util.GetValueOfInt(DB.ExecuteScalar(@"SELECT COUNT(*) FROM C_PaySchedule 
                                            WHERE VA009_Advance = 'Y' AND C_PaymentTerm_ID = " + PaymentTerm_Id, null, null)) > 0)
            {
                isAdvancePayTerm = false;
            }

            return(isAdvancePayTerm);
        }
예제 #2
0
        /// Get Payment Base Type
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="fields"></param>
        /// <returns>Dictionary</returns>
        public Dictionary <String, object> GetPayBaseType(Ctx ctx, string fields)
        {
            if (fields != null)
            {
                Dictionary <String, object> retDic = null;
                string[] paramValue = fields.ToString().Split(',');
                //Assign parameter value
                int C_DocType_ID = Util.GetValueOfInt(paramValue[0].ToString());
                //End Assign parameter

                MDocType _doctype = new MDocType(ctx, C_DocType_ID, null);
                if (_doctype != null)
                {
                    retDic = new Dictionary <string, object>();
                    retDic["DocBaseType"] = _doctype.GetDocBaseType();
                    return(retDic);
                }
                else
                {
                    return(null);
                }
            }
            else
            {
                return(null);
            }
        }
예제 #3
0
        public void CreateCashLine(MInvoice invoice, int C_InvoicePaySchedule_ID, decimal amt)
        {
            SetC_Invoice_ID(invoice.GetC_Invoice_ID());
            SetC_InvoicePaySchedule_ID(C_InvoicePaySchedule_ID);
            SetCashType(CASHTYPE_Invoice);
            SetC_BPartner_ID(invoice.GetC_BPartner_ID());
            SetC_Currency_ID(invoice.GetC_Currency_ID());
            //	Amount
            MDocType dt = MDocType.Get(GetCtx(), invoice.GetC_DocType_ID());

            if (MDocBaseType.DOCBASETYPE_APINVOICE.Equals(dt.GetDocBaseType()) ||
                MDocBaseType.DOCBASETYPE_ARCREDITMEMO.Equals(dt.GetDocBaseType()))
            {
                amt = Decimal.Negate(amt);
                SetVSS_PAYMENTTYPE("P");
            }
            else
            {
                SetVSS_PAYMENTTYPE("R");
            }
            SetAmount(amt);
            //
            SetDiscountAmt(Env.ZERO);
            SetWriteOffAmt(Env.ZERO);
            SetIsGenerated(true);
            _invoice = invoice;
        }
예제 #4
0
        public String PrepareIt()
        {
            MDocType dt = MDocType.Get(GetCtx(), GetC_DocType_ID());

            if (!MPeriod.IsOpen(GetCtx(), GetDateAcct(), dt.GetDocBaseType()))
            {
                _processMsg = "@PeriodClosed@";
                return(DocActionVariables.STATUS_INVALID);
            }

            // is Non Business Day?
            if (MNonBusinessDay.IsNonBusinessDay(GetCtx(), GetDateAcct()))
            {
                _processMsg = VAdvantage.Common.Common.NONBUSINESSDAY;
                return(DocActionVariables.STATUS_INVALID);
            }
            if (IsVA027_MultiCheque())
            {
                if (Util.GetValueOfInt(DB.ExecuteScalar("Select Count(*) From VA027_ChequeDetails Where VA027_PostDatedCheck_ID=" + GetVA027_PostDatedCheck_ID(), null, Get_Trx())) <= 0)
                {
                    _processMsg = "@NoLinesFound@";
                    return(DocActionVariables.STATUS_INVALID);
                }
            }

            return(DocActionVariables.STATUS_INPROGRESS);
        }
예제 #5
0
        }       //	prepare

        /// <summary>
        /// Perrform Process.
        /// </summary>
        /// <returns>Message </returns>
        protected override String DoIt()
        {
            log.Info("M_Warehouse_ID=" + _M_Warehouse_ID
                     + ", C_BPartner_ID=" + _C_BPartner_ID
                     + " - ReplenishmentCreate=" + _ReplenishmentCreate
                     + ", C_DocType_ID=" + _C_DocType_ID);
            if (_ReplenishmentCreate != null && _C_DocType_ID == 0 || _C_DocType_ID == -1)
            {
                throw new Exception("@FillMandatory@ @C_DocType_ID@");
            }


            MWarehouse wh = MWarehouse.Get(GetCtx(), _M_Warehouse_ID);

            if (wh.Get_ID() == 0)
            {
                throw new Exception("@FillMandatory@ @M_Warehouse_ID@");
            }
            if (wh.GetM_WarehouseSource_ID() > 0)
            {
                _M_WareSource = "M_WarehouseSource_ID = " + Util.GetValueOfString(wh.GetM_WarehouseSource_ID());
            }
            else
            {
                _M_WareSource = null;
            }
            //
            PrepareTable();
            FillTable(wh);
            //
            if (_ReplenishmentCreate == null)
            {
                return("OK");
            }
            //
            MDocType dt = MDocType.Get(GetCtx(), _C_DocType_ID);

            if (!dt.GetDocBaseType().Equals(_ReplenishmentCreate))
            {
                throw new Exception("@C_DocType_ID@=" + dt.GetName() + " <> " + _ReplenishmentCreate);
            }
            //

            if (_ReplenishmentCreate.Equals("POO"))
            {
                CreatePO();
            }
            else if (_ReplenishmentCreate.Equals("POR"))
            {
                CreateRequisition();
            }
            else if (_ReplenishmentCreate.Equals("MMM"))
            {
                CreateMovements();
            }
            return(_info);
        }       //	doIt
        /// <summary>
        /// Process
        /// </summary>
        /// <returns>message</returns>
        protected override String DoIt()
        {
            MPeriod period = new MPeriod(GetCtx(), _C_Period_ID, Get_Trx());

            // Get all Document type related to Tenant
            MDocType[]    types     = MDocType.GetOfClient(GetCtx());
            int           count     = 0;
            List <String> baseTypes = new List <String>();
            ValueNamePair vp        = null;

            // Split multiselected organizations to get array
            if (!String.IsNullOrEmpty(orgs))
            {
                _AD_Org_ID = orgs.Split(',');
            }


            for (int i = 0; i < types.Length; i++)
            {
                MDocType type        = types[i];
                String   docBaseType = type.GetDocBaseType();
                if (baseTypes.Contains(docBaseType))
                {
                    continue;
                }

                // loop on multiple selected organizations
                for (int j = 0; j < _AD_Org_ID.Length; j++)
                {
                    MPeriodControl pc = new MPeriodControl(period, docBaseType);
                    pc.SetAD_Org_ID(Util.GetValueOfInt(_AD_Org_ID[j]));
                    if (pc.Save())
                    {
                        count++;
                    }
                    else
                    {
                        vp = VLogger.RetrieveError();
                        if (vp != null)
                        {
                            log.Severe(Msg.GetMsg(GetCtx(), "PeriodCtlNotSaved") + ", " + vp.GetName());
                        }
                        else
                        {
                            log.Severe(Msg.GetMsg(GetCtx(), "PeriodCtlNotSaved"));
                        }
                    }
                }
                baseTypes.Add(docBaseType);
            }

            log.Fine("PeriodControl #" + count);

            return(Msg.GetMsg(GetCtx(), "PeriodControlGenerated"));
        }
        public static void CreateDocumentTypes(Ctx ctx, int AD_Client_ID, SvrProcess sp, Trx trxName)
        {
            _log.Info("AD_Client_ID=" + AD_Client_ID);
            String sql = "SELECT rl.Value, rl.Name "
                         + "FROM AD_Ref_List rl "
                         + "WHERE rl.AD_Reference_ID=183"
                         + " AND rl.IsActive='Y' AND NOT EXISTS "
                         + " (SELECT * FROM C_DocType dt WHERE dt.AD_Client_ID='" + AD_Client_ID + "' AND rl.Value=dt.DocBaseType)";
            IDataReader idr = null;

            try
            {
                idr = DataBase.DB.ExecuteReader(sql, null);
                while (idr.Read())
                {
                    String name  = idr[1].ToString();
                    String value = idr[0].ToString();
                    _log.Config(name + "=" + value);
                    MDocType dt = new MDocType(ctx, value, name, trxName);
                    if (dt.Save())
                    {
                        if (sp != null)
                        {
                            sp.AddLog(0, null, null, name);
                        }
                        else
                        {
                            _log.Fine(name);
                        }
                    }
                    else
                    {
                        if (sp != null)
                        {
                            sp.AddLog(0, null, null, "Not created: " + name);
                        }
                        else
                        {
                            _log.Warning("Not created: " + name);
                        }
                    }
                }
                idr.Close();
            }
            catch (Exception e)
            {
                if (idr != null)
                {
                    idr.Close();
                }
                _log.Log(Level.SEVERE, sql, e);
            }
        }       //	createDocumentTypes
예제 #8
0
        /// <summary>
        /// Get DocType Detail
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="fields"></param>
        /// <returns></returns>
        public Dictionary <string, string> GetDocType(Ctx ctx, string fields)
        {
            string[] paramValue = fields.Split(',');
            int      C_DocType_ID;

            //Assign parameter value
            C_DocType_ID = Util.GetValueOfInt(paramValue[0].ToString());
            //End Assign parameter
            MDocType dt = MDocType.Get(ctx, C_DocType_ID);
            Dictionary <string, string> result = new Dictionary <string, string>();

            result["IsSOTrx"] = dt.IsSOTrx().ToString();
            return(result);
        }
예제 #9
0
        /**
         *  Set Invoice - no discount
         *	@param invoice invoice
         */
        public void SetInvoiceMultiCurrency(MInvoice invoice, Decimal Amt, int C_Currency_ID)
        {
            SetC_Invoice_ID(invoice.GetC_Invoice_ID());
            SetCashType(CASHTYPE_Invoice);
            SetC_Currency_ID(C_Currency_ID);
            //	Amount
            MDocType dt  = MDocType.Get(GetCtx(), invoice.GetC_DocType_ID());
            Decimal  amt = Amt;

            if (MDocBaseType.DOCBASETYPE_APINVOICE.Equals(dt.GetDocBaseType()) ||
                MDocBaseType.DOCBASETYPE_ARCREDITMEMO.Equals(dt.GetDocBaseType()))
            {
                amt = Decimal.Negate(amt);
            }
            SetAmount(amt);
            //
            SetDiscountAmt(Env.ZERO);
            SetWriteOffAmt(Env.ZERO);
            SetIsGenerated(true);
            _invoice = invoice;
        }
예제 #10
0
        protected override bool BeforeSave(bool newRecord)
        {
            //JID_1292: Cheque Date must be greater than Account Date
            if (newRecord || Is_ValueChanged("VA027_CheckDate") || Is_ValueChanged("IsActive"))
            {
                // not to check in case of Reverse
                if (!(GetVA027_Description() != null && GetVA027_Description().Contains("{->")))
                {
                    // can be check when Multi cheque is False
                    if (Util.GetValueOfString(Get_Value("VA027_MultiCheque")) == "False")
                    {
                        if (GetVA027_CheckDate().Value.Date <= GetDateAcct().Value.Date)
                        {
                            log.SaveError("", Msg.GetMsg(GetCtx(), "VA027_CheckDateCanbeGreaterSys"));         // Cheque Date must be greater than Account Date
                            return(false);
                        }
                    }
                }
            }
            //if charge is not selected then set the tax_id=0
            if (GetC_Charge_ID() == 0)
            {
                SetC_Tax_ID(0);
            }
            else
            {
                sql = "SELECT COUNT(VA027_CheckAllocate_ID) FROM VA027_CheckAllocate i INNER JOIN VA027_ChequeDetails ii " +
                      "ON i.VA027_ChequeDetails_ID = ii.VA027_ChequeDetails_ID INNER JOIN VA027_PostDatedCheck iii " +
                      "ON ii.VA027_PostDatedCheck_ID = iii.VA027_PostDatedCheck_ID " +
                      "WHERE iii.VA027_PostDatedCheck_ID = " + GetVA027_PostDatedCheck_ID();
                if (Util.GetValueOfInt(DB.ExecuteScalar(sql, null, Get_TrxName())) > 0)
                {
                    log.SaveError("", Msg.GetMsg(GetCtx(), "VA027_DeleLineFirst"));
                    return(false);
                }
            }

            // Validate -- if check detail recotd exisy then not able to chage document type Account, Bank and Multicheck checkbox
            if (Util.GetValueOfString(Get_ValueOld("VA027_MultiCheque")) == "True")
            {
                if (Util.GetValueOfInt(DB.ExecuteScalar("SELECT COUNT(*) FROM VA027_ChequeDetails WHERE VA027_PostDatedCheck_ID = " + GetVA027_PostDatedCheck_ID(), null, Get_Trx())) > 0)
                {
                    if (Is_ValueChanged("C_DocType_ID") || Is_ValueChanged("VA027_MultiCheque") || Is_ValueChanged("C_BankAccount_ID"))
                    {
                        SetVA027_CheckNo("");
                        log.SaveError("", Msg.GetMsg(GetCtx(), "VA027_RecordExistnotChange"));
                        return(false);
                    }
                }
                SetVA027_CheckNo("");
            }

            // validate when we giving check (Payable)
            MDocType docType = new MDocType(GetCtx(), GetC_DocType_ID(), Get_Trx());

            if (docType.GetDocBaseType() != "PDR")
            {
                // Validate Unique entry based on bank  and Check No
                if ((!string.IsNullOrEmpty(GetVA027_CheckNo()) && Util.GetValueOfString(Get_Value("VA027_MultiCheque")) == "False") &&
                    (newRecord || Is_ValueChanged("VA027_CheckNo") || Is_ValueChanged("IsActive") || Is_ValueChanged("C_DocType_ID") || Is_ValueChanged("C_BankAccount_ID")))
                {
                    string sql = null;
                    // check on Cheque Detail Tab
                    sql = @"SELECT COUNT(*) FROM VA027_ChequeDetails cd INNER JOIN VA027_PostDatedCheck pdc ON pdc.VA027_PostDatedCheck_ID = cd.VA027_PostDatedCheck_ID
                            INNER JOIN  C_BankAccount ba ON ba.C_BankAccount_ID = pdc.C_BankAccount_ID 
                            INNER JOIN C_Bank b ON b.C_Bank_ID = ba.C_Bank_ID 
                            INNER JOIN C_DocType dt ON dt.C_DocType_ID = pdc.C_DocType_ID
                            WHERE cd.IsActive = 'Y' AND pdc.IsActive = 'Y' AND pdc.VA027_MultiCheque = 'Y' AND pdc.DocStatus NOT IN ('RE', 'VO') AND
                            b.C_Bank_ID = (SELECT C_Bank_ID FROM c_bankaccount WHERE C_BankAccount_ID =" + GetC_BankAccount_ID() +
                          @" ) AND cd.VA027_CheckNo = '" + GetVA027_CheckNo() + @"' AND dt.DocBaseType <> 'PDR'";
                    int count = Util.GetValueOfInt(DB.ExecuteScalar(sql, null, Get_Trx()));
                    if (count > 0)
                    {
                        log.SaveError("", Msg.GetMsg(GetCtx(), "VA027_Bank_ChequeNoNotSame"));
                        return(false);
                    }
                    else
                    {
                        // check independently on Post Dated check table
                        count = 0;
                        if (newRecord)
                        {
                            sql = @"SELECT COUNT(*) FROM  VA027_PostDatedCheck pdc 
                                INNER JOIN  C_BankAccount ba ON ba.C_BankAccount_ID = pdc.C_BankAccount_ID 
                                INNER JOIN C_Bank b ON b.C_Bank_ID = ba.C_Bank_ID  
                                INNER JOIN C_DocType dt ON dt.C_DocType_ID = pdc.C_DocType_ID
                                WHERE pdc.IsActive = 'Y' AND pdc.DocStatus NOT IN ('RE', 'VO') AND dt.DocBaseType <> 'PDR' AND
                                b.C_Bank_ID = (SELECT C_Bank_ID FROM c_bankaccount WHERE C_BankAccount_ID =" + GetC_BankAccount_ID() +
                                  @" ) AND pdc.VA027_CheckNo = '" + GetVA027_CheckNo() + @"'";
                        }
                        else
                        {
                            sql = @"SELECT COUNT(*) FROM  VA027_PostDatedCheck pdc 
                                INNER JOIN  C_BankAccount ba ON ba.C_BankAccount_ID = pdc.C_BankAccount_ID 
                                INNER JOIN C_Bank b ON b.C_Bank_ID = ba.C_Bank_ID  
                                INNER JOIN C_DocType dt ON dt.C_DocType_ID = pdc.C_DocType_ID
                                WHERE  pdc.IsActive = 'Y' AND pdc.DocStatus NOT IN ('RE', 'VO') AND dt.DocBaseType <> 'PDR' AND 
                                b.C_Bank_ID = (SELECT C_Bank_ID FROM c_bankaccount WHERE C_BankAccount_ID =" + GetC_BankAccount_ID() +
                                  @" ) AND pdc.VA027_CheckNo = '" + GetVA027_CheckNo() + @"' AND pdc.VA027_PostDatedCheck_ID <> " + GetVA027_PostDatedCheck_ID();
                        }
                        count = Util.GetValueOfInt(DB.ExecuteScalar(sql, null, Get_Trx()));
                        if (count > 0)
                        {
                            log.SaveError("", Msg.GetMsg(GetCtx(), "VA027_Bank_ChequeNoNotSame"));
                            return(false);
                        }
                    }

                    // check Payment Table
                    count = 0;
                    sql   = @"SELECT COUNT(*) FROM  C_Payment pdc
                        INNER JOIN  C_BankAccount ba ON ba.C_BankAccount_ID = pdc.C_BankAccount_ID 
                        INNER JOIN C_Bank b ON b.C_Bank_ID = ba.C_Bank_ID  
                        INNER JOIN C_DocType dt ON dt.C_DocType_ID = pdc.C_DocType_ID
                        WHERE  pdc.IsActive = 'Y' AND
                        b.C_Bank_ID = (SELECT C_Bank_ID FROM c_bankaccount WHERE C_BankAccount_ID =" + GetC_BankAccount_ID() +
                            @" ) AND pdc.CheckNo = '" + GetVA027_CheckNo() + @"' AND DocStatus NOT IN ('RE', 'VO') AND dt.DocBaseType <> 'ARR'";
                    count = Util.GetValueOfInt(DB.ExecuteScalar(sql, null, Get_Trx()));
                    if (count > 0)
                    {
                        log.SaveError("", Msg.GetMsg(GetCtx(), "VA027_Bank_ChequeNoNotSameOnPay"));
                        return(false);
                    }
                }
            }
            // End
            return(true);
        }
        /// <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"));
            }
        }
        /// <summary>
        ///     Create Shipment
        /// </summary>
        /// <returns>info</returns>
        protected override String DoIt()
        {
            //log.info("C_Invoice_ID=" + _C_Invoice_ID
            //    + ", M_Warehouse_ID=" + _M_Warehouse_ID
            //    + ", C_DocType_ID=" + _C_DocType_ID);
            if (_C_Invoice_ID == 0)
            {
                throw new ArgumentException("@NotFound@ @C_Invoice_ID@");
            }
            if (_M_Warehouse_ID == 0)
            {
                throw new ArgumentException("@NotFound@ @M_Warehouse_ID@");
            }
            //
            MInvoice invoice = new MInvoice(GetCtx(), _C_Invoice_ID, Get_Trx());

            if (invoice.Get_ID() == 0)
            {
                throw new ArgumentException("@NotFound@ @C_Invoice_ID@");
            }
            if (!MInvoice.DOCSTATUS_Completed.Equals(invoice.GetDocStatus()))
            {
                throw new ArgumentException("@InvoiceCreateDocNotCompleted@");
            }
            MDocType dt = MDocType.Get(GetCtx(), _C_DocType_ID);

            if (invoice.IsSOTrx() != dt.IsSOTrx() ||
                invoice.IsReturnTrx() != dt.IsReturnTrx())
            {
                throw new ArgumentException("@C_DocType_ID@ <> @C_Invoice_ID@");
            }

            //*****************************Vikas  1 Dec 2015  *********************************
            //Case Msg Not Showing Proper
            MInOut ship = null;
            MOrder ord  = new MOrder(GetCtx(), invoice.GetC_Order_ID(), null);

            if (ord.GetC_BPartner_ID() > 0)
            {
                ship = new MInOut(invoice, _C_DocType_ID, null, _M_Warehouse_ID);
                // Change by Mohit Asked by Amardeep sir 02/03/2016
                ship.SetPOReference(invoice.GetPOReference());
                // End
                if (!ship.Save())
                {
                    return(GetRetrievedError(ship, "@SaveError@ Receipt"));
                    // throw new ArgumentException("@SaveError@ Receipt");
                }
            }
            else
            {
                return(GetRetrievedError(ship, "InvoiceNotLinkedWithPO"));
                //throw new ArgumentException("@InvoiceNotLinkedWithPO@");
            }

            /*
             * MInOut ship = new MInOut(invoice, _C_DocType_ID, null, _M_Warehouse_ID);
             * if (!ship.Save())
             * {
             *     throw new ArgumentException("@SaveError@ Receipt");
             * }
             */
            //************************END*****************************************
            MInvoiceLine[] invoiceLines = invoice.GetLines(false);
            for (int i = 0; i < invoiceLines.Length; i++)
            {
                MInvoiceLine invoiceLine = invoiceLines[i];

                MProduct product = invoiceLine.GetProduct();
                //	Nothing to Deliver

                // Get the lines of Invoice based on the setting taken on Tenant to allow non item Product
                if (Util.GetValueOfString(GetCtx().GetContext("$AllowNonItem")).Equals("N") &&
                    ((product != null && product.GetProductType() != MProduct.PRODUCTTYPE_Item) || invoiceLine.GetC_Charge_ID() != 0))
                {
                    continue;
                }

                MInOutLine sLine = new MInOutLine(ship);
                //JID_1679 Generate Receipt from Invoice(Vendor) for remaining quantity
                //decimal movementqty = 0;
                //if (invoiceLine.GetC_OrderLine_ID() != 0)
                //{
                //    decimal? res = 0;
                //    movementqty = Util.GetValueOfDecimal(DB.ExecuteScalar(@" select (QtyOrdered-sum(MovementQty))   from C_OrderLine ol Inner join M_InOutLine il on il.C_orderline_ID= ol.C_Orderline_Id "
                //            + " WHERE il.C_OrderLine_ID =" + invoiceLine.GetC_OrderLine_ID() + "group by QtyOrdered", null, Get_Trx()));
                //    // in case of partial receipt
                //    if (invoiceLine.GetQtyInvoiced() > movementqty && movementqty != 0)
                //    {
                //        if (product.GetC_UOM_ID() != invoiceLine.GetC_UOM_ID())
                //        {
                //            res = MUOMConversion.ConvertProductTo(GetCtx(), product.GetM_Product_ID(), invoiceLine.GetC_UOM_ID(), movementqty);
                //        }
                //        sLine.SetInvoiceLine(invoiceLine, 0,    //	Locator
                //            invoice.IsSOTrx() ? (movementqty) : Env.ZERO);
                //        sLine.SetQtyEntered(res == 0 ? (movementqty) : res);
                //        sLine.SetMovementQty(movementqty);
                //    }
                //    // if QtyInvoiced is less or No Material receipt is found against the order
                //    else
                //    {
                //        sLine.SetInvoiceLine(invoiceLine, 0,    //	Locator
                //          invoice.IsSOTrx() ? invoiceLine.GetQtyInvoiced() : Env.ZERO);
                //        sLine.SetQtyEntered(invoiceLine.GetQtyEntered());
                //        sLine.SetMovementQty(invoiceLine.GetQtyInvoiced());
                //    }
                //}
                //else
                //{
                sLine.SetInvoiceLine(invoiceLine, 0,            //	Locator
                                     invoice.IsSOTrx() ? invoiceLine.GetQtyInvoiced() : Env.ZERO);
                sLine.SetQtyEntered(invoiceLine.GetQtyEntered());
                sLine.SetMovementQty(invoiceLine.GetQtyInvoiced());
                //}
                if (invoice.IsCreditMemo())
                {
                    sLine.SetQtyEntered(Decimal.Negate(sLine.GetQtyEntered()));   //.negate());
                    sLine.SetMovementQty(Decimal.Negate(sLine.GetMovementQty())); //.negate());
                }
                if (!sLine.Save())
                {
                    ship.Get_Trx().Rollback();
                    //if (movementqty == 0)
                    //{
                    //    _processMsg += ", LineNo: " + invoiceLine.GetLine() + Msg.GetMsg(GetCtx(), "MRIsAlreadyCreated");
                    //    return _processMsg;
                    //}
                    //else
                    //{
                    return(GetRetrievedError(sLine, "@SaveError@ @M_InOutLine_ID@"));
                    //}
                    // throw new ArgumentException("@SaveError@ @M_InOutLine_ID@");
                }
                invoiceLine.SetM_InOutLine_ID(sLine.GetM_InOutLine_ID());
                //  _processMsg+= ", LineNo: "+invoiceLine.GetLine()+Msg.GetMsg(GetCtx(), "MRCreatedWithDocNo" + ship.GetDocumentNo());
                if (!invoiceLine.Save())
                {
                    return(GetRetrievedError(invoiceLine, "@SaveError@ @C_InvoiceLine_ID@"));
                    //throw new ArgumentException("@SaveError@ @C_InvoiceLine_ID@");
                }
            }
            return(ship.GetDocumentNo());
        }
        /// <summary>
        /// Create 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());
            }
        }
예제 #14
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());
        }
예제 #15
0
        }       //	doIt

        /// <summary>
        /// Create GL Journal
        /// </summary>
        /// <returns>document info</returns>
        private String CreateGLJournal()
        {
            List <X_T_InvoiceGL> list = new List <X_T_InvoiceGL>();
            String sql = "SELECT * FROM T_InvoiceGL "
                         + "WHERE AD_PInstance_ID=" + GetAD_PInstance_ID()
                         + " ORDER BY AD_Org_ID";
            IDataReader idr = null;

            try
            {
                idr = DataBase.DB.ExecuteReader(sql, null, Get_TrxName());
                while (idr.Read())
                {
                    list.Add(new X_T_InvoiceGL(GetCtx(), idr, Get_TrxName()));
                }
                idr.Close();
            }
            catch (Exception e)
            {
                if (idr != null)
                {
                    idr.Close();
                }
                log.Log(Level.SEVERE, sql, e);
            }
            if (list.Count == 0)
            {
                return(" - No Records found");
            }

            //
            MAcctSchema        aas            = MAcctSchema.Get(GetCtx(), _C_AcctSchema_ID);
            MAcctSchemaDefault asDefaultAccts = MAcctSchemaDefault.Get(GetCtx(), _C_AcctSchema_ID);
            MGLCategory        cat            = MGLCategory.GetDefaultSystem(GetCtx());

            if (cat == null)
            {
                MDocType docType = MDocType.Get(GetCtx(), _C_DocTypeReval_ID);
                cat = MGLCategory.Get(GetCtx(), docType.GetGL_Category_ID());
            }
            //
            MJournalBatch batch = new MJournalBatch(GetCtx(), 0, Get_TrxName());

            batch.SetDescription(GetName());
            batch.SetC_DocType_ID(_C_DocTypeReval_ID);
            batch.SetDateDoc(DateTime.Now);// new Timestamp(System.currentTimeMillis()));
            batch.SetDateAcct(_DateReval);
            batch.SetC_Currency_ID(aas.GetC_Currency_ID());
            if (!batch.Save())
            {
                return(GetRetrievedError(batch, "Could not create Batch"));
                //return " - Could not create Batch";
            }
            //
            MJournal journal   = null;
            Decimal? drTotal   = Env.ZERO;
            Decimal? crTotal   = Env.ZERO;
            int      AD_Org_ID = 0;

            for (int i = 0; i < list.Count; i++)
            {
                X_T_InvoiceGL gl = list[i];//.get(i);
                if (Env.Signum(gl.GetAmtRevalDrDiff()) == 0 && Env.Signum(gl.GetAmtRevalCrDiff()) == 0)
                {
                    continue;
                }
                MInvoice invoice = new MInvoice(GetCtx(), gl.GetC_Invoice_ID(), null);
                if (invoice.GetC_Currency_ID() == aas.GetC_Currency_ID())
                {
                    continue;
                }
                //
                if (journal == null)
                {
                    journal = new MJournal(batch);
                    journal.SetC_AcctSchema_ID(aas.GetC_AcctSchema_ID());
                    journal.SetC_Currency_ID(aas.GetC_Currency_ID());
                    journal.SetC_ConversionType_ID(_C_ConversionTypeReval_ID);
                    MOrg org = MOrg.Get(GetCtx(), gl.GetAD_Org_ID());
                    journal.SetDescription(GetName() + " - " + org.GetName());
                    journal.SetGL_Category_ID(cat.GetGL_Category_ID());
                    if (!journal.Save())
                    {
                        return(GetRetrievedError(journal, "Could not create Journal"));
                        //return " - Could not create Journal";
                    }
                }
                //
                MJournalLine line = new MJournalLine(journal);
                line.SetLine((i + 1) * 10);
                line.SetDescription(invoice.GetSummary());
                //
                MFactAcct fa = new MFactAcct(GetCtx(), gl.GetFact_Acct_ID(), null);
                line.SetC_ValidCombination_ID(MAccount.Get(fa));
                Decimal?dr = gl.GetAmtRevalDrDiff();
                Decimal?cr = gl.GetAmtRevalCrDiff();
                drTotal = Decimal.Add(drTotal.Value, dr.Value);
                crTotal = Decimal.Add(crTotal.Value, cr.Value);
                line.SetAmtSourceDr(dr.Value);
                line.SetAmtAcctDr(dr.Value);
                line.SetAmtSourceCr(cr.Value);
                line.SetAmtAcctCr(cr.Value);
                line.Save();
                //
                if (AD_Org_ID == 0)             //	invoice org id
                {
                    AD_Org_ID = gl.GetAD_Org_ID();
                }
                //	Change in Org
                if (AD_Org_ID != gl.GetAD_Org_ID())
                {
                    CreateBalancing(asDefaultAccts, journal, drTotal.Value, crTotal.Value, AD_Org_ID, (i + 1) * 10);
                    //
                    AD_Org_ID = gl.GetAD_Org_ID();
                    drTotal   = Env.ZERO;
                    crTotal   = Env.ZERO;
                    journal   = null;
                }
            }
            CreateBalancing(asDefaultAccts, journal, drTotal.Value, crTotal.Value, AD_Org_ID, (list.Count + 1) * 10);

            return(" - " + batch.GetDocumentNo() + " #" + list.Count);
        }       //	createGLJournal
        /**
         *  Create Difference Document
         *  @param inout shipment/receipt
         *	@param confirm confirm line
         *	@return true if created
         */
        private bool CreateDifferenceDoc(MInOut inout, MInOutLineConfirm confirm)
        {
            if (_processMsg == null)
            {
                _processMsg = "";
            }
            else if (_processMsg.Length > 0)
            {
                _processMsg += "; ";
            }
            //	Credit Memo if linked Document
            if (Env.Signum(confirm.GetDifferenceQty()) != 0 &&
                !inout.IsSOTrx() && !inout.IsReturnTrx() && inout.GetRef_InOut_ID() != 0)
            {
                log.Info("Difference=" + confirm.GetDifferenceQty());
                if (_creditMemo == null)
                {
                    _creditMemo = new MInvoice(inout, null);
                    _creditMemo.SetDescription(Msg.Translate(GetCtx(),
                                                             "M_InOutConfirm_ID") + " " + GetDocumentNo());
                    _creditMemo.SetC_DocTypeTarget_ID(MDocBaseType.DOCBASETYPE_APCREDITMEMO);
                    if (!_creditMemo.Save(Get_TrxName()))
                    {
                        _processMsg += "Credit Memo not created";
                        return(false);
                    }
                    SetC_Invoice_ID(_creditMemo.GetC_Invoice_ID());
                }
                MInvoiceLine line = new MInvoiceLine(_creditMemo);
                line.SetShipLine(confirm.GetLine());
                line.SetQty(confirm.GetDifferenceQty());        //	Entered/Invoiced
                if (!line.Save(Get_TrxName()))
                {
                    _processMsg += "Credit Memo Line not created";
                    return(false);
                }
                confirm.SetC_InvoiceLine_ID(line.GetC_InvoiceLine_ID());
            }

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

            //
            if (!confirm.Save(Get_TrxName()))
            {
                _processMsg += "Confirmation Line not saved";
                return(false);
            }
            return(true);
        }
예제 #17
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());
        }
예제 #18
0
        public bool ReverseCorrectIt()
        {
            try
            {
                MDocType dt = MDocType.Get(GetCtx(), GetC_DocType_ID());
                if (!MPeriod.IsOpen(GetCtx(), GetDateAcct(), dt.GetDocBaseType()))
                {
                    _processMsg = "@PeriodClosed@";
                    return(false);
                }

                // is Non Business Day?
                if (MNonBusinessDay.IsNonBusinessDay(GetCtx(), GetDateAcct()))
                {
                    _processMsg = VAdvantage.Common.Common.NONBUSINESSDAY;
                    return(false);
                }
                //commented by arpit
                //if (!IsVA027_PaymentGenerated())
                //{
                //    _processMsg = "Payment Not Generated Yet";
                //    Get_Trx().Rollback();
                //    return false;
                //}
                //end here
                if (GetC_Payment_ID() > 0)
                {
                    MPayment pay = new MPayment(GetCtx(), GetC_Payment_ID(), Get_Trx());
                    if (pay.GetDocStatus() != "RE" && pay.GetDocStatus() != "VO")
                    {
                        _processMsg = Msg.GetMsg(GetCtx(), "VA027_PaymentNotVoid");
                        Get_Trx().Rollback();
                        return(false);
                    }
                }
                MVA027PostDatedCheck reversal = new MVA027PostDatedCheck(GetCtx(), 0, Get_Trx());
                CopyValues(this, reversal);
                reversal.SetClientOrg(this);
                reversal.SetVA027_PayAmt(Decimal.Negate(reversal.GetVA027_PayAmt()));
                reversal.SetDocumentNo(GetDocumentNo() + REVERSE_INDICATOR);
                if (!string.IsNullOrEmpty(GetVA027_CheckNo()))
                {
                    reversal.SetVA027_CheckNo(GetVA027_CheckNo() + REVERSE_INDICATOR);
                }
                reversal.SetDocStatus(DOCSTATUS_Drafted);
                reversal.SetDocAction(DOCACTION_Complete);
                reversal.SetProcessed(false);
                reversal.SetProcessing(false);
                reversal.SetPosted(false);
                reversal.SetVA027_Description(GetVA027_Description());
                reversal.AddDescription("{->" + GetDocumentNo() + ")");
                if (reversal.Save(Get_Trx()))
                {
                    DataSet ds = new DataSet();
                    ds = DB.ExecuteDataset("Select * from VA027_CHEQUEDETAILS Where VA027_PostDatedCheck_ID=" + GetVA027_PostDatedCheck_ID(), null, Get_Trx());
                    if (ds != null && ds.Tables[0].Rows.Count > 0)
                    {
                        for (Int32 i = 0; i < ds.Tables[0].Rows.Count; i++)
                        {
                            MVA027ChequeDetails original = new MVA027ChequeDetails(GetCtx(), Util.GetValueOfInt(ds.Tables[0].Rows[i]["VA027_CHEQUEDETAILS_ID"]), Get_Trx());
                            MVA027ChequeDetails cd       = new MVA027ChequeDetails(GetCtx(), 0, Get_Trx());
                            if (original.GetC_Payment_ID() > 0)
                            {
                                MPayment payment = new MPayment(GetCtx(), original.GetC_Payment_ID(), Get_Trx());
                                if (payment.GetDocStatus() != "RE" && payment.GetDocStatus() != "VO")
                                {
                                    _processMsg = Msg.GetMsg(GetCtx(), "VA027_PaymentNotVoid");
                                    Get_Trx().Rollback();
                                    return(false);
                                }
                            }
                            cd.SetAD_Client_ID(original.GetAD_Client_ID());
                            cd.SetAD_Org_ID(original.GetAD_Org_ID());
                            cd.SetVA027_AccountName(original.GetVA027_AccountName());
                            cd.SetLineNo(original.GetLineNo());
                            cd.SetVA027_PostDatedCheck_ID(reversal.GetVA027_PostDatedCheck_ID());
                            cd.SetVA027_AccountNo(original.GetVA027_AccountNo());
                            cd.SetVA027_CheckDate(original.GetVA027_CheckDate());
                            cd.SetVA027_CheckNo(original.GetVA027_CheckNo() + REVERSE_INDICATOR);
                            cd.SetVA027_ChequeAmount(Decimal.Negate(original.GetVA027_ChequeAmount()));
                            cd.SetVA027_MICR(original.GetVA027_MICR());
                            cd.SetVA027_PaymentStatus("3");
                            cd.SetVA027_ValidMonth(original.GetVA027_ValidMonth());
                            cd.SetProcessed(true);
                            cd.Save(Get_Trx());
                        }
                    }
                }

                if (!reversal.ProcessIt(DocActionVariables.ACTION_COMPLETE))
                {
                    _processMsg = "Reversal ERROR: " + reversal.GetProcessMsg();
                    return(false);
                }
                reversal.CloseIt();
                _processMsg = reversal.GetDocumentNo();
                reversal.SetVA027_PaymentStatus("3");
                reversal.SetDocStatus(DOCSTATUS_Reversed);
                reversal.SetDocAction(DOCACTION_None);
                reversal.Save(Get_Trx());

                this.AddDescription("(" + GetDocumentNo() + "<-)");

                SetDocStatus(DOCSTATUS_Reversed);
                SetDocAction(DOCACTION_None);
                SetProcessed(true);
            }
            catch (Exception ex)
            {
                log.Severe(ex.ToString());
                log.Severe("Error in Reverse.");
            }

            return(true);
        }
        /**
         *  Complete Document
         *  @return new status (Complete, In Progress, Invalid, Waiting ..)
         */
        public String CompleteIt()
        {
            //	Re-Check
            if (!_justPrepared)
            {
                String status = PrepareIt();
                if (!DocActionVariables.STATUS_INPROGRESS.Equals(status))
                {
                    return(status);
                }
            }
            //	Implicit Approval
            if (!IsApproved())
            {
                ApproveIt();
            }
            log.Info(ToString());
            //
            MInOut inout = new MInOut(GetCtx(), GetM_InOut_ID(), Get_TrxName());

            MInOutLineConfirm[] lines = GetLines(false);

            /* created by sunil 19/9/2016*/
            if (Util.GetValueOfInt(DB.ExecuteScalar("SELECT COUNT(*) FROM AD_ModuleInfo WHERE Prefix = 'DTD001_'")) > 0)
            {
                MPackage package = new MPackage(GetCtx(), inout.GetM_Package_ID(), Get_Trx());
                if (inout.GetM_Package_ID() > 0 && !package.IsDTD001_IsPackgConfirm())
                {
                    _processMsg = Msg.GetMsg(GetCtx(), "PleaseConfirmPackage");
                    return(DocActionVariables.STATUS_INVALID);
                }
            }
            //End

            //	Check if we need to split Shipment
            if (IsInDispute())
            {
                MDocType dt = MDocType.Get(GetCtx(), inout.GetC_DocType_ID());
                if (dt.IsSplitWhenDifference())
                {
                    if (dt.GetC_DocTypeDifference_ID() == 0)
                    {
                        _processMsg = "No Split Document Type defined for: " + dt.GetName();
                        return(DocActionVariables.STATUS_INVALID);
                    }
                    SplitInOut(inout, dt.GetC_DocTypeDifference_ID(), lines);
                    _lines = null;
                }
            }

            //	All lines
            for (int i = 0; i < lines.Length; i++)
            {
                MInOutLineConfirm confirmLine = lines[i];
                confirmLine.Set_TrxName(Get_TrxName());
                if (!confirmLine.ProcessLine(inout.IsSOTrx(), GetConfirmType()))
                {
                    _processMsg = "ShipLine not saved - " + confirmLine;
                    return(DocActionVariables.STATUS_INVALID);
                }
                if (confirmLine.IsFullyConfirmed())
                {
                    confirmLine.SetProcessed(true);
                    confirmLine.Save(Get_TrxName());
                }
                else
                {
                    if (CreateDifferenceDoc(inout, confirmLine))
                    {
                        confirmLine.SetProcessed(true);
                        confirmLine.Save(Get_TrxName());
                    }
                    else
                    {
                        log.Log(Level.SEVERE, "Scrapped=" + confirmLine.GetScrappedQty()
                                + " - Difference=" + confirmLine.GetDifferenceQty());

                        return(DocActionVariables.STATUS_INVALID);
                    }
                }
            }   //	for all lines

            if (_creditMemo != null)
            {
                _processMsg += " @C_Invoice_ID@=" + _creditMemo.GetDocumentNo();
            }
            if (_inventory != null)
            {
                //   _processMsg += " @M_Inventory_ID@=" + _inventory.GetDocumentNo();
                //new 13 jan
                _processMsg += " Internal.Inventory= " + _inventory.GetDocumentNo();
            }


            //	User Validation
            String valid = ModelValidationEngine.Get().FireDocValidate(this,
                                                                       ModalValidatorVariables.DOCTIMING_AFTER_COMPLETE);

            if (valid != null)
            {
                _processMsg = valid;
                return(DocActionVariables.STATUS_INVALID);
            }

            SetProcessed(true);
            if (!Save(Get_Trx()))
            {
                Get_Trx().Rollback();
                _processMsg = "Ship/Receipt Confirmation Not saved";
                return(DocActionVariables.STATUS_INVALID);
            }

            // Created By Sunil 17/9/2016
            // Complete Shipment
            MInOut io     = new MInOut(GetCtx(), GetM_InOut_ID(), Get_TrxName());
            var    Status = io.CompleteIt();

            if (Status == "CO")
            {
                io.SetProcessed(true);
                io.SetDocStatus(DocActionVariables.STATUS_COMPLETED);
                io.SetDocAction(DocActionVariables.ACTION_CLOSE);
                io.Save();
            }
            else if (Status == "IN")
            {
                Get_Trx().Rollback();
                _processMsg = "Shipment Not Completed";
                return(DocActionVariables.STATUS_INVALID);
            }
            //end

            //SetProcessed(true);
            SetDocAction(DOCACTION_Close);
            return(DocActionVariables.STATUS_COMPLETED);
        }
        protected override bool BeforeSave(bool newRecord)
        {
            //JID_1292: Cheque Date must be greater than Account Date
            MVA027PostDatedCheck pdc = new MVA027PostDatedCheck(GetCtx(), GetVA027_PostDatedCheck_ID(), Get_Trx());

            if (newRecord || Is_ValueChanged("VA027_CheckDate") || Is_ValueChanged("IsActive"))
            {
                if (!(pdc.GetVA027_Description() != null && pdc.GetVA027_Description().Contains("{->")))
                {
                    if (GetVA027_CheckDate().Value.Date <= pdc.GetDateAcct().Value.Date)
                    {
                        log.SaveError("", Msg.GetMsg(GetCtx(), "VA027_CheckDateCanbeGreaterSys"));
                        return(false);
                    }
                }
            }

            // validate when we giving check (Payable)
            MDocType docType = new MDocType(GetCtx(), pdc.GetC_DocType_ID(), Get_Trx());

            if (docType.GetDocBaseType() != "PDR")
            {
                // Validate Unique entry based on bank Account and Check No
                if ((!string.IsNullOrEmpty(GetVA027_CheckNo())) && (newRecord || Is_ValueChanged("VA027_CheckNo")))
                {
                    string sql = null;
                    // check on cheque detail tab
                    if (newRecord)
                    {
                        sql = @"SELECT COUNT(*) FROM VA027_ChequeDetails cd INNER JOIN VA027_PostDatedCheck pdc ON pdc.VA027_PostDatedCheck_ID = cd.VA027_PostDatedCheck_ID 
                            INNER JOIN  C_BankAccount ba ON ba.C_BankAccount_ID = pdc.C_BankAccount_ID 
                            INNER JOIN C_Bank b ON b.C_Bank_ID = ba.C_Bank_ID  
                            INNER JOIN C_DocType dt ON dt.C_DocType_ID = pdc.C_DocType_ID 
                            WHERE cd.IsActive = 'Y' AND pdc.IsActive = 'Y' AND pdc.DocStatus NOT IN ('RE', 'VO') AND dt.DocBaseType <> 'PDR' AND 
                            b.C_Bank_ID = (SELECT C_Bank_ID FROM c_bankaccount WHERE C_BankAccount_ID =" + pdc.GetC_BankAccount_ID() +
                              @" ) AND cd.VA027_CheckNo = '" + GetVA027_CheckNo() + @"'";
                    }
                    else
                    {
                        sql = @"SELECT COUNT(*) FROM VA027_ChequeDetails cd INNER JOIN VA027_PostDatedCheck pdc ON pdc.VA027_PostDatedCheck_ID = cd.VA027_PostDatedCheck_ID 
                            INNER JOIN  C_BankAccount ba ON ba.C_BankAccount_ID = pdc.C_BankAccount_ID 
                            INNER JOIN C_Bank b ON b.C_Bank_ID = ba.C_Bank_ID  
                            INNER JOIN C_DocType dt ON dt.C_DocType_ID = pdc.C_DocType_ID 
                            WHERE cd.IsActive = 'Y' AND pdc.IsActive = 'Y' AND pdc.DocStatus NOT IN ('RE', 'VO') AND dt.DocBaseType <> 'PDR' AND 
                            b.C_Bank_ID = (SELECT C_Bank_ID FROM c_bankaccount WHERE C_BankAccount_ID =" + pdc.GetC_BankAccount_ID() +
                              @" ) AND cd.VA027_CheckNo = '" + GetVA027_CheckNo() + @"' AND cd.VA027_ChequeDetails_ID <> " + GetVA027_ChequeDetails_ID();
                    }
                    int count = Util.GetValueOfInt(DB.ExecuteScalar(sql, null, Get_Trx()));
                    if (count > 0)
                    {
                        log.SaveError("Error", Msg.GetMsg(GetCtx(), "VA027_Bank_ChequeNoNotSame"));
                        return(false);
                    }
                    else
                    {
                        // check independently on Post Dated check table
                        count = 0;
                        sql   = @"SELECT COUNT(*) FROM  VA027_PostDatedCheck pdc  
                            INNER JOIN  C_BankAccount ba ON ba.C_BankAccount_ID = pdc.C_BankAccount_ID 
                            INNER JOIN C_Bank b ON b.C_Bank_ID = ba.C_Bank_ID  
                            INNER JOIN C_DocType dt ON dt.C_DocType_ID = pdc.C_DocType_ID 
                            WHERE  pdc.IsActive = 'Y' AND pdc.VA027_MultiCheque = 'N' AND dt.DocBaseType <> 'PDR' AND 
                            b.C_Bank_ID = (SELECT C_Bank_ID FROM c_bankaccount WHERE C_BankAccount_ID =" + pdc.GetC_BankAccount_ID() +
                                @" ) AND pdc.VA027_CheckNo = '" + GetVA027_CheckNo() + @"' AND pdc.DocStatus NOT IN ('RE', 'VO')";
                        count = Util.GetValueOfInt(DB.ExecuteScalar(sql, null, Get_Trx()));
                        if (count > 0)
                        {
                            log.SaveError("Error", Msg.GetMsg(GetCtx(), "VA027_Bank_ChequeNoNotSame"));
                            return(false);
                        }
                    }

                    // check Payment Table
                    count = 0;
                    sql   = @"SELECT COUNT(*) FROM  C_Payment pdc
                        INNER JOIN  C_BankAccount ba ON ba.C_BankAccount_ID = pdc.C_BankAccount_ID 
                        INNER JOIN C_Bank b ON b.C_Bank_ID = ba.C_Bank_ID  
                        INNER JOIN C_DocType dt ON dt.C_DocType_ID = pdc.C_DocType_ID
                        WHERE  pdc.IsActive = 'Y' AND
                        b.C_Bank_ID = (SELECT C_Bank_ID FROM c_bankaccount WHERE C_BankAccount_ID =" + pdc.GetC_BankAccount_ID() +
                            @" ) AND pdc.CheckNo = '" + GetVA027_CheckNo() + @"' AND DocStatus NOT IN ('RE', 'VO') AND dt.DocBaseType <> 'ARR'";
                    count = Util.GetValueOfInt(DB.ExecuteScalar(sql, null, Get_Trx()));
                    if (count > 0)
                    {
                        log.SaveError("Error", Msg.GetMsg(GetCtx(), "VA027_Bank_ChequeNoNotSameOnPay"));
                        return(false);
                    }
                }
            }
            return(true);
        }
예제 #21
0
        /// <summary>
        /// Perform Process.
        /// </summary>
        /// <returns>Message (text with variables)</returns>
        protected override String DoIt()
        {
            log.Info("M_DistributionRun_ID=" + _M_DistributionRun_ID
                     + ", C_DocType_ID=" + _C_DocType_ID
                     + ", DatePromised=" + _DatePromised
                     + ", Test=" + _IsTest);
            //	Distribution Run
            if (_M_DistributionRun_ID == 0)
            {
                throw new ArgumentException("No Distribution Run ID");
            }
            _run = new MDistributionRun(GetCtx(), _M_DistributionRun_ID, Get_TrxName());
            if (_run.Get_ID() == 0)
            {
                throw new Exception("Distribution Run not found -  M_DistributionRun_ID=" + _M_DistributionRun_ID);
            }
            _runLines = _run.GetLines(true);
            if (_runLines == null || _runLines.Length == 0)
            {
                throw new Exception("No active, non-zero Distribution Run Lines found");
            }

            //	Document Type
            if (_C_DocType_ID == 0)
            {
                throw new ArgumentException("No Document Type ID");
            }
            _docType = new MDocType(GetCtx(), _C_DocType_ID, null);     //	outside trx
            if (_docType.Get_ID() == 0)
            {
                throw new Exception("Document Type not found -  C_DocType_ID=" + _C_DocType_ID);
            }
            //
            //_DateOrdered = Utility.Util.GetValueOfDateTime(new DateTime(CommonFunctions.CurrentTimeMillis()));
            _DateOrdered = Utility.Util.GetValueOfDateTime(DateTime.Now.Date);
            if (_DatePromised == null)
            {
                _DatePromised = _DateOrdered;
            }

            //	Create Temp Lines
            if (InsertDetails() == 0)
            {
                throw new Exception("No Lines");
            }

            //	Order By Distribution Run Line
            _details = MDistributionRunDetail.Get(GetCtx(), _M_DistributionRun_ID, false, Get_TrxName());
            //	First Run -- Add & Round
            AddAllocations();

            //	Do Allocation
            int loops = 0;

            while (!IsAllocationEqTotal())
            {
                AdjustAllocation();
                AddAllocations();
                if (++loops > 10)
                {
                    throw new Exception("Loop detected - more than 10 Allocation attempts");
                }
            }

            //	Order By Business Partner
            _details = MDistributionRunDetail.Get(GetCtx(), _M_DistributionRun_ID, true, Get_TrxName());
            //	Create Orders
            CreateOrders();

            return("@Created@ #" + _counter);
        }       //	doIt
예제 #22
0
        }       //	invalidateIt

        /// <summary>
        /// Prepare Document
        /// </summary>
        /// <returns>new status (In Progress or Invalid) </returns>
        public String PrepareIt()
        {
            log.Info(ToString());
            m_processMsg = ModelValidationEngine.Get().FireDocValidate(this, ModalValidatorVariables.DOCTIMING_BEFORE_PREPARE);
            if (m_processMsg != null)
            {
                return(DocActionVariables.STATUS_INVALID);
            }
            MDocType dt = MDocType.Get(GetCtx(), GetC_DocType_ID());

            //	Get Period
            MPeriod period = MPeriod.Get(GetCtx(), GetDateAcct());

            if (period == null)
            {
                log.Warning("No Period for " + GetDateAcct());
                m_processMsg = "@PeriodNotFound@";
                return(DocActionVariables.STATUS_INVALID);
            }
            //	Standard Period
            if (period.GetC_Period_ID() != GetC_Period_ID() &&
                period.IsStandardPeriod())
            {
                m_processMsg = "@PeriodNotValid@";
                return(DocActionVariables.STATUS_INVALID);
            }
            Boolean open = period.IsOpen(dt.GetDocBaseType());

            if (!open)
            {
                log.Warning(period.GetName()
                            + ": Not open for " + dt.GetDocBaseType() + " (" + GetDateAcct() + ")");
                m_processMsg = "@PeriodClosed@";
                return(DocActionVariables.STATUS_INVALID);
            }

            // JID_0521 - Restrict if debit and credit amount is not equal.-Mohit-12-jun-2019.
            if (GetTotalCr() != GetTotalDr())
            {
                m_processMsg = Msg.GetMsg(GetCtx(), "DBAndCRAmtNotEqual");
                return(DocActionVariables.STATUS_INVALID);
            }

            //	Lines
            MJournalLine[] lines = GetLines(true);
            if (lines.Length == 0)
            {
                m_processMsg = "@NoLines@";
                return(DocActionVariables.STATUS_INVALID);
            }

            //Manish 18/7/2016 .. Because if line dimention (Amount) column sum is not equals to debit or credit value complete process will not done.
            int     journalDRAndCR = 0;
            string  getlinevalues  = "SELECT NVL(ElementType,null) AS ElementType,AmtSourceDr,AmtAcctCr,AmtSourceCr,GL_JournalLine_ID FROM GL_JournalLine where GL_Journal_ID=" + Get_Value("GL_Journal_ID");
            DataSet dts            = DB.ExecuteDataset(getlinevalues, null, null);

            if (dts != null && dts.Tables[0].Rows.Count > 0)
            {
                for (int i = 0; i < dts.Tables[0].Rows.Count; i++)
                {
                    journalDRAndCR = 0;

                    if (dts.Tables[0].Rows[i]["ElementType"].ToString() == "")
                    {
                        continue;
                    }

                    if (Convert.ToInt32(dts.Tables[0].Rows[i]["AmtSourceDr"]) > 0)
                    {
                        journalDRAndCR = Convert.ToInt32(dts.Tables[0].Rows[i]["AmtSourceDr"]);
                    }
                    else
                    {
                        if (Convert.ToInt32(dts.Tables[0].Rows[i]["AmtSourceCr"]) > 0)
                        {
                            journalDRAndCR = Convert.ToInt32(dts.Tables[0].Rows[i]["AmtSourceCr"]);
                        }
                    }

                    string getlineval = "SELECT SUM(amount) FROM gl_linedimension where GL_JournalLine_ID=" + Convert.ToInt32(dts.Tables[0].Rows[i]["GL_JournalLine_ID"]);
                    int    count      = Util.GetValueOfInt(DB.ExecuteScalar(getlineval));

                    if (journalDRAndCR != count)
                    {
                        m_processMsg = "@AmountNotMatch@";
                        return(DocActionVariables.STATUS_INVALID);
                    }
                }
            }



            //	Add up Amounts
            Decimal AmtSourceDr = Env.ZERO;
            Decimal AmtSourceCr = Env.ZERO;

            for (int i = 0; i < lines.Length; i++)
            {
                MJournalLine line = lines[i];
                if (!IsActive())
                {
                    continue;
                }
                //
                if (line.IsDocControlled())
                {
                    m_processMsg = "@DocControlledError@ - @Line@=" + line.GetLine()
                                   + " - " + line.GetAccountElementValue();
                    return(DocActionVariables.STATUS_INVALID);
                }
                //
                AmtSourceDr = Decimal.Add(AmtSourceDr, line.GetAmtAcctDr());
                AmtSourceCr = Decimal.Add(AmtSourceCr, line.GetAmtAcctCr());
            }
            SetTotalDr(AmtSourceDr);
            SetTotalCr(AmtSourceCr);

            //	Control Amount
            if (Env.ZERO.CompareTo(GetControlAmt()) != 0 &&
                GetControlAmt().CompareTo(GetTotalDr()) != 0)
            {
                m_processMsg = "@ControlAmtError@";
                return(DocActionVariables.STATUS_INVALID);
            }

            //	Unbalanced Jornal & Not Suspense
            if (AmtSourceDr.CompareTo(AmtSourceCr) != 0)
            {
                MAcctSchemaGL gl = MAcctSchemaGL.Get(GetCtx(), GetC_AcctSchema_ID());
                if (gl == null || !gl.IsUseSuspenseBalancing())
                {
                    m_processMsg = "@UnbalancedJornal@";
                    return(DocActionVariables.STATUS_INVALID);
                }
            }

            if (!DOCACTION_Complete.Equals(GetDocAction()))
            {
                SetDocAction(DOCACTION_Complete);
            }
            m_justPrepared = true;
            return(DocActionVariables.STATUS_INPROGRESS);
        }       //	prepareIt
예제 #23
0
        }       //	toString

        /// <summary>
        /// Get Document Info

        /// </summary>
        /// <returns>document info (untranslated)</returns>
        public String GetDocumentInfo()
        {
            MDocType dt = MDocType.Get(GetCtx(), GetC_DocType_ID());

            return(dt.GetName() + " " + GetDocumentNo());
        }       //	getDocumentInfo
        protected override string DoIt()
        {
            try
            {
                if (order_ID == 0)
                {
                    throw new ArgumentException("No Order");
                }

                MOrder from = new MOrder(GetCtx(), order_ID, Get_TrxName());

                // Check Validity date of Blanket Order.
                if (from.GetOrderValidTo() < DateTime.Now.Date)
                {
                    return(Msg.GetMsg(GetCtx(), "VIS_BlanketNotValid"));
                }

                MDocType dt = MDocType.Get(GetCtx(), from.GetC_DocType_ID());

                //Document Type against Release Order
                if (dt.GetDocumentTypeforReleases() == 0)
                {
                    return(Msg.GetMsg(GetCtx(), "VIS_ReleaseDocumentnotFound"));
                }

                if (from.GetDocStatus() == MOrder.DOCSTATUS_Drafted ||
                    from.GetDocStatus() == MOrder.DOCSTATUS_InProgress ||
                    from.GetDocStatus() == MOrder.DOCSTATUS_Voided ||
                    from.GetDocStatus() == MOrder.DOCSTATUS_Reversed)
                {
                    throw new Exception("Order Not Valid");
                }

                //Document Type against Release Order
                //MDocType dtt = MDocType.Get(GetCtx(), dt.GetDocumentTypeforReleases());
                //if (dtt == null)
                //{
                //    throw new Exception(Msg.GetMsg(GetCtx(), "VIS_ReleaseDocumentnotFound"));
                //}

                // JID_1474 if full quantity of all lines are released from blanket order and user run Release order process then system will not allow to create
                // Release order and give message: 'All quantity are released'.

                if (Util.GetValueOfInt(DB.ExecuteScalar("SELECT SUM(qtyentered) FROM C_OrderLine WHERE C_Order_ID = " + GetRecord_ID(), null, Get_TrxName())) == 0)
                {
                    return(Msg.GetMsg(GetCtx(), "VIS_AllQtyReleased"));
                }

                //Creating Release PO/SO against blanket Orders
                MOrder rposo = MOrder.CopyFrom(from, from.GetDateAcct(),
                                               dt.GetDocumentTypeforReleases(), false, true, Get_TrxName(), false);

                rposo.SetPOReference(Util.GetValueOfString(from.GetDocumentNo()));
                rposo.Set_Value("IsBlanketTrx", false);

                // JID_0890: On Blanket Sales/Purchase Order, Create Release Purchase/Sales Order Process was not working.
                //rposo.SetOrig_Order_ID(order_ID);
                rposo.SetC_Order_Blanket(GetRecord_ID()); //Set Blanket Order ID to release SO/PO
                rposo.SetIsSOTrx(dt.IsSOTrx());
                //Set Same Document Sequence FROM Document type-- for Document is Number Controlled
                //Commented because its creating same document no
                //if (dtt.IsDocNoControlled() && dtt.GetDocNoSequence_ID() > 0)
                //{
                //    MSequence seq = new MSequence(GetCtx(), dtt.GetDocNoSequence_ID(), Get_TrxName());
                //    rposo.SetDocumentNo(Util.GetValueOfString(seq.GetCurrentNext()));
                //}
                if (!rposo.Save(Get_TrxName()))
                {
                    ValueNamePair pp = VLogger.RetrieveError();
                    throw new Exception("Could not create new Release Order. " + (pp != null ? pp.GetName() : ""));
                }
                string msg = Msg.GetMsg(GetCtx(), "OrderCreatedSuccessfully");
                return(msg + ":" + rposo.GetDocumentNo());
            }
            catch (Exception e)
            {
                //JID_1474 : if exception is found then we have to rollback and return that exception as suggested by Puneet and Gagandeep kaur
                Get_TrxName().Rollback();
                _log.SaveError("Could not create new Release Order", e);
                return(e.Message);
            }
        }