コード例 #1
0
        /// <summary>
        /// Void Document.
        /// </summary>
        /// <returns>false</returns>
        public bool VoidIt()
        {
            log.Info(ToString());
            if (DOCSTATUS_Closed.Equals(GetDocStatus()) ||
                DOCSTATUS_Reversed.Equals(GetDocStatus()) ||
                DOCSTATUS_Voided.Equals(GetDocStatus()))
            {
                m_processMsg = "Document Closed: " + GetDocStatus();
                SetDocAction(DOCACTION_None);
                return(false);
            }

            //	Not Processed
            if (DOCSTATUS_Drafted.Equals(GetDocStatus()) ||
                DOCSTATUS_Invalid.Equals(GetDocStatus()) ||
                DOCSTATUS_InProgress.Equals(GetDocStatus()) ||
                DOCSTATUS_Approved.Equals(GetDocStatus()) ||
                DOCSTATUS_NotApproved.Equals(GetDocStatus()))
            {
                ;
            }
            //	Std Period open?
            else
            {
                if (!MPeriod.IsOpen(GetCtx(), GetStatementDate(), MDocBaseType.DOCBASETYPE_BANKSTATEMENT))
                {
                    m_processMsg = "@PeriodClosed@";
                    return(false);
                }

                // is Non Business Day?
                if (MNonBusinessDay.IsNonBusinessDay(GetCtx(), GetStatementDate()))
                {
                    m_processMsg = Common.Common.NONBUSINESSDAY;
                    return(false);
                }


                if (MFactAcct.Delete(Table_ID, GetC_BankStatement_ID(), Get_TrxName()) < 0)
                {
                    return(false);       //	could not delete
                }
            }

            //	Set lines to 0
            Decimal transactionAmt = 0; //To update transaction amount in unMatched Balance in case of void

            MBankStatementLine[] lines = GetLines(true);
            for (int i = 0; i < lines.Length; i++)
            {
                MBankStatementLine line = lines[i];
                transactionAmt += line.GetTrxAmt();
                if (line.GetStmtAmt().CompareTo(Env.ZERO) != 0)
                {
                    String description = Msg.Translate(GetCtx(), "Voided") + " ("
                                         + Msg.Translate(GetCtx(), "StmtAmt") + "=" + line.GetStmtAmt();
                    if (line.GetTrxAmt().CompareTo(Env.ZERO) != 0)
                    {
                        description += ", " + Msg.Translate(GetCtx(), "TrxAmt") + "=" + line.GetTrxAmt();
                    }
                    if (line.GetChargeAmt().CompareTo(Env.ZERO) != 0)
                    {
                        description += ", " + Msg.Translate(GetCtx(), "ChargeAmt") + "=" + line.GetChargeAmt();
                    }
                    if (line.GetInterestAmt().CompareTo(Env.ZERO) != 0)
                    {
                        description += ", " + Msg.Translate(GetCtx(), "InterestAmt") + "=" + line.GetInterestAmt();
                    }
                    description += ")";
                    line.AddDescription(description);
                    line.SetStmtAmt(Env.ZERO);
                    line.SetTrxAmt(Env.ZERO);
                    line.SetChargeAmt(Env.ZERO);
                    line.SetInterestAmt(Env.ZERO);
                    line.Save(Get_TrxName());
                    if (line.GetC_Payment_ID() != 0)
                    {
                        MPayment payment = new MPayment(GetCtx(), line.GetC_Payment_ID(), Get_TrxName());
                        payment.SetIsReconciled(false);
                        payment.Save(Get_TrxName());
                    }
                }
            }
            AddDescription(Msg.Translate(GetCtx(), "Voided"));
            Decimal voidedDifference = GetStatementDifference();

            SetStatementDifference(Env.ZERO);

            //VA009----------------------------------Anuj----------------------
            //int _CountVA009 = Util.GetValueOfInt(DB.ExecuteScalar("SELECT COUNT(AD_MODULEINFO_ID) FROM AD_MODULEINFO WHERE PREFIX='VA009_'  AND IsActive = 'Y'"));
            if (Env.IsModuleInstalled("VA009_"))
            {
                MBankStatementLine[] STlines = GetLines(false);
                string status = "R"; // Received
                for (int i = 0; i < STlines.Length; i++)
                {
                    MBankStatementLine line = STlines[i];
                    if (line.GetC_Payment_ID() != 0)
                    {
                        MPayment payment        = new MPayment(GetCtx(), line.GetC_Payment_ID(), Get_TrxName());
                        string   _paymentMethod = Util.GetValueOfString(DB.ExecuteScalar("Select va009_paymentbaseType from va009_paymentmethod where va009_paymentmethod_id=" + payment.GetVA009_PaymentMethod_ID() + " And IsActive = 'Y' AND AD_Client_ID = " + GetAD_Client_ID()));
                        if (_paymentMethod == "S") // Check
                        {
                            status = "B";          // Bounced
                        }
                        else
                        {
                            status = "C"; // Rejected
                        }
                        payment.SetVA009_ExecutionStatus(status);
                        payment.Save(Get_TrxName());

                        //MInvoicePaySchedule inp = new MInvoicePaySchedule(GetCtx(), payment.GetC_InvoicePaySchedule_ID(), Get_TrxName());
                        //inp.SetVA009_ExecutionStatus(status);
                        //inp.Save(Get_TrxName());

                        // update execution status as set on Payment on Invoice Schedule -  for those payment which are completed or closed
                        if (payment.GetDocStatus() == DOCSTATUS_Closed || payment.GetDocStatus() == DOCSTATUS_Completed)
                        {
                            int no = Util.GetValueOfInt(DB.ExecuteQuery(@"UPDATE C_InvoicePaySchedule
                                                                          SET VA009_ExecutionStatus = '" + payment.GetVA009_ExecutionStatus() + @"'  
                                                                          WHERE C_Payment_ID = " + line.GetC_Payment_ID(), null, Get_Trx()));
                        }
                    }
                }
            }
            //END----------------------------------Anuj----------------------

            //	Update Bank Account
            MBankAccount ba = MBankAccount.Get(GetCtx(), GetC_BankAccount_ID());

            ba.SetCurrentBalance(Decimal.Subtract(ba.GetCurrentBalance(), voidedDifference));
            ba.SetUnMatchedBalance(Decimal.Add(ba.GetUnMatchedBalance(), transactionAmt));   //Arpit
            ba.Save(Get_TrxName());
            SetProcessed(true);
            SetDocAction(DOCACTION_None);
            return(true);
        }
コード例 #2
0
        protected override String DoIt()
        {
            string Sql, newcon = "";

            String date      = string.Format("{0:dd/MM/yy}", today);
            int    Record_id = GetRecord_ID();

            VAdvantage.Model.X_C_Contract con = new VAdvantage.Model.X_C_Contract(GetCtx(), Record_id, null);
            if (Record_id != 0)
            {
                // Sql = "Select C_Contract_id From C_Contract where to_char(EndDate,'dd/mm/yy')='" + date + "' and C_Contract_id=" + Record_id + " and RenewContract = 'N'";
                //Sql = "Select C_Contract_id From C_Contract where to_char(EndDate,'dd/mm/yy')='" + date + "' and C_Contract_id=" + Record_id;
                Sql = "select RenewalType from c_contract where C_Contract_id=" + Record_id + " and RenewContract = 'N' and isactive = 'Y' and ad_client_id = " + GetCtx().GetAD_Client_ID();
                string renewType = Util.GetValueOfString(DB.ExecuteScalar(Sql));
                if (renewType == "M")
                {
                    Sql = "select C_Contract_id from c_contract where C_Contract_id=" + Record_id + " and RenewContract = 'N' and ad_client_id = " + GetCtx().GetAD_Client_ID();
                }
                else
                {
                    Sql = "select C_Contract_id from c_contract where (enddate- nvl(cancelbeforedays,0)) <= sysdate and C_Contract_id=" + Record_id + " and RenewContract = 'N' and ad_client_id = " + GetCtx().GetAD_Client_ID();
                }
            }
            else
            {
                //Sql = "Select C_Contract_id From C_Contract where to_char(EndDate,'dd/mm/yy')='" + date + "' and RenewContract = 'N'";
                Sql = "select C_Contract_id from c_contract where (enddate- nvl(cancelbeforedays,0)) <= sysdate and RenewalType='A' and RenewContract = 'N' and ad_client_id = " + GetCtx().GetAD_Client_ID();
            }

            IDataReader dr    = DB.ExecuteReader(Sql);
            int         COUNT = 0;

            try
            {
                while (dr.Read())
                {
                    VAdvantage.Model.X_C_Contract contact = new VAdvantage.Model.X_C_Contract(GetCtx(), Util.GetValueOfInt(dr[0]), null);

                    string type = Util.GetValueOfString(contact.GetRenewalType());
                    if (type == "M")
                    {
                        DateTime?CDate = Util.GetValueOfDateTime(contact.GetCancellationDate());

                        int cycles = Util.GetValueOfInt(contact.GetCycles());

                        string RType = contact.GetRenewalType();
                        if (CDate != null)
                        {
                            continue;
                        }
                        VAdvantage.Model.X_C_Contract New = new VAdvantage.Model.X_C_Contract(GetCtx(), 0, null);
                        New.SetRefContract(contact.GetDocumentNo());
                        New.SetC_Order_ID(contact.GetC_Order_ID());
                        New.SetC_OrderLine_ID(contact.GetC_OrderLine_ID());
                        DateTime OldStart = (DateTime)(contact.GetStartDate());
                        DateTime Start    = (DateTime)(contact.GetEndDate());
                        int      duration = (Start - OldStart).Days;
                        DateTime End      = Start.AddDays(duration);
                        New.SetStartDate(Start.AddDays(1));
                        //  New.SetEndDate(End.AddDays(1));
                        New.SetC_BPartner_ID(contact.GetC_BPartner_ID());
                        New.SetBill_Location_ID(contact.GetBill_Location_ID());
                        New.SetBill_User_ID(contact.GetBill_User_ID());
                        New.SetSalesRep_ID(contact.GetSalesRep_ID());
                        New.SetC_Currency_ID(contact.GetC_Currency_ID());
                        New.SetC_ConversionType_ID(contact.GetC_ConversionType_ID());
                        New.SetC_PaymentTerm_ID(contact.GetC_PaymentTerm_ID());

                        New.SetC_Frequency_ID(contact.GetC_Frequency_ID());
                        // invoice Count Start
                        //DateTime SDate = Start;
                        //DateTime Edate = End;
                        int      frequency = Util.GetValueOfInt(contact.GetC_Frequency_ID());
                        string   PSql      = "Select NoOfMonths from C_Frequency where C_Frequency_ID=" + frequency;
                        int      months    = Util.GetValueOfInt(DB.ExecuteScalar(PSql, null, null));
                        int      dur       = months * cycles;
                        DateTime endDate   = Start.AddMonths(dur);
                        endDate = endDate.AddDays(-1);
                        New.SetEndDate(endDate);
                        //int totaldays = (Edate - SDate).Days;
                        //int count = totaldays / days;
                        New.SetTotalInvoice(cycles);
                        //invoice Count end
                        if (Record_id != 0)
                        {
                            New.SetM_PriceList_ID(contact.GetRef_PriceList_ID());
                            String Query   = "Select M_PriceList_Version_id from M_PriceList_Version where IsActive='Y' and M_PriceList_Id=" + contact.GetRef_PriceList_ID();
                            int    Version = Util.GetValueOfInt(DB.ExecuteScalar(Query));
                            Query = "Select PriceList from M_ProductPrice where M_PriceList_Version_id=" + Version + " and M_Product_ID=" + contact.GetM_Product_ID();
                            decimal Listprice = Util.GetValueOfInt(DB.ExecuteScalar(Query));
                            Query = "Select PriceStd from M_ProductPrice where M_PriceList_Version_id=" + Version + " and M_Product_ID=" + contact.GetM_Product_ID();
                            decimal Stdprice = Util.GetValueOfInt(DB.ExecuteScalar(Query));
                            if (Stdprice == 0 && Listprice == 0)
                            {
                                dr.Close();
                                return(Msg.GetMsg(GetCtx(), "ProductNotINPriceList"));
                            }


                            New.SetPriceEntered(Stdprice);
                            New.SetPriceActual(Stdprice);
                            New.SetPriceList(Listprice);
                        }
                        else
                        {
                            New.SetM_PriceList_ID(contact.GetM_PriceList_ID());
                            New.SetPriceEntered(contact.GetPriceEntered());
                            New.SetPriceActual(contact.GetPriceActual());
                            New.SetPriceList(contact.GetPriceList());
                        }
                        New.SetC_UOM_ID(contact.GetC_UOM_ID());
                        New.SetM_Product_ID(contact.GetM_Product_ID());
                        // New.SetLineNetAmt(contact.GetLineNetAmt());

                        New.SetQtyEntered(contact.GetQtyEntered());
                        // New.SetDiscount(contact.GetDiscount());
                        New.SetC_Tax_ID(contact.GetC_Tax_ID());
                        New.SetC_Campaign_ID(contact.GetC_Campaign_ID());
                        New.SetRef_Contract_ID(contact.GetC_Contract_ID());
                        New.SetC_Project_ID(contact.GetC_Project_ID());
                        New.SetDescription(contact.GetDescription());
                        //  New.SetLineNetAmt(contact.GetLineNetAmt());
                        //  New.SetGrandTotal(contact.GetGrandTotal());
                        New.SetTaxAmt(contact.GetTaxAmt());
                        New.SetCancelBeforeDays(contact.GetCancelBeforeDays());
                        New.SetCycles(contact.GetCycles());
                        New.SetRenewContract("N");
                        New.SetScheduleContract("N");
                        New.SetDocStatus("DR");
                        New.SetRenewalType("M");

                        String  sqltax = "select rate from c_tax WHERE c_tax_id=" + contact.GetC_Tax_ID() + "";
                        Decimal?Rate   = Util.GetValueOfDecimal(DB.ExecuteScalar(sqltax, null, null));


                        New.SetLineNetAmt(Decimal.Multiply(New.GetPriceEntered(), New.GetQtyEntered()));

                        Decimal?TotalRate = Util.GetValueOfDecimal((Util.GetValueOfDecimal(New.GetLineNetAmt()) * Util.GetValueOfDecimal(Rate)) / 100);

                        TotalRate = Decimal.Round(TotalRate.Value, 2);

                        Decimal?dis = Decimal.Multiply(Decimal.Divide(Decimal.Subtract(New.GetPriceList(), New.GetPriceEntered()), New.GetPriceList()), 100);
                        //Decimal? Discount = Util.GetValueOfDecimal(((Decimal.ToDouble(PriceList.Value) - Decimal.ToDouble(PriceActual.Value)) / Decimal.ToDouble(PriceList.Value) * 100.0));

                        New.SetDiscount(dis);
                        New.SetTaxAmt(TotalRate);
                        New.SetGrandTotal(Decimal.Add(New.GetLineNetAmt(), New.GetTaxAmt()));

                        if (New.Save())
                        {
                            newcon = New.GetDocumentNo();
                            ++COUNT;
                            if (Record_id != 0)
                            {
                                contact.SetRef_Contract_ID(New.GetC_Contract_ID());
                                contact.SetRenewContract("Y");
                                if (contact.Save())
                                {
                                }
                            }
                        }
                    }
                    else
                    {
                        DateTime?CDate = Util.GetValueOfDateTime(contact.GetCancellationDate());

                        int cycles = Util.GetValueOfInt(contact.GetCycles());

                        string RType = contact.GetRenewalType();
                        if (CDate != null)
                        {
                            continue;
                        }
                        VAdvantage.Model.X_C_Contract New = new VAdvantage.Model.X_C_Contract(GetCtx(), 0, null);
                        New.SetRefContract(contact.GetDocumentNo());
                        New.SetC_Order_ID(contact.GetC_Order_ID());
                        New.SetC_OrderLine_ID(contact.GetC_OrderLine_ID());
                        DateTime OldStart = (DateTime)(contact.GetStartDate());
                        DateTime Start    = (DateTime)(contact.GetEndDate());
                        int      duration = (Start - OldStart).Days;
                        DateTime End      = Start.AddDays(duration);
                        New.SetStartDate(Start.AddDays(1));

                        int    frequency = Util.GetValueOfInt(contact.GetC_Frequency_ID());
                        string PSql      = "Select NoOfMonths from C_Frequency where C_Frequency_ID=" + frequency;
                        int    months    = Util.GetValueOfInt(DB.ExecuteScalar(PSql, null, null));
                        int    total     = months * cycles;

                        DateTime?endDate = New.GetStartDate().Value.AddMonths(total);
                        endDate = endDate.Value.AddDays(-1);
                        //int totaldays = (Edate - SDate).Days;


                        New.SetEndDate(endDate);
                        New.SetC_BPartner_ID(contact.GetC_BPartner_ID());
                        New.SetBill_Location_ID(contact.GetBill_Location_ID());
                        New.SetBill_User_ID(contact.GetBill_User_ID());
                        New.SetSalesRep_ID(contact.GetSalesRep_ID());
                        New.SetC_Currency_ID(contact.GetC_Currency_ID());
                        New.SetC_ConversionType_ID(contact.GetC_ConversionType_ID());
                        New.SetC_PaymentTerm_ID(contact.GetC_PaymentTerm_ID());

                        New.SetC_Frequency_ID(contact.GetC_Frequency_ID());
                        // invoice Count Start

                        DateTime SDate = Start;
                        DateTime Edate = End;
                        //int frequency = Util.GetValueOfInt(contact.GetC_Frequency_ID());
                        //string PSql = "Select NoOfDays from C_Frequency where C_Frequency_ID=" + frequency;
                        //int days = Util.GetValueOfInt(DB.ExecuteScalar(PSql, null, null));
                        //int totaldays = (Edate - SDate).Days;
                        //int count = totaldays / days;

                        if (Record_id != 0)
                        {
                            if (contact.GetRef_PriceList_ID() == 0)
                            {
                                dr.Close();
                                return(Msg.GetMsg(GetCtx(), "FirstSelectPriceList"));
                            }
                            New.SetM_PriceList_ID(contact.GetRef_PriceList_ID());
                            String Query   = "Select M_PriceList_Version_id from M_PriceList_Version where IsActive='Y' and M_PriceList_Id=" + contact.GetRef_PriceList_ID();
                            int    Version = Util.GetValueOfInt(DB.ExecuteScalar(Query));
                            Query = "Select PriceList,PriceStd from M_ProductPrice where M_PriceList_Version_id=" + Version + " and M_Product_ID=" + contact.GetM_Product_ID();
                            decimal Listprice = Util.GetValueOfInt(DB.ExecuteScalar(Query));
                            Query = "Select PriceList,PriceStd from M_ProductPrice where M_PriceList_Version_id=" + Version + " and M_Product_ID=" + contact.GetM_Product_ID();
                            decimal Stdprice = Util.GetValueOfInt(DB.ExecuteScalar(Query));
                            if (Stdprice == 0 && Listprice == 0)
                            {
                                return(Msg.GetMsg(GetCtx(), "ProductNotINPriceList"));
                            }


                            New.SetPriceEntered(Stdprice);
                            New.SetPriceActual(Stdprice);
                            New.SetPriceList(Listprice);
                        }
                        else
                        {
                            New.SetPriceActual(contact.GetPriceActual());
                            New.SetPriceList(contact.GetPriceList());
                            New.SetPriceEntered(contact.GetPriceEntered());
                            New.SetM_PriceList_ID(contact.GetM_PriceList_ID());
                        }
                        New.SetTotalInvoice(contact.GetCycles());
                        //invoice Count end

                        New.SetC_UOM_ID(contact.GetC_UOM_ID());
                        New.SetM_Product_ID(contact.GetM_Product_ID());
                        // New.SetLineNetAmt(contact.GetLineNetAmt());

                        New.SetQtyEntered(contact.GetQtyEntered());
                        New.SetDiscount(contact.GetDiscount());
                        New.SetC_Tax_ID(contact.GetC_Tax_ID());
                        New.SetC_Campaign_ID(contact.GetC_Campaign_ID());
                        New.SetRef_Contract_ID(contact.GetC_Contract_ID());
                        New.SetC_Project_ID(contact.GetC_Project_ID());
                        New.SetDescription(contact.GetDescription());
                        New.SetLineNetAmt(contact.GetLineNetAmt());
                        New.SetGrandTotal(contact.GetGrandTotal());
                        New.SetTaxAmt(contact.GetTaxAmt());
                        New.SetCancelBeforeDays(contact.GetCancelBeforeDays());
                        New.SetCycles(contact.GetCycles());
                        New.SetRenewContract("N");
                        New.SetScheduleContract("Y");
                        New.SetRenewalType("A");
                        New.SetDocStatus("DR");
                        if (contact.GetBillStartDate() != null)
                        {
                            New.SetBillStartDate(contact.GetBillStartDate().Value.AddMonths(contact.GetTotalInvoice()));
                        }
                        else
                        {
                            New.SetBillStartDate(New.GetStartDate());
                        }

                        if (New.Save())
                        {
                            newcon = New.GetDocumentNo();
                            ++COUNT;
                            //if (Record_id != 0)
                            //{
                            contact.SetRef_Contract_ID(New.GetC_Contract_ID());
                            contact.SetRenewContract("Y");
                            if (contact.Save())
                            {
                            }
                            //}
                            EnterSchedules(New.GetC_Contract_ID(), cycles);
                            New.SetProcessed(true);
                            New.Save();
                        }
                    }
                }
                dr.Close();
                // X_C_Contract contract = new X_C_Contract(GetCtx(),id, null);
                if (COUNT != 0 && Record_id != 0)
                {
                    return(Msg.GetMsg(GetCtx(), "ContractReNewed :" + newcon));
                }
                if (COUNT != 0)
                {
                    return(Msg.GetMsg(GetCtx(), "ContractReNewed"));
                }
                return(Msg.GetMsg(GetCtx(), "NoContractReNewed"));
            }
            catch
            {
                if (dr != null)
                {
                    dr.Close();
                    dr = null;
                }
            }
            finally {
                if (dr != null)
                {
                    dr.Close();
                    dr = null;
                }
            }
            return(Msg.GetMsg(GetCtx(), "NoContractReNewed"));
        }
コード例 #3
0
        /**
         *  Complete Document
         *  @return new status (Complete, In Progress, Invalid, Waiting ..)
         */
        public String CompleteIt()
        {
            try
            {
                //	Re-Check
                if (!_justPrepared)
                {
                    String status = PrepareIt();
                    if (!DocActionVariables.STATUS_INPROGRESS.Equals(status))
                    {
                        return(status);
                    }
                }
                //	Implicit Approval
                if (!IsApproved())
                {
                    ApproveIt();
                }
                log.Info(ToString());

                //	User Validation
                String valid = ModelValidationEngine.Get().FireDocValidate(this, ModalValidatorVariables.DOCTIMING_AFTER_COMPLETE);
                if (valid != null)
                {
                    _processMsg = valid;
                    return(DocActionVariables.STATUS_INVALID);
                }
                //
                SetProcessed(true);
                SetDocAction(DocActionVariables.ACTION_CLOSE);
                /**************************************************************************************************************/
                // Check Column Name  new 6jan 0 vikas
                int _count = Util.GetValueOfInt(DB.ExecuteScalar(" SELECT Count(*) FROM AD_Column WHERE columnname = 'DTD001_SourceReserve' "));

                Tuple <String, String, String> mInfo = null;
                if (Env.HasModulePrefix("DTD001_", out mInfo))
                {
                    MRequisitionLine[] lines   = GetLines();
                    MProduct           product = null;
                    for (int i = 0; i < lines.Length; i++)
                    {
                        MRequisitionLine line = lines[i];
                        if (line.GetM_Product_ID() > 0)
                        {
                            product = MProduct.Get(GetCtx(), line.GetM_Product_ID());
                        }

                        int loc_id = GetLocation(GetM_Warehouse_ID());
                        //new 6jan 1
                        int Sourcewhloc_id = GetSwhLocation(GetDTD001_MWarehouseSource_ID());
                        if (Sourcewhloc_id == 0)
                        {                                                                  // JID_1098: done by Bharat on 31 Jan 2019, need to correct these messages
                            _processMsg = Msg.GetMsg(GetCtx(), "DTD001_DefineSrcLocator"); //"Define Locator For That SourceWarehouse";
                            return(DocActionVariables.STATUS_INVALID);
                        }
                        //End
                        if (loc_id == 0)
                        {
                            //return Msg.GetMsg(GetCtx(),"MMPM_DefineLocator");
                            _processMsg = Msg.GetMsg(GetCtx(), "DTD001_DefineLocator"); //"Define Locator For That Warehouse";
                            return(DocActionVariables.STATUS_INVALID);
                        }
                        if (line.Get_ColumnIndex("OrderLocator_ID") > 0)
                        {
                            line.SetOrderLocator_ID(loc_id);
                            line.SetReserveLocator_ID(Sourcewhloc_id);
                            if (!line.Save())
                            {
                                _processMsg = Msg.GetMsg(GetCtx(), "ReqLineNotSaved");
                                return(DocActionVariables.STATUS_INVALID);
                            }
                        }
                        //if (Util.GetValueOfInt(DB.ExecuteScalar("SELECT COUNT(AD_MODULEINFO_ID) FROM AD_MODULEINFO WHERE PREFIX='VA203_'", null, null)) > 0)
                        // SI_0686_2 :  storage should not update in case of product is other than item type.
                        if (Env.IsModuleInstalled("VA203_") && product != null && product.GetProductType() == X_M_Product.PRODUCTTYPE_Item)
                        {
                            storage = MStorage.Get(GetCtx(), loc_id, line.GetM_Product_ID(), line.GetM_AttributeSetInstance_ID(), Get_Trx());
                            if (storage == null)
                            {
                                storage = MStorage.GetCreate(GetCtx(), loc_id, line.GetM_Product_ID(), line.GetM_AttributeSetInstance_ID(), Get_Trx());
                            }
                            storage.SetDTD001_QtyReserved((Decimal.Add(storage.GetDTD001_QtyReserved(), (Decimal)line.GetQty())));
                            if (!storage.Save())
                            {
                                log.Info("Requisition Reserverd Quantity not saved at storage at locator " + loc_id + " and product is " + line.GetM_Product_ID());
                            }
                            ///new 6jan 2
                            if (_count > 0)
                            {
                                Swhstorage = MStorage.Get(GetCtx(), Sourcewhloc_id, line.GetM_Product_ID(), line.GetM_AttributeSetInstance_ID(), Get_Trx());
                                if (Swhstorage == null)
                                {
                                    Swhstorage = MStorage.GetCreate(GetCtx(), Sourcewhloc_id, line.GetM_Product_ID(), line.GetM_AttributeSetInstance_ID(), Get_Trx());
                                }
                                Swhstorage.SetDTD001_SourceReserve((Decimal.Add(Swhstorage.GetDTD001_SourceReserve(), (Decimal)line.GetQty())));
                                if (!Swhstorage.Save())
                                {
                                    log.Info("Requisition Reserverd Quantity not saved at storage at locator " + Sourcewhloc_id + " and product is " + line.GetM_Product_ID());
                                }
                            }
                            //End
                        }
                        else if (product != null && product.GetProductType() == X_M_Product.PRODUCTTYPE_Item)
                        {
                            // SI_0657: consider Attribute also
                            storage = MStorage.Get(GetCtx(), loc_id, line.GetM_Product_ID(), line.GetM_AttributeSetInstance_ID(), Get_Trx());
                            if (storage == null)
                            {
                                //MStorage.Add(GetCtx(), GetM_Warehouse_ID(), loc_id, line.GetM_Product_ID(), 0, 0, 0, 0, line.GetQty(), null);
                                MStorage.Add(GetCtx(), GetM_Warehouse_ID(), loc_id, line.GetM_Product_ID(), line.GetM_AttributeSetInstance_ID(), line.GetM_AttributeSetInstance_ID(), (Decimal)0, (Decimal)0, (Decimal)0, line.GetQty(), Get_Trx());
                            }
                            else
                            {
                                storage.SetDTD001_QtyReserved((Decimal.Add(storage.GetDTD001_QtyReserved(), (Decimal)line.GetQty())));
                                storage.Save();
                            }
                            //new 6jan 3
                            if (_count > 0)
                            {
                                Swhstorage = MStorage.Get(GetCtx(), Sourcewhloc_id, line.GetM_Product_ID(), line.GetM_AttributeSetInstance_ID(), Get_Trx());
                                if (Swhstorage == null)
                                {
                                    MStorage.Add(GetCtx(), GetDTD001_MWarehouseSource_ID(), Sourcewhloc_id, line.GetM_Product_ID(), line.GetM_AttributeSetInstance_ID(), line.GetM_AttributeSetInstance_ID(), (Decimal)0, (Decimal)0, (Decimal)0, 0, Get_Trx());
                                    MStorage StrgResrvQty = null;
                                    StrgResrvQty = MStorage.GetCreate(GetCtx(), Sourcewhloc_id, line.GetM_Product_ID(), line.GetM_AttributeSetInstance_ID(), Get_Trx());
                                    StrgResrvQty.SetDTD001_SourceReserve(Decimal.Add(StrgResrvQty.GetDTD001_SourceReserve(), line.GetQty()));
                                    StrgResrvQty.Save();
                                }
                                else
                                {
                                    Swhstorage.SetDTD001_SourceReserve((Decimal.Add(Swhstorage.GetDTD001_SourceReserve(), (Decimal)line.GetQty())));
                                    Swhstorage.Save();
                                }
                            }
                            //End
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show("MRequisition--CompleteIt");
                log.Severe(ex.ToString());
            }
            return(DocActionVariables.STATUS_COMPLETED);
        }
コード例 #4
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());

            //	Std Period open?
            if (!MPeriod.IsOpen(GetCtx(), GetDateAcct(), dt.GetDocBaseType()))
            {
                m_processMsg = "@PeriodClosed@";
                return(DocActionVariables.STATUS_INVALID);
            }

            // is Non Business Day?
            if (MNonBusinessDay.IsNonBusinessDay(GetCtx(), GetDateAcct()))
            {
                m_processMsg = Common.Common.NONBUSINESSDAY;
                return(DocActionVariables.STATUS_INVALID);
            }


            //	Add up Amounts & prepare them
            MJournal[] journals = GetJournals(false);
            if (journals.Length == 0)
            {
                m_processMsg = "@NoLines@";
                return(DocActionVariables.STATUS_INVALID);
            }

            Decimal TotalDr = Env.ZERO;
            Decimal TotalCr = Env.ZERO;

            for (int i = 0; i < journals.Length; i++)
            {
                MJournal journal = journals[i];
                if (!journal.IsActive())
                {
                    continue;
                }
                //	Prepare if not closed
                if (DOCSTATUS_Closed.Equals(journal.GetDocStatus()) ||
                    DOCSTATUS_Voided.Equals(journal.GetDocStatus()) ||
                    DOCSTATUS_Reversed.Equals(journal.GetDocStatus()) ||
                    DOCSTATUS_Completed.Equals(journal.GetDocStatus()))
                {
                    ;
                }
                else
                {
                    String status = journal.PrepareIt();
                    if (!DocActionVariables.STATUS_INPROGRESS.Equals(status))
                    {
                        journal.SetDocStatus(status);
                        journal.Save();
                        m_processMsg = journal.GetProcessMsg();
                        return(status);
                    }
                    journal.SetDocStatus(DOCSTATUS_InProgress);
                    journal.Save();
                }
                //
                //TotalDr = TotalDr.add(journal.getTotalDr());
                TotalDr = Decimal.Add(TotalDr, journal.GetTotalDr());
                TotalCr = Decimal.Add(TotalCr, journal.GetTotalCr());
            }
            SetTotalDr(TotalDr);
            SetTotalCr(TotalCr);

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

            //	Add up Amounts
            m_justPrepared = true;
            return(DocActionVariables.STATUS_INPROGRESS);
        }       //	prepareIt
コード例 #5
0
        /// <summary>
        /// is used to save data in case of Full move container / full qty move
        /// </summary>
        /// <param name="movementId">movement header refernce</param>
        /// <param name="fromLocatorId">From Locator - from where we have to move product</param>
        /// <param name="fromContainerId">From Container - from which container, we have to move product</param>
        /// <param name="toLocatorId">To Locator - where we are moving product</param>
        /// <param name="toContainerId">To container - in which container we are moving product</param>
        /// <param name="lineNo"></param>
        /// <param name="isMoveFullContainerQty">Is Container also move with Product</param>
        /// <param name="trx">Self created Trx</param>
        /// <returns>Message : lines inserted or not</returns>
        public String SaveMoveLinewithFullContainer(int movementId, int fromLocatorId, int fromContainerId, int toLocatorId, int toContainerId, int lineNo, bool isMoveFullContainerQty, Trx trx)
        {
            MMovement     movement         = new MMovement(_ctx, movementId, trx);
            string        childContainerId = null;
            StringBuilder error            = new StringBuilder();

            // Get Path upto selected container
            string sql           = @"SELECT sys_connect_by_path(m_productcontainer_id,'->') tree
                            FROM m_productcontainer 
                           WHERE m_productcontainer_id = " + fromContainerId + @"
                            START WITH ref_m_container_id IS NULL CONNECT BY prior m_productcontainer_id = ref_m_container_id
                           ORDER BY tree ";
            string pathContainer = Util.GetValueOfString(DB.ExecuteScalar(sql, null, trx));

            // child records with Parent Id
            if (!isMoveFullContainerQty)
            {
                sql = @"SELECT tree, m_productcontainer_id FROM
                            (SELECT sys_connect_by_path(m_productcontainer_id,'->') tree , m_productcontainer_id
                             FROM m_productcontainer
                             START WITH ref_m_container_id IS NULL
                             CONNECT BY prior m_productcontainer_id = ref_m_container_id
                             ORDER BY tree  
                             )
                           WHERE tree LIKE ('" + pathContainer + "%') ";
                DataSet ds = DB.ExecuteDataset(sql, null, trx);
                if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        if (String.IsNullOrEmpty(childContainerId))
                        {
                            childContainerId = Util.GetValueOfString(ds.Tables[0].Rows[i]["m_productcontainer_id"]);
                        }
                        else
                        {
                            childContainerId += "," + Util.GetValueOfString(ds.Tables[0].Rows[i]["m_productcontainer_id"]);
                        }
                    }
                }
                ds.Dispose();
            }
            else
            {
                childContainerId = fromContainerId.ToString();
            }

            // check is same container already moved to another container
            // Ex :: p1 -> c1 and p1 -> c2
            // OR also check -- is any other container is moving into exist target container
            // Ex :: p1 -> c1 and p2 -> p1
            if (!isMoveFullContainerQty)
            {
                if (!IsContainerMoved(movementId, pathContainer, childContainerId, toContainerId, trx))
                {
                    return(Msg.GetMsg(_ctx, "VIS_AlreadyMoved"));
                }
            }

            // not to move Parent container to its child container
            if (toContainerId > 0 && childContainerId.Contains(toContainerId.ToString()))
            {
                //Parent cant be Move to its own child
                return(Msg.GetMsg(_ctx, "VIS_cantMoveParentTochild"));
            }

            // Get All records of Parent Container and child container
            sql = @"SELECT * FROM (
                            SELECT p.M_PRODUCT_ID, p.NAME, p.C_UOM_ID, u.Name AS UomName,  t.M_ATTRIBUTESETINSTANCE_ID, t.M_ProductContainer_ID,
                            SUM(t.ContainerCurrentQty) keep (dense_rank last ORDER BY t.MovementDate, t.M_Transaction_ID) AS ContainerCurrentQty
                            FROM M_Transaction t
                            INNER JOIN M_Product p ON p.M_Product_ID = t.M_Product_ID
                            INNER JOIN C_UOM u ON u.C_UOM_ID = p.C_UOM_ID
                            WHERE t.IsActive = 'Y' AND NVL(t.M_ProductContainer_ID, 0) IN ( " + childContainerId +
                  @" ) AND t.MovementDate <=" + GlobalVariable.TO_DATE(movement.GetMovementDate(), true) + @" 
                               AND t.M_Locator_ID  = " + fromLocatorId + @"
                               AND t.AD_Client_ID  = " + movement.GetAD_Client_ID() + @"
                            GROUP BY p.M_PRODUCT_ID, p.NAME, p.C_UOM_ID, u.Name, t.M_ATTRIBUTESETINSTANCE_ID, t.M_ProductContainer_ID 
                          ) t WHERE ContainerCurrentQty <> 0 ";
            DataSet dsRecords = DB.ExecuteDataset(sql, null, trx);

            if (dsRecords != null && dsRecords.Tables.Count > 0 && dsRecords.Tables[0].Rows.Count > 0)
            {
                int           movementlineId = 0;
                MMovementLine moveline       = null;
                MProduct      product        = null;
                for (int i = 0; i < dsRecords.Tables[0].Rows.Count; i++)
                {
                    movementlineId = Util.GetValueOfInt(DB.ExecuteScalar(@"SELECT NVL(M_MovementLine_ID, 0) AS M_Movement_ID FROM M_MovementLine WHERE 
                             M_Movement_ID = " + Util.GetValueOfInt(movementId) +
                                                                         @" AND M_Product_ID = " + Util.GetValueOfInt(dsRecords.Tables[0].Rows[i]["M_Product_ID"]) +
                                                                         @" AND NVL(M_AttributeSetInstance_ID, 0) = " + Util.GetValueOfInt(dsRecords.Tables[0].Rows[i]["M_AttributeSetInstance_ID"]) +
                                                                         @" AND M_Locator_ID = " + Util.GetValueOfInt(fromLocatorId) +
                                                                         @" AND NVL(M_ProductContainer_ID, 0) = " + Util.GetValueOfInt(dsRecords.Tables[0].Rows[i]["M_ProductContainer_ID"]) +
                                                                         @" AND M_LocatorTo_ID = " + Util.GetValueOfInt(toLocatorId) +
                                                                         @" AND NVL(Ref_M_ProductContainerTo_ID, 0) = " + toContainerId +
                                                                         @" AND AD_Org_ID = " + movement.GetAD_Org_ID()));

                    if (movementlineId > 0)
                    {
                        moveline = new MMovementLine(_ctx, movementlineId, trx);
                    }
                    else
                    {
                        moveline = new MMovementLine(_ctx, 0, trx);
                    }
                    if (movementlineId == 0)
                    {
                        #region Create new record of movement line
                        lineNo += 10;
                        moveline.SetAD_Client_ID(movement.GetAD_Client_ID());
                        moveline.SetAD_Org_ID(movement.GetAD_Org_ID());
                        moveline.SetM_Movement_ID(movement.GetM_Movement_ID());
                        moveline.SetLine(lineNo);
                        moveline.SetM_Product_ID(Util.GetValueOfInt(dsRecords.Tables[0].Rows[i]["M_Product_ID"]));
                        moveline.SetM_AttributeSetInstance_ID(Util.GetValueOfInt(dsRecords.Tables[0].Rows[i]["M_AttributeSetInstance_ID"]));
                        moveline.SetC_UOM_ID(Util.GetValueOfInt(dsRecords.Tables[0].Rows[i]["C_UOM_ID"]));
                        moveline.SetM_Locator_ID(fromLocatorId);
                        moveline.SetM_LocatorTo_ID(toLocatorId);
                        moveline.SetM_ProductContainer_ID(Util.GetValueOfInt(dsRecords.Tables[0].Rows[i]["M_ProductContainer_ID"]));
                        moveline.SetRef_M_ProductContainerTo_ID(toContainerId);
                        moveline.SetQtyEntered(Util.GetValueOfDecimal(dsRecords.Tables[0].Rows[i]["ContainerCurrentQty"]));
                        moveline.SetMovementQty(Util.GetValueOfDecimal(dsRecords.Tables[0].Rows[i]["ContainerCurrentQty"]));
                        moveline.SetMoveFullContainer(isMoveFullContainerQty ? false : true);
                        // when move full container, then only need to update IsParentMove and Target container (which represent - to which container we are moving)
                        // and set true value on those line which container are moving, not on its child container
                        if (!isMoveFullContainerQty)
                        {
                            moveline.SetIsParentMove(Util.GetValueOfInt(dsRecords.Tables[0].Rows[i]["M_ProductContainer_ID"]) == fromContainerId ? true : false);
                            moveline.SetTargetContainer_ID(fromContainerId);
                        }
                        #endregion
                    }
                    else
                    {
                        #region Update record of movement line
                        moveline.SetQtyEntered(Decimal.Add(moveline.GetQtyEntered(), Util.GetValueOfDecimal(dsRecords.Tables[0].Rows[i]["ContainerCurrentQty"])));
                        moveline.SetMovementQty(Decimal.Add(moveline.GetMovementQty(), Util.GetValueOfDecimal(dsRecords.Tables[0].Rows[i]["ContainerCurrentQty"])));
                        moveline.SetMoveFullContainer(true);
                        #endregion
                    }
                    if (!moveline.Save(trx))
                    {
                        #region Save error catch and rollback
                        product = MProduct.Get(_ctx, Util.GetValueOfInt(dsRecords.Tables[0].Rows[i]["M_Product_ID"]));
                        ValueNamePair pp = VLogger.RetrieveError();
                        if (pp != null)
                        {
                            _log.SaveError("Movement line not inserted through Move Container Form : ", pp.GetName());
                            if (String.IsNullOrEmpty(error.ToString()))
                            {
                                error.Append(Msg.GetMsg(_ctx, "VIS_MoveLineNotSaveFor") + product.GetName() + Msg.GetMsg(_ctx, "VIS_DueTo") + pp.GetName());
                            }
                            else
                            {
                                error.Append(" , " + Msg.GetMsg(_ctx, "VIS_MoveLineNotSaveFor") + product.GetName() + Msg.GetMsg(_ctx, "VIS_DueTo") + pp.GetName());
                            }
                        }
                        trx.Rollback();
                        #endregion
                    }
                    else
                    {
                        trx.Commit();
                    }
                }
            }
            else
            {
                return(Msg.GetMsg(_ctx, "VIS_ContainerhaveNoRecord"));
            }

            return(String.IsNullOrEmpty(error.ToString()) ? "VIS_SuccessFullyInserted" : error.ToString());
        }
コード例 #6
0
        protected override string DoIt()
        {
            sql = @"SELECT   M_Product_ID ,   M_Locator_ID ,   M_AttributeSetInstance_ID ,  M_Transaction_ID , M_InventoryLine_ID , 
                           CurrentQty ,   MovementQty ,  MovementType , movementdate , TO_Char(Created, 'DD-MON-YY HH24:MI:SS')
                    FROM M_Transaction WHERE IsActive= 'Y' ";
            //if (orgId != null && !string.IsNullOrEmpty(orgId))
            //{
            //    sql += " AND AD_Org_ID  IN ( " + orgId + " )";
            //}
            if (productId != null && !string.IsNullOrEmpty(productId))
            {
                sql += " AND M_Product_ID IN ( " + productId + " )";
            }
            sql          += " ORDER BY   M_Product_ID  ,  M_Locator_ID ,  M_AttributeSetInstance_ID , movementdate , M_Transaction_ID ASC ";
            dsTransaction = new DataSet();
            try
            {
                dsTransaction = DB.ExecuteDataset(sql, null, Get_Trx());
                if (dsTransaction != null)
                {
                    if (dsTransaction.Tables.Count > 0)
                    {
                        if (dsTransaction.Tables[0].Rows.Count > 0)
                        {
                            int i = 0;
                            for (i = 0; i < dsTransaction.Tables[0].Rows.Count; i++)
                            {
                                if (_M_Product_ID == Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Product_ID"]) &&
                                    _M_Locator_ID == Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Locator_ID"]) &&
                                    _M_AttributeSetInstance_ID == Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_AttributeSetInstance_ID"]) &&
                                    Util.GetValueOfString(dsTransaction.Tables[0].Rows[i]["MovementType"]) == "I+" &&
                                    Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_InventoryLine_ID"]) > 0)
                                {
                                    //update Quantity Book at inventory line
                                    inventoryLine = new MInventoryLine(GetCtx(), Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_InventoryLine_ID"]), Get_Trx());
                                    inventory     = new MInventory(GetCtx(), Util.GetValueOfInt(inventoryLine.GetM_Inventory_ID()), null);
                                    if (!inventory.IsInternalUse())
                                    {
                                        inventoryLine.SetQtyBook(_currentQty);
                                        inventoryLine.SetOpeningStock(_currentQty);
                                        inventoryLine.SetDifferenceQty(Decimal.Subtract(_currentQty, Util.GetValueOfDecimal(dsTransaction.Tables[0].Rows[i]["CurrentQty"])));
                                        if (!inventoryLine.Save())
                                        {
                                            log.Info("Quantity Book Not Updated at Inventory Line Tab <===> " + Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_InventoryLine_ID"]));
                                            Rollback();
                                            continue;
                                        }
                                        else
                                        {
                                            Commit();
                                        }

                                        // update movement Qty at Transaction for the same record
                                        transaction = new VAdvantage.Model.MTransaction(GetCtx(), Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Transaction_ID"]), Get_Trx());
                                        // transaction.SetMovementQty(Decimal.Subtract(inventoryLine.GetQtyCount(), _currentQty));
                                        transaction.SetMovementQty(Decimal.Negate(Decimal.Subtract(_currentQty, Util.GetValueOfDecimal(dsTransaction.Tables[0].Rows[i]["CurrentQty"]))));
                                        if (!transaction.Save())
                                        {
                                            log.Info("Current Quantity Not Updated at Transaction Tab <===> " + Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Transaction_ID"]));
                                        }
                                        else
                                        {
                                            Commit();
                                            _currentQty = Util.GetValueOfDecimal(transaction.GetCurrentQty());
                                            continue;
                                        }
                                    }
                                    else
                                    {
                                        transaction = new VAdvantage.Model.MTransaction(GetCtx(), Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Transaction_ID"]), Get_Trx());
                                        transaction.SetCurrentQty(Decimal.Add(_currentQty, Util.GetValueOfDecimal(dsTransaction.Tables[0].Rows[i]["MovementQty"])));
                                        if (!transaction.Save())
                                        {
                                            log.Info("Current Quantity Not Updated at Transaction Tab <===> " + Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Transaction_ID"]));
                                        }
                                        else
                                        {
                                            Commit();
                                            _currentQty = Decimal.Add(_currentQty, Util.GetValueOfDecimal(dsTransaction.Tables[0].Rows[i]["MovementQty"]));
                                            continue;
                                        }
                                    }
                                }
                                else if (Util.GetValueOfString(dsTransaction.Tables[0].Rows[i]["MovementType"]) == "I+" &&
                                         Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_InventoryLine_ID"]) > 0)
                                {
                                    if (_M_Product_ID > 0)
                                    {
                                        UpdateStorage(_M_Product_ID, _M_Locator_ID, _M_AttributeSetInstance_ID, _currentQty);
                                    }
                                    _currentQty   = Util.GetValueOfDecimal(dsTransaction.Tables[0].Rows[i]["CurrentQty"]);
                                    _M_Product_ID = Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Product_ID"]);
                                    _M_Locator_ID = Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Locator_ID"]);
                                    _M_AttributeSetInstance_ID = Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_AttributeSetInstance_ID"]);
                                    continue;
                                }

                                if (_M_Product_ID == Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Product_ID"]) &&
                                    _M_Locator_ID == Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Locator_ID"]) &&
                                    _M_AttributeSetInstance_ID == Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_AttributeSetInstance_ID"]))
                                {
                                    transaction = new VAdvantage.Model.MTransaction(GetCtx(), Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Transaction_ID"]), Get_Trx());
                                    transaction.SetCurrentQty(Decimal.Add(_currentQty, Util.GetValueOfDecimal(dsTransaction.Tables[0].Rows[i]["MovementQty"])));
                                    if (!transaction.Save())
                                    {
                                        log.Info("Current Quantity Not Updated at Transaction Tab <===> " + Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Transaction_ID"]));
                                    }
                                    else
                                    {
                                        Commit();
                                        log.Info("Current Quantity  Updated at Transaction Tab <===> " + Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Transaction_ID"]));
                                        _currentQty = Decimal.Add(_currentQty, Util.GetValueOfDecimal(dsTransaction.Tables[0].Rows[i]["MovementQty"]));
                                    }
                                }
                                //when Attribute not matched
                                else if (_M_Product_ID == Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Product_ID"]) &&
                                         _M_Locator_ID == Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Locator_ID"]) &&
                                         _M_AttributeSetInstance_ID != Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_AttributeSetInstance_ID"]))
                                {
                                    if (_M_Product_ID > 0)
                                    {
                                        UpdateStorage(_M_Product_ID, _M_Locator_ID, _M_AttributeSetInstance_ID, _currentQty);
                                    }
                                    _currentQty   = Util.GetValueOfDecimal(dsTransaction.Tables[0].Rows[i]["CurrentQty"]);
                                    _M_Product_ID = Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Product_ID"]);
                                    _M_Locator_ID = Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Locator_ID"]);
                                    _M_AttributeSetInstance_ID = Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_AttributeSetInstance_ID"]);
                                    continue;
                                }
                                // when Locator not Matched
                                else if (_M_Product_ID == Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Product_ID"]) &&
                                         _M_Locator_ID != Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Locator_ID"]) &&
                                         _M_AttributeSetInstance_ID == Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_AttributeSetInstance_ID"]))
                                {
                                    if (_M_Product_ID > 0)
                                    {
                                        UpdateStorage(_M_Product_ID, _M_Locator_ID, _M_AttributeSetInstance_ID, _currentQty);
                                    }
                                    _currentQty   = Util.GetValueOfDecimal(dsTransaction.Tables[0].Rows[i]["CurrentQty"]);
                                    _M_Product_ID = Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Product_ID"]);
                                    _M_Locator_ID = Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Locator_ID"]);
                                    _M_AttributeSetInstance_ID = Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_AttributeSetInstance_ID"]);
                                    continue;
                                }
                                // when Product not Matched (Changed by Amit on 5-11-2015)
                                else if (_M_Product_ID != Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Product_ID"]) &&
                                         _M_Locator_ID == Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Locator_ID"]) &&
                                         _M_AttributeSetInstance_ID == Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_AttributeSetInstance_ID"]))
                                {
                                    if (_M_Product_ID > 0)
                                    {
                                        UpdateStorage(_M_Product_ID, _M_Locator_ID, _M_AttributeSetInstance_ID, _currentQty);
                                    }
                                    _currentQty   = Util.GetValueOfDecimal(dsTransaction.Tables[0].Rows[i]["CurrentQty"]);
                                    _M_Product_ID = Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Product_ID"]);
                                    _M_Locator_ID = Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Locator_ID"]);
                                    _M_AttributeSetInstance_ID = Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_AttributeSetInstance_ID"]);
                                    continue;
                                }
                                //when Product , Locator n Attribute both not matched (means First Record)
                                else if (_M_Product_ID != Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Product_ID"]) &&
                                         _M_Locator_ID != Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Locator_ID"]) &&
                                         _M_AttributeSetInstance_ID != Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_AttributeSetInstance_ID"]))
                                {
                                    if (_M_Product_ID > 0)
                                    {
                                        UpdateStorage(_M_Product_ID, _M_Locator_ID, _M_AttributeSetInstance_ID, _currentQty);
                                    }
                                    _currentQty   = Util.GetValueOfDecimal(dsTransaction.Tables[0].Rows[i]["CurrentQty"]);
                                    _M_Product_ID = Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Product_ID"]);
                                    _M_Locator_ID = Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Locator_ID"]);
                                    _M_AttributeSetInstance_ID = Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_AttributeSetInstance_ID"]);
                                    continue;
                                }
                                //when Locator n Attribute both not matched
                                else if (_M_Product_ID == Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Product_ID"]) &&
                                         _M_Locator_ID != Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Locator_ID"]) &&
                                         _M_AttributeSetInstance_ID != Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_AttributeSetInstance_ID"]))
                                {
                                    if (_M_Product_ID > 0)
                                    {
                                        UpdateStorage(_M_Product_ID, _M_Locator_ID, _M_AttributeSetInstance_ID, _currentQty);
                                    }
                                    _currentQty   = Util.GetValueOfDecimal(dsTransaction.Tables[0].Rows[i]["CurrentQty"]);
                                    _M_Product_ID = Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Product_ID"]);
                                    _M_Locator_ID = Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Locator_ID"]);
                                    _M_AttributeSetInstance_ID = Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_AttributeSetInstance_ID"]);
                                    continue;
                                }
                                // when product and Locator not Matched
                                else if (_M_Product_ID != Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Product_ID"]) &&
                                         _M_Locator_ID != Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Locator_ID"]) &&
                                         _M_AttributeSetInstance_ID == Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_AttributeSetInstance_ID"]))
                                {
                                    if (_M_Product_ID > 0)
                                    {
                                        UpdateStorage(_M_Product_ID, _M_Locator_ID, _M_AttributeSetInstance_ID, _currentQty);
                                    }
                                    _currentQty   = Util.GetValueOfDecimal(dsTransaction.Tables[0].Rows[i]["CurrentQty"]);
                                    _M_Product_ID = Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Product_ID"]);
                                    _M_Locator_ID = Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Locator_ID"]);
                                    _M_AttributeSetInstance_ID = Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_AttributeSetInstance_ID"]);
                                    continue;
                                }
                                // when product and Attribute not Matched
                                else if (_M_Product_ID != Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Product_ID"]) &&
                                         _M_Locator_ID == Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Locator_ID"]) &&
                                         _M_AttributeSetInstance_ID != Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_AttributeSetInstance_ID"]))
                                {
                                    if (_M_Product_ID > 0)
                                    {
                                        UpdateStorage(_M_Product_ID, _M_Locator_ID, _M_AttributeSetInstance_ID, _currentQty);
                                    }
                                    _currentQty   = Util.GetValueOfDecimal(dsTransaction.Tables[0].Rows[i]["CurrentQty"]);
                                    _M_Product_ID = Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Product_ID"]);
                                    _M_Locator_ID = Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Locator_ID"]);
                                    _M_AttributeSetInstance_ID = Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_AttributeSetInstance_ID"]);
                                    continue;
                                }
                            }
                        }
                    }
                }
                dsTransaction.Dispose();
            }
            catch
            {
                if (dsTransaction != null)
                {
                    dsTransaction.Dispose();
                }
                return(Msg.GetMsg(GetCtx(), "NotCompleted"));
            }
            finally
            {
                if (dsTransaction != null)
                {
                    dsTransaction.Dispose();
                }
            }
            return(Msg.GetMsg(GetCtx(), "SucessfullyCompleted"));

            #region
            //            sql = @"SELECT   M_Product_ID ,   M_Locator_ID ,   M_AttributeSetInstance_ID ,  M_Transaction_ID ,
            //                           CurrentQty ,   MovementQty ,  MovementType , TO_Char(Created, 'DD-MON-YY HH24:MI:SS')
            //                    FROM M_Transaction WHERE IsActive= 'Y' ";
            //            //if (orgId != null && !string.IsNullOrEmpty(orgId))
            //            //{
            //            //    sql += " AND AD_Org_ID  IN ( " + orgId + " )";
            //            //}
            //            if (productId != null && !string.IsNullOrEmpty(productId))
            //            {
            //                sql += " AND M_Product_ID IN ( " + productId + " )";
            //            }
            //            sql += " ORDER BY   M_Product_ID  ,  M_Locator_ID ,  M_AttributeSetInstance_ID , Created ASC ";
            //            dsTransaction = new DataSet();
            //            try
            //            {
            //                dsTransaction = DB.ExecuteDataset(sql, null, null);
            //                if (dsTransaction != null)
            //                {
            //                    if (dsTransaction.Tables.Count > 0)
            //                    {
            //                        if (dsTransaction.Tables[0].Rows.Count > 0)
            //                        {
            //                            int i = 0;
            //                            for (i = 0; i < dsTransaction.Tables[0].Rows.Count; i++)
            //                            {
            //                                if (Util.GetValueOfString(dsTransaction.Tables[0].Rows[i]["MovementType"]) == "I+")
            //                                {
            //                                    _currentQty = Util.GetValueOfDecimal(dsTransaction.Tables[0].Rows[i]["CurrentQty"]);
            //                                    _M_Product_ID = Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Product_ID"]);
            //                                    _M_Locator_ID = Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Locator_ID"]);
            //                                    _M_AttributeSetInstance_ID = Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_AttributeSetInstance_ID"]);
            //                                    continue;
            //                                }
            //                                else if (_M_Product_ID == Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Product_ID"]) &&
            //                                          _M_Locator_ID == Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Locator_ID"]) &&
            //                                          _M_AttributeSetInstance_ID == Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_AttributeSetInstance_ID"]))
            //                                {
            //                                    transaction = new VAdvantage.Model.MTransaction(GetCtx(), Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Transaction_ID"]), null);
            //                                    transaction.SetCurrentQty(Decimal.Add(_currentQty, Util.GetValueOfDecimal(dsTransaction.Tables[0].Rows[i]["MovementQty"])));
            //                                    if (!transaction.Save())
            //                                    {
            //                                        log.Info("Current Quantity Not Updated at Transaction Tab <===> " + Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Transaction_ID"]));
            //                                    }
            //                                    else
            //                                    {
            //                                        Commit();
            //                                        _currentQty = Decimal.Add(_currentQty, Util.GetValueOfDecimal(dsTransaction.Tables[0].Rows[i]["MovementQty"]));
            //                                    }
            //                                }
            //                                //when Attribute not matched
            //                                else if (_M_Product_ID == Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Product_ID"]) &&
            //                                          _M_Locator_ID == Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Locator_ID"]) &&
            //                                          _M_AttributeSetInstance_ID != Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_AttributeSetInstance_ID"]))
            //                                {
            //                                    _currentQty = Util.GetValueOfDecimal(dsTransaction.Tables[0].Rows[i]["CurrentQty"]);
            //                                    _M_Product_ID = Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Product_ID"]);
            //                                    _M_Locator_ID = Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Locator_ID"]);
            //                                    _M_AttributeSetInstance_ID = Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_AttributeSetInstance_ID"]);
            //                                    continue;
            //                                }
            //                                // when Locator not Matched
            //                                else if (_M_Product_ID == Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Product_ID"]) &&
            //                                         _M_Locator_ID != Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Locator_ID"]) &&
            //                                         _M_AttributeSetInstance_ID == Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_AttributeSetInstance_ID"]))
            //                                {
            //                                    _currentQty = Util.GetValueOfDecimal(dsTransaction.Tables[0].Rows[i]["CurrentQty"]);
            //                                    _M_Product_ID = Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Product_ID"]);
            //                                    _M_Locator_ID = Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Locator_ID"]);
            //                                    _M_AttributeSetInstance_ID = Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_AttributeSetInstance_ID"]);
            //                                    continue;
            //                                }
            //                                //when Product , Locator n Attribute both not matched (means First Record)
            //                                else if (_M_Product_ID != Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Product_ID"]) &&
            //                                        _M_Locator_ID != Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Locator_ID"]) &&
            //                                        _M_AttributeSetInstance_ID != Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_AttributeSetInstance_ID"]))
            //                                {
            //                                    _currentQty = Util.GetValueOfDecimal(dsTransaction.Tables[0].Rows[i]["CurrentQty"]);
            //                                    _M_Product_ID = Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Product_ID"]);
            //                                    _M_Locator_ID = Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Locator_ID"]);
            //                                    _M_AttributeSetInstance_ID = Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_AttributeSetInstance_ID"]);
            //                                    continue;
            //                                }
            //                                //when Locator n Attribute both not matched
            //                                else if (_M_Product_ID == Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Product_ID"]) &&
            //                                   _M_Locator_ID != Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Locator_ID"]) &&
            //                                   _M_AttributeSetInstance_ID != Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_AttributeSetInstance_ID"]))
            //                                {
            //                                    _currentQty = Util.GetValueOfDecimal(dsTransaction.Tables[0].Rows[i]["CurrentQty"]);
            //                                    _M_Product_ID = Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Product_ID"]);
            //                                    _M_Locator_ID = Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Locator_ID"]);
            //                                    _M_AttributeSetInstance_ID = Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_AttributeSetInstance_ID"]);
            //                                    continue;
            //                                }
            //                                // when product and Locator not Matched
            //                                else if (_M_Product_ID != Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Product_ID"]) &&
            //                                        _M_Locator_ID != Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Locator_ID"]) &&
            //                                        _M_AttributeSetInstance_ID == Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_AttributeSetInstance_ID"]))
            //                                {
            //                                    _currentQty = Util.GetValueOfDecimal(dsTransaction.Tables[0].Rows[i]["CurrentQty"]);
            //                                    _M_Product_ID = Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Product_ID"]);
            //                                    _M_Locator_ID = Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Locator_ID"]);
            //                                    _M_AttributeSetInstance_ID = Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_AttributeSetInstance_ID"]);
            //                                    continue;
            //                                }
            //                                // when product and Attribute not Matched
            //                                else if (_M_Product_ID != Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Product_ID"]) &&
            //                                        _M_Locator_ID == Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Locator_ID"]) &&
            //                                        _M_AttributeSetInstance_ID != Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_AttributeSetInstance_ID"]))
            //                                {
            //                                    _currentQty = Util.GetValueOfDecimal(dsTransaction.Tables[0].Rows[i]["CurrentQty"]);
            //                                    _M_Product_ID = Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Product_ID"]);
            //                                    _M_Locator_ID = Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_Locator_ID"]);
            //                                    _M_AttributeSetInstance_ID = Util.GetValueOfInt(dsTransaction.Tables[0].Rows[i]["M_AttributeSetInstance_ID"]);
            //                                    continue;
            //                                }
            //                            }
            //                        }
            //                    }
            //                }
            //                dsTransaction.Dispose();
            //            }
            //            catch
            //            {
            //                if (dsTransaction != null)
            //                {
            //                    dsTransaction.Dispose();
            //                }
            //                return Msg.GetMsg(GetCtx(), "NotCompleted");
            //            }
            //            finally
            //            {
            //                if (dsTransaction != null)
            //                {
            //                    dsTransaction.Dispose();
            //                }
            //            }
            //            return Msg.GetMsg(GetCtx(), "SucessfullyCompleted");
            #endregion
        }
コード例 #7
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(" - 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(" - 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
コード例 #8
0
 public void PassingTest()
 {
     Assert.Equal(4, Decimal.Add(2, 2));
 }
コード例 #9
0
 /// <summary>
 /// Is Source Segment balanced.
 /// Implemented only for Org
 /// Other sensible candidates are Project, User1/2
 /// </summary>
 /// <param name="segmentType"></param>
 /// <returns>true if segments are balanced</returns>
 public bool IsSegmentBalanced(String segmentType)
 {
     if (segmentType.Equals(X_C_AcctSchema_Element.ELEMENTTYPE_Organization))
     {
         Dictionary <int, Decimal?> map = new Dictionary <int, Decimal?>();
         //  Add up values by key
         for (int i = 0; i < _lines.Count; i++)
         {
             //FactLine line = (FactLine)_lines[i];
             //int key = Utility.Util.GetValueOfInt(line.GetAD_Org_ID());
             //Decimal bal = line.GetSourceBalance();
             //Decimal oldBal;
             //if (map.TryGetValue(key, out oldBal))
             //{
             //    oldBal = map[key];
             //    bal = Decimal.Add(bal, oldBal);
             //    map[key] = bal;//put(key, bal);
             //}
             //map.Add(key, bal);//put(key, bal);
             try
             {
                 FactLine line   = (FactLine)_lines[i];
                 int      key    = Utility.Util.GetValueOfInt(line.GetAD_Org_ID());
                 Decimal? bal    = line.GetSourceBalance();
                 Decimal? oldBal = null;
                 if (map.TryGetValue(key, out oldBal))
                 {
                     oldBal = map[key];
                 }
                 if (oldBal != null)
                 {
                     bal = Decimal.Add(bal.Value, oldBal.Value);
                 }
                 if (!map.Keys.Contains(key))
                 {
                     map.Add(key, bal);
                 }
                 else
                 {
                     map[key] = bal;
                 }
             }
             catch { }
         }
         //  check if all keys are zero
         //Iterator values = map.values().iterator();
         IEnumerator values = map.Values.GetEnumerator();
         while (values.MoveNext())
         {
             Decimal bal = (Decimal)values.Current;
             if (Env.Signum(bal) != 0)
             {
                 map.Clear();
                 log.Warning("(" + segmentType + ") NO - " + ToString() + ", Balance=" + bal);
                 return(false);
             }
         }
         map.Clear();
         log.Finer("(" + segmentType + ") - " + ToString());
         return(true);
     }
     log.Finer("(" + segmentType + ") (not checked) - " + ToString());
     return(true);
 }
コード例 #10
0
 public void AddPenny()
 {
     MyFortune = Decimal.Add(MyFortune, .01m);
 }
コード例 #11
0
 /// <summary>
 /// Add
 /// </summary>
 /// <param name="dr"></param>
 /// <param name="cr"></param>
 public void Add(Decimal dr, Decimal cr)
 {
     DR = Decimal.Add(DR, dr);
     CR = Decimal.Add(CR, cr);
 }
コード例 #12
0
        /**
         *  Before Save
         *	@param newRecord new
         *	@return true
         */
        protected override bool BeforeSave(bool newRecord)
        {
            //	Check Storage
            if (!newRecord &&                                      //
                ((Is_ValueChanged("IsActive") && !IsActive()) ||   //	now not active
                 (Is_ValueChanged("IsStocked") && !IsStocked()) || //	now not stocked
                 (Is_ValueChanged("ProductType") &&                //	from Item
                  PRODUCTTYPE_Item.Equals(Get_ValueOld("ProductType")))))
            {
                MStorage[] storages = MStorage.GetOfProduct(GetCtx(), Get_ID(), Get_TrxName());
                Decimal    OnHand   = Env.ZERO;
                Decimal    Ordered  = Env.ZERO;
                Decimal    Reserved = Env.ZERO;
                for (int i = 0; i < storages.Length; i++)
                {
                    OnHand   = Decimal.Add(OnHand, (storages[i].GetQtyOnHand()));
                    Ordered  = Decimal.Add(OnHand, (storages[i].GetQtyOrdered()));
                    Reserved = Decimal.Add(OnHand, (storages[i].GetQtyReserved()));
                }
                String errMsg = "";
                if (Env.Signum(OnHand) != 0)
                {
                    errMsg = "@QtyOnHand@ = " + OnHand;
                }
                if (Env.Signum(Ordered) != 0)
                {
                    errMsg += " - @QtyOrdered@ = " + Ordered;
                }
                if (Env.Signum(Reserved) != 0)
                {
                    errMsg += " - @QtyReserved@" + Reserved;
                }
                if (errMsg.Length > 0)
                {
                    log.SaveError("Error", Msg.ParseTranslation(GetCtx(), errMsg));
                    return(false);
                }
            }   //	storage

            //	Reset Stocked if not Item
            if (IsStocked() && !PRODUCTTYPE_Item.Equals(GetProductType()))
            {
                SetIsStocked(false);
            }

            //	UOM reset
            if (_precision != null && Is_ValueChanged("C_UOM_ID"))
            {
                _precision = null;
            }
            if (Util.GetValueOfInt(Env.GetCtx().GetContext("#AD_User_ID")) != 100)
            {
                if (Is_ValueChanged("C_UOM_ID") || Is_ValueChanged("M_AttributeSet_ID"))
                {
                    string uqry = "SELECT SUM(cc) as count FROM  (SELECT COUNT(*) AS cc FROM M_MovementLine WHERE M_Product_ID = " + GetM_Product_ID() + @"  UNION
                SELECT COUNT(*) AS cc FROM M_InventoryLine WHERE M_Product_ID = " + GetM_Product_ID() + " UNION SELECT COUNT(*) AS cc FROM C_OrderLine WHERE M_Product_ID = " + GetM_Product_ID() +
                                  " UNION  SELECT COUNT(*) AS cc FROM M_InOutLine WHERE M_Product_ID = " + GetM_Product_ID() + ")";
                    int no = Util.GetValueOfInt(DB.ExecuteScalar(uqry));
                    if (no == 0 || IsBOM())
                    {
                        uqry = "SELECT count(*) FROM M_ProductionPlan WHERE M_Product_ID = " + GetM_Product_ID();
                        no   = Util.GetValueOfInt(DB.ExecuteScalar(uqry));
                    }
                    if (no > 0)
                    {
                        log.SaveError("Error", Msg.ParseTranslation(GetCtx(), "Could not Save Record. Transactions available in System."));
                        return(false);
                    }
                }
            }
            if (newRecord)
            {
                string sql     = "SELECT UPCUNIQUE('p','" + GetUPC() + "') as productID FROM Dual";
                int    manu_ID = Util.GetValueOfInt(DB.ExecuteScalar(sql, null, null));
                if (manu_ID > 0)
                {
                    _log.SaveError("UPC is Unique", "");
                    return(false);
                }
            }
            else
            {
                if (!String.IsNullOrEmpty(GetUPC()) &&
                    Util.GetValueOfString(Get_ValueOld("UPC")) != GetUPC())
                {
                    string sql     = "SELECT UPCUNIQUE('p','" + GetUPC() + "') as productID FROM Dual";
                    int    manu_ID = Util.GetValueOfInt(DB.ExecuteScalar(sql, null, null));
                    //if (manu_ID != 0 && manu_ID != GetM_Product_ID())
                    if (manu_ID > 0)
                    {
                        _log.SaveError("UPC is Unique", "");
                        return(false);
                    }
                }
            }
            return(true);
        }
コード例 #13
0
        }       //	rejectIt

        /// <summary>
        /// Complete Document
        /// </summary>
        /// <returns>new status (Complete, In Progress, Invalid, Waiting ..)</returns>
        public String CompleteIt()
        {
            log.Info("completeIt - " + ToString());
            //	Re-Check
            if (!m_justPrepared)
            {
                String status = PrepareIt();
                if (!DocActionVariables.STATUS_INPROGRESS.Equals(status))
                {
                    return(status);
                }
            }
            //	Implicit Approval
            ApproveIt();

            //	Add up Amounts & complete them
            MJournal[] journals = GetJournals(true);
            Decimal?   TotalDr  = Env.ZERO;
            Decimal?   TotalCr  = Env.ZERO;

            for (int i = 0; i < journals.Length; i++)
            {
                MJournal journal = journals[i];
                if (!journal.IsActive())
                {
                    journal.SetProcessed(true);
                    journal.SetDocStatus(DOCSTATUS_Voided);
                    journal.SetDocAction(DOCACTION_None);
                    journal.Save();
                    continue;
                }
                //	Complete if not closed
                if (DOCSTATUS_Closed.Equals(journal.GetDocStatus()) ||
                    DOCSTATUS_Voided.Equals(journal.GetDocStatus()) ||
                    DOCSTATUS_Reversed.Equals(journal.GetDocStatus()) ||
                    DOCSTATUS_Completed.Equals(journal.GetDocStatus()))
                {
                    ;
                }
                else
                {
                    String status = journal.CompleteIt();
                    if (!DocActionVariables.STATUS_COMPLETED.Equals(status))
                    {
                        journal.SetDocStatus(status);
                        journal.Save();
                        m_processMsg = journal.GetProcessMsg();
                        return(status);
                    }
                    journal.SetDocStatus(DOCSTATUS_Completed);
                    journal.Save();
                }
                //
                //TotalDr = TotalDr.add(journal.getTotalDr());
                TotalDr = Decimal.Add(TotalDr.Value, journal.GetTotalDr());
                TotalCr = Decimal.Add(TotalCr.Value, journal.GetTotalCr());
            }
            SetTotalDr(TotalDr.Value);
            SetTotalCr(TotalCr.Value);
            //	User Validation
            String valid = ModelValidationEngine.Get().FireDocValidate(this, ModalValidatorVariables.DOCTIMING_AFTER_COMPLETE);

            if (valid != null)
            {
                m_processMsg = valid;
                return(DocActionVariables.STATUS_INVALID);
            }
            //
            SetProcessed(true);
            SetDocAction(DOCACTION_Close);
            return(DocActionVariables.STATUS_COMPLETED);
        }       //	completeIt
コード例 #14
0
        protected override String DoIt()
        {
            int    C_Contract_ID = 0;
            String Sql           = "Select C_OrderLine_ID from C_OrderLine where C_Order_ID=" + orderID;

            dr = DB.ExecuteReader(Sql);
            VAdvantage.Model.X_C_Order order = new VAdvantage.Model.X_C_Order(GetCtx(), orderID, null);
            string DocStatus = order.GetDocStatus();

            if (DocStatus != "CO")
            {
                return(Msg.GetMsg(GetCtx(), "FirstCompleteOrder"));
            }

            while (dr.Read())
            {
                VAdvantage.Model.X_C_OrderLine line = new VAdvantage.Model.X_C_OrderLine(GetCtx(), Util.GetValueOfInt(dr[0]), null);
                if (line.IsContract() && line.GetC_Contract_ID() == 0)
                {
                    VAdvantage.Model.X_C_Contract    contact = new VAdvantage.Model.X_C_Contract(GetCtx(), 0, null);
                    VAdvantage.Model.MProductPricing pp      = new VAdvantage.Model.MProductPricing(GetCtx().GetAD_Client_ID(), GetCtx().GetAD_Org_ID(),
                                                                                                    line.GetM_Product_ID(), order.GetC_BPartner_ID(), line.GetQtyOrdered(), true);
                    int M_PriceList_ID = Util.GetValueOfInt(order.GetM_PriceList_ID());
                    pp.SetM_PriceList_ID(M_PriceList_ID);

                    string sql = "SELECT pl.IsTaxIncluded,pl.EnforcePriceLimit,pl.C_Currency_ID,c.StdPrecision,"
                                 + "plv.M_PriceList_Version_ID,plv.ValidFrom "
                                 + "FROM M_PriceList pl,C_Currency c,M_PriceList_Version plv "
                                 + "WHERE pl.C_Currency_ID=c.C_Currency_ID"
                                 + " AND pl.M_PriceList_ID=plv.M_PriceList_ID"
                                 + " AND pl.M_PriceList_ID=" + M_PriceList_ID                                   //	1
                                 + "ORDER BY plv.ValidFrom DESC";

                    int     M_PriceList_Version_ID = 0;
                    int     C_Currency_ID          = 0;
                    DataSet ds = DB.ExecuteDataset(sql, null);
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        DataRow dr1 = ds.Tables[0].Rows[i];
                        //	Tax Included
                        //  bool isTaxIncluded = Util.GetValueOfBool(ds.Tables[0].Rows[i]["IsTaxIncluded"]);
                        //	Price Limit Enforce
                        //  bool isTaxIncluded = Util.GetValueOfBool(ds.Tables[0].Rows[i]["IsTaxIncluded"]);
                        //	Currency
                        //  int ii = Util.GetValueOfInt(dr[2].ToString());
                        C_Currency_ID = Util.GetValueOfInt(ds.Tables[0].Rows[i]["C_Currency_ID"]);
                        // int prislst = Util.GetValueOfInt(dr[4].ToString());
                        //	PriceList Version
                        M_PriceList_Version_ID = Util.GetValueOfInt(ds.Tables[0].Rows[i]["M_PriceList_Version_ID"]);
                    }
                    //int M_PriceList_Version_ID = GetCtx().GetContextAsInt(WindowNo, "M_PriceList_Version_ID");
                    pp.SetM_PriceList_Version_ID(M_PriceList_Version_ID);


                    contact.SetDescription(order.GetDescription());
                    contact.SetC_Order_ID(order.GetC_Order_ID());
                    contact.SetC_OrderLine_ID(line.GetC_OrderLine_ID());
                    contact.SetStartDate(line.GetStartDate());
                    contact.SetEndDate(line.GetEndDate());

                    contact.SetC_BPartner_ID(order.GetC_BPartner_ID());
                    contact.SetBill_Location_ID(order.GetBill_Location_ID());
                    contact.SetBill_User_ID(order.GetBill_User_ID());
                    contact.SetSalesRep_ID(order.GetSalesRep_ID());

                    contact.SetC_Currency_ID(line.GetC_Currency_ID());
                    contact.SetC_ConversionType_ID(order.GetC_ConversionType_ID());
                    contact.SetC_PaymentTerm_ID(order.GetC_PaymentTerm_ID());
                    contact.SetM_PriceList_ID(order.GetM_PriceList_ID());
                    contact.SetC_Frequency_ID(line.GetC_Frequency_ID());

                    contact.SetPriceList(pp.GetPriceList());
                    contact.SetPriceActual(pp.GetPriceStd());
                    contact.SetPriceEntered(pp.GetPriceStd());
                    contact.SetQtyEntered(line.GetQtyPerCycle());

                    Decimal discount = Decimal.Round(Decimal.Divide(Decimal.Multiply(Decimal.Subtract(pp.GetPriceList(), pp.GetPriceStd()), new Decimal(100)), pp.GetPriceList()), 2);
                    contact.SetDiscount(discount);
                    //contact.SetGrandTotal(
                    // invoice Count Start

                    //DateTime SDate = (DateTime)(line.GetStartDate());
                    //DateTime Edate = (DateTime)(line.GetEndDate());
                    //int frequency = Util.GetValueOfInt(line.GetC_Frequency_ID());
                    //string PSql = "Select NoOfDays from C_Frequency where C_Frequency_ID=" + frequency;
                    //int days = Util.GetValueOfInt(DB.ExecuteScalar(PSql, null, null));
                    //int totaldays = (Edate - SDate).Days;
                    //int count = totaldays / days;

                    contact.SetTotalInvoice(line.GetNoofCycle());

                    //invoice Count end
                    contact.SetC_Project_ID(order.GetC_Project_ID());
                    // contact.SetPriceList(line.GetPriceList());
                    //contact.SetPriceActual(line.GetPriceActual());
                    contact.SetC_UOM_ID(line.GetC_UOM_ID());
                    contact.SetM_Product_ID(line.GetM_Product_ID());
                    // contact.SetPriceEntered(line.GetPriceEntered());
                    //contact.SetQtyEntered(line.GetQtyEntered());
                    // contact.SetDiscount(line.GetDiscount());
                    contact.SetC_Tax_ID(line.GetC_Tax_ID());
                    contact.SetC_Campaign_ID(order.GetC_Campaign_ID());

                    sql = "select rate from c_tax where c_tax_id = " + line.GetC_Tax_ID();
                    Decimal?rate = Util.GetNullableDecimal(DB.ExecuteScalar(sql, null, null));

                    Decimal?amt = Decimal.Multiply(pp.GetPriceStd(), (Decimal.Divide(rate.Value, 100)));


                    amt = Decimal.Round(amt.Value, 2, MidpointRounding.AwayFromZero);

                    Decimal?taxAmt = Decimal.Multiply(amt.Value, line.GetQtyPerCycle());

                    contact.SetTaxAmt(taxAmt);
                    contact.SetGrandTotal(Decimal.Add(Decimal.Multiply(line.GetQtyPerCycle(), pp.GetPriceStd()), taxAmt.Value));
                    contact.SetLineNetAmt(Decimal.Multiply(line.GetQtyPerCycle(), pp.GetPriceStd()));

                    contact.SetDocStatus("DR");
                    contact.SetRenewContract("N");
                    if (contact.Save())
                    {
                        line.SetC_Contract_ID(contact.GetC_Contract_ID());
                        if (line.Save())
                        {
                        }
                    }
                    C_Contract_ID = contact.GetC_Contract_ID();
                }
            }
            dr.Close();

            order.SetCreateServiceContract("Y");
            if (!order.Save())
            {
            }


            return(Msg.GetMsg(GetCtx(), "ServiceContractGenerationDone"));
        }
コード例 #15
0
        /// <summary>
        /// Process Allocation (does not update line).
        /// - Update and Link Invoice/Payment/Cash
        /// </summary>
        /// <param name="reverse">reverse if true allocation is reversed</param>
        /// <returns>C_BPartner_ID</returns>
        public int ProcessIt(bool reverse)
        {
            log.Fine("Reverse=" + reverse + " - " + ToString());
            int C_Invoice_ID = GetC_Invoice_ID();
            MInvoicePaySchedule invoiceSchedule = null;
            MPayment            payment         = null;
            MCashLine           cashLine        = null;
            MInvoice            invoice         = GetInvoice();

            if (invoice != null &&
                GetC_BPartner_ID() != invoice.GetC_BPartner_ID())
            {
                SetC_BPartner_ID(invoice.GetC_BPartner_ID());
            }
            //
            int C_Payment_ID  = GetC_Payment_ID();
            int C_CashLine_ID = GetC_CashLine_ID();

            //	Update Payment
            if (C_Payment_ID != 0)
            {
                payment = new MPayment(GetCtx(), C_Payment_ID, Get_TrxName());
                if (GetC_BPartner_ID() != payment.GetC_BPartner_ID())
                {
                    log.Warning("C_BPartner_ID different - Invoice=" + GetC_BPartner_ID() + " - Payment=" + payment.GetC_BPartner_ID());
                }
                if (reverse)
                {
                    if (!payment.IsCashTrx())
                    {
                        payment.SetIsAllocated(false);
                        payment.Save();
                    }
                }
                else
                {
                    if (payment.TestAllocation())
                    {
                        payment.Save();
                    }
                }
            }

            //	Payment - Invoice
            if (C_Payment_ID != 0 && invoice != null)
            {
                //	Link to Invoice
                if (reverse)
                {
                    invoice.SetC_Payment_ID(0);
                    log.Fine("C_Payment_ID=" + C_Payment_ID
                             + " Unlinked from C_Invoice_ID=" + C_Invoice_ID);
                }
                else if (invoice.IsPaid())
                {
                    invoice.SetC_Payment_ID(C_Payment_ID);
                    log.Fine("C_Payment_ID=" + C_Payment_ID
                             + " Linked to C_Invoice_ID=" + C_Invoice_ID);
                }

                //	Link to Order
                String update = "UPDATE C_Order o "
                                + "SET C_Payment_ID="
                                + (reverse ? "NULL " : "(SELECT C_Payment_ID FROM C_Invoice WHERE C_Invoice_ID=" + C_Invoice_ID + ") ")
                                + "WHERE EXISTS (SELECT * FROM C_Invoice i "
                                + "WHERE o.C_Order_ID=i.C_Order_ID AND i.C_Invoice_ID=" + C_Invoice_ID + ")";
                if (DataBase.DB.ExecuteQuery(update, null, Get_TrxName()) > 0)
                {
                    log.Fine("C_Payment_ID=" + C_Payment_ID
                             + (reverse ? " UnLinked from" : " Linked to")
                             + " order of C_Invoice_ID=" + C_Invoice_ID);
                }
            }

            //	Cash - Invoice
            if (C_CashLine_ID != 0 && invoice != null)
            {
                //	Link to Invoice
                if (reverse)
                {
                    invoice.SetC_CashLine_ID(0);
                    log.Fine("C_CashLine_ID=" + C_CashLine_ID
                             + " Unlinked from C_Invoice_ID=" + C_Invoice_ID);
                    // Set isallocated false on cashline while allocation gets deallocated assigned by Mukesh sir on 27/12/2017
                    MCashLine cashline = new MCashLine(GetCtx(), GetC_CashLine_ID(), Get_TrxName());
                    cashline.SetIsAllocated(false);
                    cashline.Save();
                }
                else
                {
                    invoice.SetC_CashLine_ID(C_CashLine_ID);
                    log.Fine("C_CashLine_ID=" + C_CashLine_ID
                             + " Linked to C_Invoice_ID=" + C_Invoice_ID);
                }

                //	Link to Order
                String update = "UPDATE C_Order o "
                                + "SET C_CashLine_ID="
                                + (reverse ? "NULL " : "(SELECT C_CashLine_ID FROM C_Invoice WHERE C_Invoice_ID=" + C_Invoice_ID + ") ")
                                + "WHERE EXISTS (SELECT * FROM C_Invoice i "
                                + "WHERE o.C_Order_ID=i.C_Order_ID AND i.C_Invoice_ID=" + C_Invoice_ID + ")";
                if (DataBase.DB.ExecuteQuery(update, null, Get_TrxName()) > 0)
                {
                    log.Fine("C_CashLine_ID=" + C_CashLine_ID
                             + (reverse ? " UnLinked from" : " Linked to")
                             + " order of C_Invoice_ID=" + C_Invoice_ID);
                }
            }

            // Added by Bharat- Update Discrepancy amount on Invoice.

            if (C_Payment_ID == 0 && C_CashLine_ID == 0 && invoice != null)
            {
                if (invoice.Get_ColumnIndex("DiscrepancyAmt") >= 0)
                {
                    decimal desAmt     = invoice.GetDiscrepancyAmt();
                    decimal desAjusted = invoice.GetDiscrepancyAdjusted();
                    decimal allocAmt   = Math.Abs(GetAmount()); //	absolute
                    if (reverse)
                    {
                        if (allocAmt > desAjusted)
                        {
                            desAmt     = Decimal.Add(desAjusted, desAmt);
                            desAjusted = 0;
                        }
                        else
                        {
                            desAmt     = Decimal.Add(desAmt, allocAmt);
                            desAjusted = Decimal.Subtract(desAjusted, allocAmt);
                        }

                        invoice.SetDiscrepancyAmt(desAmt);
                        invoice.SetDiscrepancyAdjusted(desAjusted);
                        if (desAmt > 0)
                        {
                            invoice.SetIsInDispute(true);
                        }
                    }
                    else
                    {
                        if (allocAmt > desAmt)
                        {
                            desAjusted = Decimal.Add(desAjusted, desAmt);
                            desAmt     = 0;
                        }
                        else
                        {
                            desAjusted = Decimal.Add(desAjusted, allocAmt);
                            desAmt     = Decimal.Subtract(desAmt, allocAmt);
                        }
                        invoice.SetDiscrepancyAmt(desAmt);
                        invoice.SetDiscrepancyAdjusted(desAjusted);
                        if (desAmt == 0)
                        {
                            invoice.SetIsInDispute(false);
                        }
                    }
                    if (!invoice.Save())
                    {
                        log.Log(Level.SEVERE, "Invoice not updated - " + invoice);
                    }
                }
            }

            //	Update Balance / Credit used - Counterpart of MInvoice.completeIt
            if (invoice != null)
            {
                if (invoice.TestAllocation() && !invoice.Save())
                {
                    log.Log(Level.SEVERE, "Invoice not updated - " + invoice);
                }
                else if (reverse)
                {
                    // added by Amit
                    // if payment Management module downloaded and Invoice Schedule id available on Allocation then mark ispaid on schedule as false
                    if (Env.IsModuleInstalled("VA009_"))
                    {
                        MAllocationHdr allocHdr = new MAllocationHdr(GetCtx(), GetC_AllocationHdr_ID(), Get_Trx());
                        decimal        payAmt   = 0;
                        MDocType       doctype  = null;
                        MCurrency      currency = new MCurrency(GetCtx(), invoice.GetC_Currency_ID(), null);
                        if (GetC_InvoicePaySchedule_ID() != 0 && !invoice.IsPaid())
                        {
                            invoiceSchedule = new MInvoicePaySchedule(GetCtx(), GetC_InvoicePaySchedule_ID(), Get_TrxName());
                            invoiceSchedule.SetVA009_IsPaid(false);
                            // when we update schedule paid as False, then update payment method and related fields on schedule as on Invoice Header
                            if (reverse)
                            {
                                invoiceSchedule.SetVA009_PaymentMethod_ID(invoice.GetVA009_PaymentMethod_ID());
                                DataSet dsPaymentMethod = DB.ExecuteDataset(@"SELECT VA009_PaymentMode, VA009_PaymentType, VA009_PaymentTrigger FROM VA009_PaymentMethod
                                          WHERE IsActive = 'Y' AND  VA009_PaymentMethod_ID = " + invoice.GetVA009_PaymentMethod_ID(), null, Get_Trx());
                                if (dsPaymentMethod != null && dsPaymentMethod.Tables.Count > 0 && dsPaymentMethod.Tables[0].Rows.Count > 0)
                                {
                                    if (!String.IsNullOrEmpty(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentMode"])))
                                    {
                                        invoiceSchedule.SetVA009_PaymentMode(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentMode"]));
                                    }
                                    if (!String.IsNullOrEmpty(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentType"])))
                                    {
                                        invoiceSchedule.SetVA009_PaymentType(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentType"]));
                                    }
                                    invoiceSchedule.SetVA009_PaymentTrigger(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentTrigger"]));
                                }
                                dsPaymentMethod = null;
                            }
                            if (reverse && payment != null)
                            {
                                #region Handle for Payment & Invoice Allocation
                                doctype = new MDocType(GetCtx(), invoice.GetC_DocType_ID(), null);

                                // convert (payment amount / Amount from View Allocation) to invoice currency amount then subtract Paid invoice amount to calculated amount
                                if (doctype.GetDocBaseType() == "ARC" || doctype.GetDocBaseType() == "APC")
                                {
                                    if (payment.GetC_Invoice_ID() != 0)
                                    {
                                        // when payment created with invoice refernce direct
                                        // convert payment amount in invoice amt with payment date and payment conversion type
                                        payAmt = MConversionRate.Convert(GetCtx(), Decimal.Negate(Decimal.Add(Decimal.Add((payment.GetPayAmt() +
                                                                                                                           (payment.Get_ColumnIndex("BackupWithholdingAmount") >= 0 ? (payment.GetWithholdingAmt() + payment.GetBackupWithholdingAmount()) : 0)), payment.GetDiscountAmt()),
                                                                                                              payment.GetWriteOffAmt())), payment.GetC_Currency_ID(), invoice.GetC_Currency_ID(), payment.GetDateAcct(),
                                                                         payment.GetC_ConversionType_ID(), GetAD_Client_ID(), GetAD_Org_ID());
                                    }
                                    else
                                    {
                                        // when payment created with Payment Allocate entry OR
                                        // when we match payment with invoice through Payment Allocation form
                                        // convert payment amount in invoice amt with view allocation date
                                        payAmt = MConversionRate.Convert(GetCtx(), Decimal.Negate(Decimal.Add(Decimal.Add(GetAmount(), GetDiscountAmt()),
                                                                                                              GetWriteOffAmt())), allocHdr.GetC_Currency_ID(), invoice.GetC_Currency_ID(), allocHdr.GetDateAcct(),
                                                                         invoice.GetC_ConversionType_ID(), GetAD_Client_ID(), GetAD_Org_ID());
                                        if (doctype.GetDocBaseType() == "APC")
                                        {
                                            payAmt = Decimal.Negate(payAmt);
                                        }
                                    }
                                }
                                else
                                {
                                    if (payment.GetC_Invoice_ID() != 0)
                                    {
                                        // when we create payment with invoice reference direct
                                        // convert payment amount in invoice amt with payment date and payment conversion type
                                        payAmt = MConversionRate.Convert(GetCtx(), Decimal.Add(Decimal.Add((payment.GetPayAmt() +
                                                                                                            (payment.Get_ColumnIndex("BackupWithholdingAmount") >= 0 ? (payment.GetWithholdingAmt() + payment.GetBackupWithholdingAmount()) : 0)), payment.GetDiscountAmt()),
                                                                                               payment.GetWriteOffAmt()), payment.GetC_Currency_ID(), invoice.GetC_Currency_ID(), payment.GetDateAcct(),
                                                                         payment.GetC_ConversionType_ID(), GetAD_Client_ID(), GetAD_Org_ID());
                                    }
                                    else
                                    {
                                        // when payment created with Payment Allocate entry Or
                                        // when we match payment with invoice through Payment Allocation form
                                        // convert payment amount in invoice amt with view allocation date
                                        payAmt = MConversionRate.Convert(GetCtx(), Decimal.Add(Decimal.Add(GetAmount(), GetDiscountAmt()), GetWriteOffAmt()),
                                                                         allocHdr.GetC_Currency_ID(), invoice.GetC_Currency_ID(), allocHdr.GetDateAcct(), invoice.GetC_ConversionType_ID(),
                                                                         GetAD_Client_ID(), GetAD_Org_ID());
                                        if (doctype.GetDocBaseType() == "API")
                                        {
                                            payAmt = Decimal.Negate(payAmt);
                                        }
                                    }
                                }
                                invoiceSchedule.SetVA009_PaidAmntInvce(Decimal.Round(Decimal.Subtract(invoiceSchedule.GetVA009_PaidAmntInvce(), payAmt),
                                                                                     currency.GetStdPrecision()));

                                // during reversal, if Invoice paid amount <> 0 then reduce that amount from next schedule
                                try
                                {
                                    if (invoiceSchedule.GetVA009_PaidAmntInvce() != 0)
                                    {
                                        int no = Util.GetValueOfInt(DB.ExecuteQuery(@"UPDATE C_InvoicePaySchedule 
                                                                 SET VA009_PaidAmntInvce =   NVL(VA009_PaidAmntInvce , 0) + " + Decimal.Round(invoiceSchedule.GetVA009_PaidAmntInvce(), currency.GetStdPrecision()) +
                                                                                    @" , VA009_PaidAmnt =  NVL(VA009_PaidAmnt , 0) + " + Decimal.Round(MConversionRate.ConvertBase(GetCtx(), invoiceSchedule.GetVA009_PaidAmntInvce(), invoice.GetC_Currency_ID(), invoice.GetDateAcct(), invoice.GetC_ConversionType_ID(), GetAD_Client_ID(), GetAD_Org_ID()), currency.GetStdPrecision()) +
                                                                                    @" WHERE C_InvoicePaySchedule_ID = ( SELECT MIN(C_InvoicePaySchedule_ID) FROM C_InvoicePaySchedule WHERE IsActive = 'Y'
                                                                 AND VA009_IsPaid = 'N' AND C_Invoice_ID = " + invoice.GetC_Invoice_ID() +
                                                                                    @" AND C_InvoicePaySchedule_ID <> " + GetC_InvoicePaySchedule_ID() + " ) ", null, Get_Trx()));

                                        // set paid invoice amount = 0, no > 0 bcz this is not last schedule
                                        if (no > 0)
                                        {
                                            invoiceSchedule.SetVA009_PaidAmntInvce(0);
                                        }
                                    }
                                }
                                catch { }

                                // convert invoice paid amount to base currency amount
                                invoiceSchedule.SetVA009_PaidAmnt(Decimal.Round(MConversionRate.ConvertBase(GetCtx(), invoiceSchedule.GetVA009_PaidAmntInvce(),
                                                                                                            invoice.GetC_Currency_ID(), invoice.GetDateAcct(), invoice.GetC_ConversionType_ID(), GetAD_Client_ID(), GetAD_Org_ID()),
                                                                                currency.GetStdPrecision()));

                                // set Currency Variance amount as 0, when we reverse paymnet/ cash journalor allocation against this schedule
                                invoiceSchedule.SetVA009_Variance(0);

                                // remove linking of Payment from schedule
                                invoiceSchedule.SetC_Payment_ID(0);

                                #endregion
                            }
                            else if (reverse && C_CashLine_ID > 0)
                            {
                                #region Handle fo Cash Journal & Invoice Allocation

                                doctype  = new MDocType(GetCtx(), invoice.GetC_DocType_ID(), null);
                                cashLine = new MCashLine(GetCtx(), C_CashLine_ID, Get_Trx());

                                // convert cash amount to invoice currency amount with allocation date then subtract Paid invoice amount to calculated amount
                                if (doctype.GetDocBaseType() == "ARC" || doctype.GetDocBaseType() == "API")
                                {
                                    payAmt = Decimal.Negate(Decimal.Add(Decimal.Add(GetAmount(), GetDiscountAmt()), GetWriteOffAmt()));
                                    payAmt = MConversionRate.Convert(GetCtx(), payAmt, allocHdr.GetC_Currency_ID(), invoice.GetC_Currency_ID(), allocHdr.GetDateAcct(),
                                                                     invoice.GetC_ConversionType_ID(), GetAD_Client_ID(), GetAD_Org_ID());
                                    invoiceSchedule.SetVA009_PaidAmntInvce(Decimal.Round(Decimal.Subtract(invoiceSchedule.GetVA009_PaidAmntInvce(), payAmt),
                                                                                         currency.GetStdPrecision()));
                                }
                                else
                                {
                                    payAmt = Decimal.Add(Decimal.Add(GetAmount(), GetDiscountAmt()), GetWriteOffAmt());
                                    payAmt = MConversionRate.Convert(GetCtx(), payAmt, allocHdr.GetC_Currency_ID(), invoice.GetC_Currency_ID(), allocHdr.GetDateAcct(),
                                                                     invoice.GetC_ConversionType_ID(), GetAD_Client_ID(), GetAD_Org_ID());
                                    invoiceSchedule.SetVA009_PaidAmntInvce(Decimal.Round(Decimal.Subtract(invoiceSchedule.GetVA009_PaidAmntInvce(), payAmt),
                                                                                         currency.GetStdPrecision()));
                                }

                                // during reversal, if Invoice paid amount <> 0 then reduce that amount from next schedule
                                try
                                {
                                    if (invoiceSchedule.GetVA009_PaidAmntInvce() != 0)
                                    {
                                        int no = Util.GetValueOfInt(DB.ExecuteQuery(@"UPDATE C_InvoicePaySchedule 
                                                                 SET VA009_PaidAmntInvce =   NVL(VA009_PaidAmntInvce , 0) + " + Decimal.Round(invoiceSchedule.GetVA009_PaidAmntInvce(), currency.GetStdPrecision()) +
                                                                                    @" , VA009_PaidAmnt =  NVL(VA009_PaidAmnt , 0) + " + Decimal.Round(MConversionRate.ConvertBase(GetCtx(), invoiceSchedule.GetVA009_PaidAmntInvce(), invoice.GetC_Currency_ID(), invoice.GetDateAcct(), invoice.GetC_ConversionType_ID(), GetAD_Client_ID(), GetAD_Org_ID()), currency.GetStdPrecision()) +
                                                                                    @" WHERE C_InvoicePaySchedule_ID = ( SELECT MIN(C_InvoicePaySchedule_ID) FROM C_InvoicePaySchedule WHERE IsActive = 'Y'
                                                                 AND VA009_IsPaid = 'N' AND C_Invoice_ID = " + invoice.GetC_Invoice_ID() +
                                                                                    @" AND C_InvoicePaySchedule_ID <> " + GetC_InvoicePaySchedule_ID() + " ) ", null, Get_Trx()));

                                        // set paid invoice amount = 0, no > 0 bcz this is not last schedule
                                        if (no > 0)
                                        {
                                            invoiceSchedule.SetVA009_PaidAmntInvce(0);
                                        }
                                    }
                                }
                                catch { }

                                // convert invoice paid amount to base currency amount
                                invoiceSchedule.SetVA009_PaidAmnt(Decimal.Round(MConversionRate.ConvertBase(GetCtx(), invoiceSchedule.GetVA009_PaidAmntInvce(),
                                                                                                            invoice.GetC_Currency_ID(), invoice.GetDateAcct(), invoice.GetC_ConversionType_ID(), GetAD_Client_ID(), GetAD_Org_ID()),
                                                                                currency.GetStdPrecision()));

                                // set Currency Variance amount as 0, when we reverse paymnet/ cash journalor allocation against this schedule
                                invoiceSchedule.SetVA009_Variance(0);

                                // remove linking of cash line from schedule
                                invoiceSchedule.SetC_CashLine_ID(0);

                                #endregion
                            }
                            else
                            {
                                invoiceSchedule.SetVA009_PaidAmntInvce(0);
                                invoiceSchedule.SetVA009_PaidAmnt(0);
                                // set Currency Variance amount as 0, when we reverse paymnet/ cash journalor allocation against this schedule
                                invoiceSchedule.SetVA009_Variance(0);
                            }
                            if (!invoiceSchedule.Save(Get_TrxName()))
                            {
                                log.Log(Level.SEVERE, "Invoice Pay Schedule not updated - " + invoice);
                            }
                        }
                    }
                }
            }

            return(GetC_BPartner_ID());
        }
コード例 #16
0
 public void FailingTest()
 {
     Assert.Equal(5, Decimal.Add(2, 2));
 }
コード例 #17
0
        private bool UpdateCbAndLine()
        {
            // Update Cash Journal
            if (!UpdateHeader())
            {
                log.Warning("Cannot update cash journal.");
                return(false);
            }

            // Update Cashbook and CashbookLine
            MCash     parent   = GetParent();
            MCashBook cashbook = new MCashBook(GetCtx(), parent.GetC_CashBook_ID(), Get_TrxName());

            cashbook.SetRunningBalance(Decimal.Add(Decimal.Subtract(cashbook.GetRunningBalance(), old_ebAmt), new_ebAmt));
            //if (cashbook.GetRunningBalance() == 0)
            //{
            //    cashbook.SetRunningBalance
            //        (Decimal.Add(Decimal.Add(Decimal.Subtract(cashbook.GetRunningBalance(), old_ebAmt), new_ebAmt),cashbook.GetCompletedBalance()));
            //}
            //else
            //{
            //    cashbook.SetRunningBalance(Decimal.Add(Decimal.Subtract(cashbook.GetRunningBalance(), old_ebAmt), new_ebAmt));
            //}

            if (!cashbook.Save())
            {
                log.Warning("Cannot update running balance.");
                return(false);
            }

            DataTable dtCashbookLine;
            int       C_CASHBOOKLINE_ID = 0;

            string sql = "SELECT C_CASHBOOKLINE_ID FROM C_CASHBOOKLINE WHERE C_CASHBOOK_ID="
                         + cashbook.GetC_CashBook_ID() + " AND DATEACCT="
                         + DB.TO_DATE(parent.GetDateAcct()) + " AND AD_ORG_ID=" + GetAD_Org_ID();

            dtCashbookLine = DB.ExecuteDataset(sql, null, null).Tables[0];

            if (dtCashbookLine.Rows.Count > 0)
            {
                C_CASHBOOKLINE_ID = Util.GetValueOfInt(dtCashbookLine.Rows[0]
                                                       .ItemArray[0]);
            }

            MCashbookLine cashbookLine = new MCashbookLine(GetCtx(), C_CASHBOOKLINE_ID, Get_TrxName());

            if (C_CASHBOOKLINE_ID == 0)
            {
                cashbookLine.SetC_CashBook_ID(cashbook.GetC_CashBook_ID());
                cashbookLine.SetAD_Org_ID(GetCtx().GetAD_Org_ID());
                cashbookLine.SetAD_Client_ID(GetCtx().GetAD_Client_ID());
                cashbookLine.SetEndingBalance
                    (Decimal.Add(Decimal.Add(Decimal.Subtract(cashbookLine.GetEndingBalance(), old_ebAmt), new_ebAmt), cashbook.GetCompletedBalance()));
            }
            else
            {
                cashbookLine.SetEndingBalance(Decimal.Add(Decimal.Subtract(cashbookLine.GetEndingBalance(), old_ebAmt), new_ebAmt));
            }
            cashbookLine.SetDateAcct(parent.GetDateAcct());
            cashbookLine.SetStatementDifference(Decimal.Add(Decimal.Subtract(cashbookLine.GetStatementDifference(), old_sdAmt), new_sdAmt));


            if (!cashbookLine.Save())
            {
                log.Warning("Cannot create/update cashbook line.");
                return(false);
            }

            return(true);
        }
コード例 #18
0
        /// <summary>
        /// Is used to save data on movememt line
        /// </summary>
        /// <param name="mData"></param>
        /// <returns></returns>
        public String SaveMovementLine(List <Dictionary <string, string> > mData)
        {
            StringBuilder error = new StringBuilder();
            bool          isMoveFullContainer    = false;
            bool          isMoveFullContainerQty = false;

            Trx trx = Trx.GetTrx("Movement");

            if (mData.Count > 0)
            {
                isMoveFullContainer = Util.GetValueOfBool(mData[0]["IsFullMoveContainer"]);

                //to delete all the movement lines where MoveFullContainer is False
                if (isMoveFullContainer)
                {
                    DB.ExecuteQuery("DELETE FROM M_MovementLine WHERE M_Movement_ID = " + Util.GetValueOfInt(mData[0]["M_Movement_ID"]) + " AND MoveFullContainer= 'N' ", null, null);
                }

                // Lines not inserted, as movement line already has a full move container line.
                if (!isMoveFullContainer)
                {
                    if (Util.GetValueOfInt(DB.ExecuteScalar(@"SELECT COUNT(MoveFullContainer) FROM M_MovementLine WHERE MoveFullContainer= 'Y' AND M_Movement_ID = "
                                                            + Util.GetValueOfInt(mData[0]["M_Movement_ID"]), null, trx)) > 0)
                    {
                        trx.Close();
                        return(Msg.GetMsg(_ctx, "VIS_LinehaveFullContainer"));
                    }
                }

                // Get Line No
                int lineNo = Util.GetValueOfInt(DB.ExecuteScalar(@"SELECT NVL(MAX(Line),0) AS DefaultValue FROM M_MovementLine WHERE M_Movement_ID="
                                                                 + Util.GetValueOfInt(mData[0]["M_Movement_ID"]), null, trx));


                isMoveFullContainerQty = Util.GetValueOfBool(mData[0]["IsfullContainerQtyWise"]);

                if (!isMoveFullContainer && !isMoveFullContainerQty)
                {
                    goto moveFullContainer;
                }
                else if (isMoveFullContainer || isMoveFullContainerQty)
                {
                    error.Clear();
                    error.Append(SaveMoveLinewithFullContainer(Util.GetValueOfInt(mData[0]["M_Movement_ID"]),
                                                               Util.GetValueOfInt(mData[0]["FromLocator"]),
                                                               Util.GetValueOfInt(mData[0]["FromContainer"]),
                                                               Util.GetValueOfInt(mData[0]["ToLocator"]),
                                                               Util.GetValueOfInt(mData[0]["ToContainer"]),
                                                               lineNo, isMoveFullContainerQty,
                                                               trx));
                    trx.Close();
                    return(error.ToString());
                }

moveFullContainer:
                MMovementLine moveline = null;
                MProduct product = null;
                int      moveId  = 0;
                for (int i = 0; i < mData.Count; i++)
                {
                    #region Quantity Only
                    MMovement move = new MMovement(_ctx, Util.GetValueOfInt(mData[i]["M_Movement_ID"]), null);

                    moveId = Util.GetValueOfInt(DB.ExecuteScalar(@"SELECT NVL(M_MovementLine_ID, 0) AS M_Movement_ID FROM M_MovementLine WHERE 
                             M_Movement_ID = " + Util.GetValueOfInt(mData[i]["M_Movement_ID"]) +
                                                                 @" AND M_Product_ID = " + Util.GetValueOfInt(mData[i]["M_Product_ID"]) +
                                                                 @" AND NVL(M_AttributeSetInstance_ID, 0) = " + Util.GetValueOfInt(mData[i]["M_AttributeSetInstance_ID"]) +
                                                                 @" AND M_Locator_ID = " + Util.GetValueOfInt(mData[i]["FromLocator"]) +
                                                                 @" AND NVL(M_ProductContainer_ID, 0) = " + Util.GetValueOfInt(mData[i]["FromContainer"]) +
                                                                 @" AND M_LocatorTo_ID = " + Util.GetValueOfInt(mData[i]["ToLocator"]) +
                                                                 @" AND NVL(Ref_M_ProductContainerTo_ID, 0) = " + Util.GetValueOfInt(mData[i]["ToContainer"]) +
                                                                 @" AND AD_Org_ID = " + move.GetAD_Org_ID()));

                    if (moveId > 0)
                    {
                        moveline = new MMovementLine(_ctx, moveId, trx);
                    }
                    else
                    {
                        moveline = new MMovementLine(_ctx, 0, trx);
                    }
                    if (moveId == 0)
                    {
                        #region Create new record of movement line
                        lineNo += 10;
                        moveline.SetAD_Client_ID(move.GetAD_Client_ID());
                        moveline.SetAD_Org_ID(move.GetAD_Org_ID());
                        moveline.SetM_Movement_ID(move.GetM_Movement_ID());
                        moveline.SetLine(lineNo);
                        moveline.SetM_Product_ID(Util.GetValueOfInt(mData[i]["M_Product_ID"]));
                        moveline.SetM_AttributeSetInstance_ID(Util.GetValueOfInt(mData[i]["M_AttributeSetInstance_ID"]));
                        moveline.SetC_UOM_ID(Util.GetValueOfInt(mData[i]["C_UOM_ID"]));
                        moveline.SetM_Locator_ID(Util.GetValueOfInt(mData[i]["FromLocator"]));
                        moveline.SetM_LocatorTo_ID(Util.GetValueOfInt(mData[i]["ToLocator"]));
                        moveline.SetM_ProductContainer_ID(Util.GetValueOfInt(mData[i]["FromContainer"]));
                        moveline.SetRef_M_ProductContainerTo_ID(Util.GetValueOfInt(mData[i]["ToContainer"]));
                        moveline.SetQtyEntered(Util.GetValueOfDecimal(mData[i]["MoveQty"]));
                        moveline.SetMovementQty(Util.GetValueOfDecimal(mData[i]["MoveQty"]));
                        moveline.SetMoveFullContainer(Util.GetValueOfBool(mData[i]["IsFullMoveContainer"]));
                        #endregion
                    }
                    else
                    {
                        #region Update record of movement line
                        moveline.SetQtyEntered(Decimal.Add(moveline.GetQtyEntered(), Util.GetValueOfDecimal(mData[i]["MoveQty"])));
                        moveline.SetMovementQty(Decimal.Add(moveline.GetMovementQty(), Util.GetValueOfDecimal(mData[i]["MoveQty"])));
                        moveline.SetMoveFullContainer(Util.GetValueOfBool(mData[i]["IsFullMoveContainer"]));
                        #endregion
                    }
                    if (!moveline.Save(trx))
                    {
                        #region Save error catch and rollback
                        product = MProduct.Get(_ctx, Util.GetValueOfInt(mData[i]["M_Product_ID"]));
                        ValueNamePair pp = VLogger.RetrieveError();
                        if (pp != null)
                        {
                            _log.SaveError("Movement line not inserted through Move Container Form : ", pp.GetName());
                            if (String.IsNullOrEmpty(error.ToString()))
                            {
                                error.Append(Msg.GetMsg(_ctx, "VIS_MoveLineNotSaveFor") + product.GetName() + Msg.GetMsg(_ctx, "VIS_DueTo") + pp.GetName());
                            }
                            else
                            {
                                error.Append(" , " + Msg.GetMsg(_ctx, "VIS_MoveLineNotSaveFor") + product.GetName() + Msg.GetMsg(_ctx, "VIS_DueTo") + pp.GetName());
                            }
                        }
                        trx.Rollback();
                        #endregion
                    }
                    else
                    {
                        trx.Commit();
                    }

                    #endregion
                }
            }
            trx.Close();
            return(String.IsNullOrEmpty(error.ToString()) ? "VIS_SuccessFullyInserted" : error.ToString());
        }
コード例 #19
0
        /// <summary>
        ///      Process Confirmation Line.
        ///     - Update InOut Line
        /// </summary>
        /// <param name="isSOTrx">sales order</param>
        /// <param name="confirmType">type</param>
        /// <returns>success</returns>
        public Boolean ProcessLine(bool isSOTrx, String confirmType)
        {
            MInOutLine line = GetLine();

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

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

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

            //	Ship or Receipt
            else if (MInOutConfirm.CONFIRMTYPE_ShipReceiptConfirm.Equals(confirmType))
            {
                //Arpit
                if (GetDifferenceQty() > 0)
                {
                    GetCtx().SetContext("DifferenceQty_", VAdvantage.Utility.Util.GetValueOfString(GetDifferenceQty()));
                }
                MProduct _pro = new MProduct(GetCtx(), line.GetM_Product_ID(), Get_TrxName());
                if (_pro.GetC_UOM_ID() != line.GetC_UOM_ID())
                {
                    decimal?pc = null;
                    pc = MUOMConversion.ConvertProductFrom(GetCtx(), line.GetM_Product_ID(), GetC_UOM_ID(), GetTargetQty());
                    line.SetTargetQty(Util.GetValueOfDecimal(pc));  //TargetQty

                    //Lakhwinder 24feb 2021
                    //Change Movement qty
                    //Decimal qty = GetConfirmedQty();
                    Decimal qty = GetConfirmedQty() + GetScrappedQty();

                    Boolean isReturnTrx = line.GetParent().IsReturnTrx();

                    /* In PO receipts and SO Returns, we have the responsibility
                     * for scrapped quantity
                     */
                    if ((!isSOTrx && !isReturnTrx) || (isSOTrx && isReturnTrx))
                    {
                        qty = Decimal.Add(qty, GetScrappedQty());
                    }
                    pc = MUOMConversion.ConvertProductFrom(GetCtx(), line.GetM_Product_ID(), GetC_UOM_ID(), qty);
                    line.SetMovementQty(Util.GetValueOfDecimal(pc)); //MovementQty

                    pc = MUOMConversion.ConvertProductFrom(GetCtx(), line.GetM_Product_ID(), GetC_UOM_ID(), GetScrappedQty());
                    line.SetScrappedQty(Util.GetValueOfDecimal(pc));  //ScrappedQty

                    pc = MUOMConversion.ConvertProductFrom(GetCtx(), line.GetM_Product_ID(), GetC_UOM_ID(), GetConfirmedQty());
                    line.SetConfirmedQty(Util.GetValueOfDecimal(pc)); //confirm Qty
                }
                else
                {
                    line.SetTargetQty(GetTargetQty());

                    //Lakhwinder 24feb 2021
                    //Change Movement qty
                    //Decimal qty = GetConfirmedQty();
                    Decimal qty = GetConfirmedQty() + GetScrappedQty();

                    Boolean isReturnTrx = line.GetParent().IsReturnTrx();

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

            return(line.Save(Get_TrxName()));
        }
コード例 #20
0
        /// <summary>
        /// Create Facts (the accounting logic) for
        /// CMC.
        /// <pre>
        /// Expense
        /// CashExpense     DR
        ///        CashAsset               CR
        ///Receipt
        ///        CashAsset       DR
        ///        CashReceipt             CR
        ///  Charge
        ///        Charge          DR
        ///          CashAsset               CR
        ///  Difference
        ///          CashDifference  DR
        ///          CashAsset               CR
        ///  Invoice
        ///          CashAsset       DR
        ///          CashTransfer            CR
        ///  Transfer
        ///          BankInTransit   DR
        ///          CashAsset               CR
        ///  </pre>
        /// </summary>
        /// <param name="?"></param>
        /// <returns>Fact</returns>
        public override List <Fact> CreateFacts(MAcctSchema as1)
        {
            //  create Fact Header
            List <Fact> facts = new List <Fact>();

            if (GetDocumentType().Equals(MDocBaseType.DOCBASETYPE_PROFITLOSS))
            {
                //Change By mohit
                // Get Assigned Accounting Schemas based on organization
                MProfitLossLines PLossline        = new MProfitLossLines(GetCtx(), _lines[0].Get_ID(), null);
                MProfitLoss      PLoss            = new MProfitLoss(GetCtx(), PLossline.GetC_ProfitLoss_ID(), null);
                MAcctSchema      HeaderAcctSchema = new MAcctSchema(GetCtx(), Util.GetValueOfInt(PLoss.Get_Value("C_AcctSchema_ID")), null);
                List <int>       _ListAcctSch     = new List <int>();
                // Profit & Loss account shall be posted only in accounting schema selected on header (By Ashish - discussed with Mukesh sir)
                //_ListAcctSch = GetAcctSchemas(PLoss.GetAD_Org_ID());
                _ListAcctSch.Add(HeaderAcctSchema.GetC_AcctSchema_ID());



                if (_ListAcctSch.Count > 0)
                {
                    int CurrencyType_ID = GetDefaultConversionType(GetAD_Client_ID(), GetAD_Org_ID());
                    for (int asch = 0; asch < _ListAcctSch.Count; asch++)
                    {
                        MAcctSchema AccountingSchema = new MAcctSchema(GetCtx(), _ListAcctSch[asch], null);
                        //	Decimal grossAmt = getAmount(Doc.AMTTYPE_Gross);
                        SetC_Currency_ID(GetCurrency(AccountingSchema.GetC_AcctSchema_ID()));
                        //  Commitment
                        Fact    fact = new Fact(this, AccountingSchema, Fact.POST_Actual);
                        Decimal total = Env.ZERO, totalCredit = Env.ZERO, totalDebit = Env.ZERO;
                        Decimal credit = Env.ZERO, debit = Env.ZERO;

                        for (int i = 0; i < _lines.Length; i++)
                        {
                            DocLine          dline = _lines[i];
                            MProfitLossLines line  = new MProfitLossLines(GetCtx(), dline.Get_ID(), null);

                            if (Util.GetValueOfInt(HeaderAcctSchema.GetC_Currency_ID()) == Util.GetValueOfInt(AccountingSchema.GetC_Currency_ID()))
                            {
                                credit = Util.GetValueOfDecimal(dline.GetAmtSourceCr());
                                debit  = Util.GetValueOfDecimal(dline.GetAmtSourceDr());
                            }
                            else
                            {
                                credit = MConversionRate.Convert(GetCtx(), Util.GetValueOfDecimal(dline.GetAmtSourceCr()), HeaderAcctSchema.GetC_Currency_ID(), AccountingSchema.GetC_Currency_ID(),
                                                                 PLoss.GetDateAcct(), CurrencyType_ID, GetAD_Client_ID(), GetAD_Org_ID());

                                debit = MConversionRate.Convert(GetCtx(), Util.GetValueOfDecimal(dline.GetAmtSourceDr()), HeaderAcctSchema.GetC_Currency_ID(), AccountingSchema.GetC_Currency_ID(),
                                                                PLoss.GetDateAcct(), CurrencyType_ID, GetAD_Client_ID(), GetAD_Org_ID());

                                Util.GetValueOfDecimal(dline.GetAmtAcctDr());
                            }
                            if (credit > 0)
                            {
                                totalCredit = Decimal.Add(totalCredit, credit);
                            }
                            if (debit > 0)
                            {
                                totalDebit = Decimal.Add(totalDebit, debit);
                            }

                            //	Account
                            MAccount expense = MAccount.Get(GetCtx(), GetAD_Client_ID(), GetAD_Org_ID(), AccountingSchema.GetC_AcctSchema_ID(), line.GetAccount_ID(), line.GetC_SubAcct_ID(), line.GetM_Product_ID(), line.GetC_BPartner_ID(), line.GetAD_OrgTrx_ID(),
                                                            line.GetC_LocFrom_ID(), line.GetC_LocTo_ID(), line.GetC_SalesRegion_ID(), line.GetC_Project_ID(), line.GetC_Campaign_ID(), line.GetC_Activity_ID(), line.GetUser1_ID(), line.GetUser2_ID(), line.GetUserElement1_ID(), line.GetUserElement2_ID(),
                                                            line.GetUserElement3_ID(), line.GetUserElement4_ID(), line.GetUserElement5_ID(), line.GetUserElement6_ID(), line.GetUserElement7_ID(), line.GetUserElement8_ID(), line.GetUserElement9_ID());

                            fact.CreateLine(dline, expense, GetCurrency(AccountingSchema.GetC_AcctSchema_ID()), debit, credit);
                        }
                        total = totalCredit - totalDebit;
                        if (total != Env.ZERO)
                        {
                            int      validComID = Util.GetValueOfInt(DB.ExecuteScalar(@"SELECT IncomeSummary_Acct FROM C_AcctSchema_GL WHERE C_AcctSchema_ID=" + AccountingSchema.GetC_AcctSchema_ID() + " AND AD_Client_ID = " + GetAD_Client_ID()));
                            MAccount acct       = MAccount.Get(GetCtx(), validComID);
                            fact.CreateLine(null, acct, GetC_Currency_ID(), total);
                        }
                        //if (TotalCurrLoss != Env.ZERO)
                        //{
                        //    int validComID = Util.GetValueOfInt(DB.ExecuteScalar(@"SELECT C_ValidCombination_ID FROM C_ValidCombination WHERE Account_ID= ( SELECT C_ElementValue_ID FROM C_ElementValue WHERE Value='82540' AND AD_Client_ID = " + GetAD_Client_ID() + " )"));
                        //    MAccount acct = MAccount.Get(GetCtx(), validComID);
                        //    TotalCurrLoss = MConversionRate.Convert(GetCtx(), TotalCurrLoss, childCashCurrency, headerCashCurrency, GetAD_Client_ID(), GetAD_Org_ID());
                        //    fact.CreateLine(null, acct,
                        //     GetC_Currency_ID(), (TotalCurrLoss));
                        //}

                        facts.Add(fact);
                    }
                }
            }
            return(facts);
        }
コード例 #21
0
 /// <summary>
 /// Before Save
 /// </summary>
 /// <param name="newRecord"></param>
 /// <returns>true</returns>
 protected override bool BeforeSave(bool newRecord)
 {
     SetEndingBalance(Decimal.Add(GetBeginningBalance(), GetStatementDifference()));
     return(true);
 }
コード例 #22
0
        /**
         *	Prepare Document
         *  @return new status (In Progress or Invalid)
         */
        public String PrepareIt()
        {
            try
            {
                log.Info(ToString());
                _processMsg = ModelValidationEngine.Get().FireDocValidate(this, ModalValidatorVariables.DOCTIMING_BEFORE_PREPARE);
                if (_processMsg != null)
                {
                    return(DocActionVariables.STATUS_INVALID);
                }

                MRequisitionLine[] lines = GetLines();

                // JID_0901: Added by Bharat on 30 Jan 2019 gives message when there are no line on requisition
                if (lines.Length == 0)
                {
                    _processMsg = "@NoLines@";
                    return(DocActionVariables.STATUS_INVALID);
                }

                //	Invalid
                if (GetAD_User_ID() == 0 ||
                    GetM_PriceList_ID() == 0 ||
                    GetM_Warehouse_ID() == 0)
                {
                    return(DocActionVariables.STATUS_INVALID);
                }



                //	Std Period open?
                if (!MPeriod.IsOpen(GetCtx(), GetDateDoc(), MDocBaseType.DOCBASETYPE_PURCHASEREQUISITION))
                {
                    _processMsg = "@PeriodClosed@";
                    return(DocActionVariables.STATUS_INVALID);
                }

                // is Non Business Day?
                if (MNonBusinessDay.IsNonBusinessDay(GetCtx(), GetDateDoc()))
                {
                    _processMsg = Common.Common.NONBUSINESSDAY;
                    return(DocActionVariables.STATUS_INVALID);
                }



                //	Add up Amounts
                int     precision  = MPriceList.GetStandardPrecision(GetCtx(), GetM_PriceList_ID());
                Decimal totalLines = Env.ZERO;
                for (int i = 0; i < lines.Length; i++)
                {
                    MRequisitionLine line    = lines[i];
                    Decimal          lineNet = Decimal.Multiply(line.GetQty(), line.GetPriceActual());
                    lineNet = Decimal.Round(lineNet, precision);//, MidpointRounding.AwayFromZero);
                    if (lineNet.CompareTo(line.GetLineNetAmt()) != 0)
                    {
                        line.SetLineNetAmt(lineNet);
                        line.Save();
                    }
                    totalLines = Decimal.Add(totalLines, line.GetLineNetAmt());
                }
                if (totalLines.CompareTo(GetTotalLines()) != 0)
                {
                    SetTotalLines(totalLines);
                    Save();
                }
                _justPrepared = true;
            }
            catch (Exception ex)
            {
                // MessageBox.Show("MRequisition--PrepareIt");
                log.Severe(ex.ToString());
            }
            return(DocActionVariables.STATUS_INPROGRESS);
        }
コード例 #23
0
        /// <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);
            }

            //	Std Period open?
            if (!MPeriod.IsOpen(GetCtx(), GetStatementDate(), MDocBaseType.DOCBASETYPE_BANKSTATEMENT))
            {
                m_processMsg = "@PeriodClosed@";
                return(DocActionVariables.STATUS_INVALID);
            }

            // is Non Business Day?
            if (MNonBusinessDay.IsNonBusinessDay(GetCtx(), GetStatementDate()))
            {
                m_processMsg = Common.Common.NONBUSINESSDAY;
                return(DocActionVariables.STATUS_INVALID);
            }

            MBankStatementLine[] lines = GetLines(true);
            if (lines.Length == 0)
            {
                m_processMsg = "@NoLines@";
                return(DocActionVariables.STATUS_INVALID);
            }
            //	Lines
            Decimal  total   = Env.ZERO;
            DateTime?minDate = GetStatementDate();
            DateTime?maxDate = minDate;

            for (int i = 0; i < lines.Length; i++)
            {
                MBankStatementLine line = lines[i];
                total = Decimal.Add(total, line.GetStmtAmt());
                if (line.GetDateAcct() < (minDate))//before
                {
                    minDate = line.GetDateAcct();
                }
                if (line.GetDateAcct() > maxDate)//after
                {
                    maxDate = line.GetDateAcct();
                }
            }
            SetStatementDifference(total);
            SetEndingBalance(Decimal.Add(GetBeginningBalance(), total));
            if (!MPeriod.IsOpen(GetCtx(), minDate, MDocBaseType.DOCBASETYPE_BANKSTATEMENT) ||
                !MPeriod.IsOpen(GetCtx(), maxDate, MDocBaseType.DOCBASETYPE_BANKSTATEMENT))
            {
                m_processMsg = "@PeriodClosed@";
                return(DocActionVariables.STATUS_INVALID);
            }

            // is Non Business Day?
            if (MNonBusinessDay.IsNonBusinessDay(GetCtx(), GetStatementDate()))
            {
                m_processMsg = Common.Common.NONBUSINESSDAY;
                return(DocActionVariables.STATUS_INVALID);
            }


            m_justPrepared = true;
            if (!DOCACTION_Complete.Equals(GetDocAction()))
            {
                SetDocAction(DOCACTION_Complete);
            }
            return(DocActionVariables.STATUS_INPROGRESS);
        }
コード例 #24
0
        /**
         *  Close Document.
         *  Cancel not delivered Qunatities
         *  @return true if success
         */
        public bool CloseIt()
        {
            try
            {
                log.Info("closeIt - " + ToString());
                //	Close Not delivered Qty
                MRequisitionLine[] lines      = GetLines();
                Decimal            totalLines = Env.ZERO;
                MProduct           product    = null;
                for (int i = 0; i < lines.Length; i++)
                {
                    MRequisitionLine line = lines[i];

                    if (line.GetM_Product_ID() > 0)
                    {
                        product = MProduct.Get(GetCtx(), line.GetM_Product_ID());
                    }

                    Decimal finalQty = line.GetQty();
                    if (line.GetC_OrderLine_ID() == 0)
                    {
                        finalQty = Env.ZERO;
                    }
                    else
                    {
                        MOrderLine ol = new MOrderLine(GetCtx(), line.GetC_OrderLine_ID(), Get_TrxName());
                        finalQty = ol.GetQtyOrdered();
                    }
                    Tuple <String, String, String> mInfo = null;
                    if (Env.HasModulePrefix("DTD001_", out mInfo))
                    {
                        int quant = Util.GetValueOfInt(line.GetQty() - line.GetDTD001_DeliveredQty());
                        // new 6jan  0
                        int _count = Util.GetValueOfInt(DB.ExecuteScalar(" SELECT Count(*) FROM AD_Column WHERE columnname = 'DTD001_SourceReserve' "));

                        //Update storage requisition reserved qty
                        //if (Util.GetValueOfInt(DB.ExecuteScalar("SELECT COUNT(AD_MODULEINFO_ID) FROM AD_MODULEINFO WHERE PREFIX='VA203_'", null, null)) > 0)
                        if (Env.IsModuleInstalled("VA203_") && product != null && product.GetProductType() == X_M_Product.PRODUCTTYPE_Item)
                        {
                            if (GetDocAction() != "VO" && GetDocStatus() != "DR")
                            {
                                if (quant > 0)
                                {
                                    //int loc_id = GetLocation(GetM_Warehouse_ID());
                                    int loc_id = line.GetOrderLocator_ID();
                                    storage = MStorage.Get(GetCtx(), loc_id, line.GetM_Product_ID(), line.GetM_AttributeSetInstance_ID(), Get_Trx());
                                    if (storage == null)
                                    {
                                        storage = MStorage.GetCreate(GetCtx(), loc_id, line.GetM_Product_ID(), line.GetM_AttributeSetInstance_ID(), Get_Trx());
                                    }
                                    storage.SetDTD001_QtyReserved((Decimal.Subtract(storage.GetDTD001_QtyReserved(), (Decimal)quant)));
                                    storage.Save();
                                    //new 6jan 5
                                    if (_count > 0)
                                    {
                                        //int Swhloc_id = GetSwhLocation(GetDTD001_MWarehouseSource_ID());
                                        int Swhloc_id = line.GetReserveLocator_ID();
                                        Swhstorage = MStorage.Get(GetCtx(), Swhloc_id, line.GetM_Product_ID(), line.GetM_AttributeSetInstance_ID(), Get_Trx());
                                        if (Swhstorage == null)
                                        {
                                            Swhstorage = MStorage.GetCreate(GetCtx(), Swhloc_id, line.GetM_Product_ID(), line.GetM_AttributeSetInstance_ID(), Get_Trx());
                                        }
                                        Swhstorage.SetDTD001_SourceReserve((Decimal.Subtract(Swhstorage.GetDTD001_SourceReserve(), (Decimal)quant)));
                                        Swhstorage.Save();
                                    }
                                    //end
                                }
                            }
                        }
                        else if (GetDocAction() != "VO" && GetDocStatus() != "DR" && product != null && product.GetProductType() == X_M_Product.PRODUCTTYPE_Item)
                        {
                            if (quant > 0)
                            {
                                int loc_id = 0;
                                if (line.Get_ColumnIndex("OrderLocator_ID") > 0)
                                {
                                    loc_id = line.GetOrderLocator_ID();
                                }
                                else
                                {
                                    loc_id = GetLocation(GetM_Warehouse_ID());
                                }
                                storage = MStorage.Get(GetCtx(), loc_id, line.GetM_Product_ID(), line.GetM_AttributeSetInstance_ID(), Get_Trx());
                                if (storage == null)
                                {
                                    storage = MStorage.GetCreate(GetCtx(), loc_id, line.GetM_Product_ID(), line.GetM_AttributeSetInstance_ID(), Get_Trx());
                                }
                                storage.SetDTD001_QtyReserved((Decimal.Subtract(storage.GetDTD001_QtyReserved(), (Decimal)quant)));
                                storage.Save();

                                //new 6jan 6
                                if (_count > 0)
                                {
                                    int Swhloc_id = 0;
                                    if (line.Get_ColumnIndex("ReserveLocator_ID") > 0)
                                    {
                                        Swhloc_id = line.GetReserveLocator_ID();
                                    }
                                    else
                                    {
                                        Swhloc_id = GetSwhLocation(GetM_Warehouse_ID());
                                    }
                                    Swhstorage = MStorage.Get(GetCtx(), Swhloc_id, line.GetM_Product_ID(), line.GetM_AttributeSetInstance_ID(), Get_Trx());
                                    if (Swhstorage == null)
                                    {
                                        Swhstorage = MStorage.GetCreate(GetCtx(), Swhloc_id, line.GetM_Product_ID(), line.GetM_AttributeSetInstance_ID(), Get_Trx());
                                    }
                                    Swhstorage.SetDTD001_SourceReserve((Decimal.Subtract(Swhstorage.GetDTD001_SourceReserve(), (Decimal)quant)));
                                    Swhstorage.Save();
                                }
                                //end
                            }
                        }
                    }
                    //	final qty is not line qty
                    if (finalQty.CompareTo(line.GetQty()) != 0)
                    {
                        String description = line.GetDescription();
                        if (description == null)
                        {
                            description = "";
                        }
                        description += " [" + line.GetQty() + "]";
                        line.SetDescription(description);
                        // Amit 9-feb-2015
                        // line.SetQty(finalQty);
                        //Amit
                        line.SetLineNetAmt();
                        line.Save();
                    }
                    //get Grand Total or SubTotal
                    totalLines = Decimal.Add(totalLines, line.GetLineNetAmt());
                }
                if (totalLines.CompareTo(GetTotalLines()) != 0)
                {
                    SetTotalLines(totalLines);
                    Save();
                }
            }
            catch (Exception ex)
            {
                // MessageBox.Show("MRequisition--CloseIt");
                log.Severe(ex.ToString());
            }
            return(true);
        }
コード例 #25
0
        /// <summary>
        ///  Generate PaySelection
        /// </summary>
        public string GeneratePaySelect(Ctx ctx, List <GridRecords> selectedRecords, Decimal?paymentAmt, String paymentRule, int C_BankAccount_ID, DateTime?payDate)
        {
            Trx trx   = null;
            Trx p_trx = null;

            List <int>      Invoice_ID = new List <int>();
            List <Decimal?> openAmt    = new List <Decimal?>();
            List <Decimal?> payAmt     = new List <Decimal?>();

            int     rowsSelected = 0;
            Decimal?totalAmt     = 0;

            // BindingSource rowSource = vdgvPayment.ItemsSource as BindingSource;
            for (int i = 0; i < selectedRecords.Count; i++)
            {
                if ((Convert.ToBoolean(selectedRecords[i].SELECT)))
                {
                    Decimal?amt = Util.GetValueOfDecimal(selectedRecords[i].PAYMENTAMOUNT);
                    Invoice_ID.Add(Util.GetValueOfInt(selectedRecords[i].C_INVOICE_ID));
                    openAmt.Add(Util.GetValueOfDecimal(selectedRecords[i].AMOUNTDUE));
                    payAmt.Add(Util.GetValueOfDecimal(selectedRecords[i].PAYMENTAMOUNT));
                    rowsSelected++;
                }
            }

            if (rowsSelected == 0)
            {
                return("");
            }

            //String paymentRule = Util.GetValueOfString(cmbPaymentRule.SelectedValue);
            //int C_BankAccount_ID = Util.GetValueOfInt(cmbBankAccount.SelectedValue);
            ////  Create Header
            //DateTime? payDate = Util.GetValueOfDateTime(vdtpPayDate.SelectedDate);


            MPaySelection m_ps = new MPaySelection(ctx, 0, null);

            m_ps.SetName(Msg.GetMsg(ctx, "VPaySelect")
                         + " - " + paymentRule
                         + " - " + payDate.Value.Date);
            m_ps.SetPayDate(payDate);
            m_ps.SetC_BankAccount_ID(C_BankAccount_ID);
            m_ps.SetIsApproved(true);
            if (!m_ps.Save())
            {
                //log.SaveError("SaveError", Msg.Translate(Envs.GetCtx(), "C_PaySelection_ID"));
                m_ps = null;
                return("");
            }

            _C_PaySelection_ID = m_ps.GetC_PaySelection_ID();
            string name = m_ps.GetName();

            //string sqlTableID = "select ad_table_id from ad_table where tablename = 'C_PaySelection'";
            //int AD_Table_ID = Util.GetValueOfInt(DB.ExecuteScalar(sqlTableID, null, null));

            // log.Config(m_ps.ToString());
            bool isSOTrx = false;

            if (X_C_Order.PAYMENTRULE_DirectDebit.Equals(paymentRule))
            {
                isSOTrx = true;
            }

            int     line    = 0;
            Decimal?pAmt    = Decimal.Zero;
            Decimal?oldpAmt = Decimal.Zero;

            for (int j = 0; j < Invoice_ID.Count; j++)
            {
                line = line + 10;
                if (Decimal.Add(pAmt.Value, Util.GetValueOfDecimal(payAmt[j])) > paymentAmt)
                {
                    oldpAmt = Decimal.Subtract(paymentAmt.Value, pAmt.Value);
                }
                pAmt = Decimal.Add(pAmt.Value, Util.GetValueOfDecimal(payAmt[j]));
                // pAmt = Util.GetValueOfDecimal(payAmt[j]);
                MPaySelectionLine psl = new MPaySelectionLine(m_ps, line, paymentRule);
                //psl.SetInvoice(Util.GetValueOfInt(Invoice_ID[j]), isSOTrx, Util.GetValueOfDecimal(openAmt[j]), Util.GetValueOfDecimal(payAmt[j]), Decimal.Subtract(Util.GetValueOfDecimal(openAmt[j]), Util.GetValueOfDecimal(payAmt[j])));
                if (paymentAmt >= pAmt)
                {
                    psl.SetInvoice(Util.GetValueOfInt(Invoice_ID[j]), isSOTrx, Util.GetValueOfDecimal(openAmt[j]), Util.GetValueOfDecimal(payAmt[j]), Decimal.Zero);
                    if (!psl.Save())
                    {
                        // log.SaveError("PaymentSelectionLineNotSaved", "PaymentSelectionLineNotSaved");
                        return("");
                    }
                    // log.Fine("C_Invoice_ID=" + Util.GetValueOfInt(Invoice_ID[j]) + ", PayAmt=" + Util.GetValueOfDecimal(payAmt[j]));
                }
                else
                {
                    psl.SetInvoice(Util.GetValueOfInt(Invoice_ID[j]), isSOTrx, Util.GetValueOfDecimal(openAmt[j]), oldpAmt.Value, Decimal.Zero);
                    if (!psl.Save())
                    {
                        //   log.SaveError("PaymentSelectionLineNotSaved", "PaymentSelectionLineNotSaved");
                        return("");
                    }
                    // log.Fine("C_Invoice_ID=" + Util.GetValueOfInt(Invoice_ID[j]) + ", PayAmt=" + Util.GetValueOfDecimal(payAmt[j]));
                }
            }


            //if (false.Equals(((Message)sc).DialogResult))
            //{
            //    Dispose();
            //    return;
            //}


            MPaySelection psel = new MPaySelection(ctx, _C_PaySelection_ID, null);

            if (psel.Get_ID() == 0)
            {
                throw new ArgumentException("Not found C_PaySelection_ID=" + _C_PaySelection_ID);
            }
            if (psel.IsProcessed())
            {
                throw new ArgumentException("@Processed@");
            }
            //
            MPaySelectionLine[]       lines = psel.GetLines(false);
            List <MPaySelectionCheck> _list = new List <MPaySelectionCheck>();

            for (int i = 0; i < lines.Length; i++)
            {
                MPaySelectionLine payLine = lines[i];
                if (!payLine.IsActive() || payLine.IsProcessed())
                {
                    continue;
                }
                CreateCheck(ctx, payLine, _list);
            }
            //
            psel.SetProcessed(true);
            psel.Save();

            //string sql = "select ad_form_id from ad_form where classname = 'VAdvantage.Apps.AForms.VPayPrint'";
            //int AD_Form_ID = Util.GetValueOfInt(DB.ExecuteScalar(sql, null, null));

            return("@C_PaySelectionCheck_ID@ - #" + _list.Count);

            //SetBusy(false);
            //Dispose();
            //FormFrame ff = new FormFrame();
            //ff.OpenForm(AD_Form_ID);
        }   //  generatePaySelect