示例#1
0
        private void DeleteCurrentBatchGiftData(Int32 ABatchNumber)
        {
            DataView giftDetailView = new DataView(FMainDS.AGiftDetail);

            giftDetailView.RowFilter = String.Format("{0}={1}",
                                                     AGiftDetailTable.GetBatchNumberDBName(),
                                                     ABatchNumber);

            giftDetailView.Sort = String.Format("{0} DESC, {1} DESC",
                                                AGiftDetailTable.GetGiftTransactionNumberDBName(),
                                                AGiftDetailTable.GetDetailNumberDBName());

            foreach (DataRowView dr in giftDetailView)
            {
                dr.Delete();
            }

            DataView giftView = new DataView(FMainDS.AGift);

            giftView.RowFilter = String.Format("{0}={1}",
                                               AGiftTable.GetBatchNumberDBName(),
                                               ABatchNumber);

            giftView.Sort = String.Format("{0} DESC",
                                          AGiftTable.GetGiftTransactionNumberDBName());

            foreach (DataRowView dr in giftView)
            {
                dr.Delete();
            }
        }
示例#2
0
        /// <summary>
        /// Find the latest gift that was given by a donor
        /// </summary>
        /// <param name="AParameters">report parameter list</param>
        /// <param name="AResults">result list</param>
        /// <returns>DataTable with row for last gift by donor</returns>
        public static DataTable SelectLatestGiftRow(TParameterList AParameters, TResultList AResults)
        {
            Int64 DonorKey = AParameters.Get("PartnerKey").ToInt64();

            String StrSql = "SELECT DISTINCT " + AGiftTable.GetTableDBName() + "." + AGiftTable.GetLedgerNumberDBName() + ", " +
                            AGiftTable.GetTableDBName() + "." + AGiftTable.GetBatchNumberDBName() + ", " +
                            AGiftTable.GetTableDBName() + "." + AGiftTable.GetGiftTransactionNumberDBName() + ", " +
                            AGiftTable.GetTableDBName() + "." + AGiftTable.GetDateEnteredDBName();

            StrSql = StrSql +
                     " FROM " + AGiftTable.GetTableDBName() +
                     " WHERE " + AGiftTable.GetTableDBName() + "." + AGiftTable.GetDonorKeyDBName() + " = " + DonorKey.ToString() +
                     " ORDER BY " + AGiftTable.GetTableDBName() + "." + AGiftTable.GetDateEnteredDBName() + " DESC";

            TDBTransaction Transaction = new TDBTransaction();
            DataTable      tempTbl     = new DataTable();

            DBAccess.ReadTransaction(
                ref Transaction,
                delegate
            {
                tempTbl = Transaction.DataBaseObj.SelectDT(StrSql, "result", Transaction);
            });

            DataTable resultTbl = tempTbl.Clone();

            resultTbl.Clear();

            if (tempTbl.Rows.Count > 0)
            {
                resultTbl.Rows.Add((object[])tempTbl.Rows[0].ItemArray.Clone());
            }

            return(resultTbl);
        }
        /// <summary>
        /// Update all donor names in gift details table
        /// </summary>
        /// <param name="ABatchNumber"></param>
        private void UpdateAllDonorNames(Int32 ABatchNumber)
        {
            Dictionary <Int32, Int64>  GiftsDict  = new Dictionary <Int32, Int64>();
            Dictionary <Int64, string> DonorsDict = new Dictionary <Int64, string>();

            DataView GiftDV = new DataView(FMainDS.AGift);

            GiftDV.RowFilter = string.Format("{0}={1}",
                                             AGiftTable.GetBatchNumberDBName(),
                                             ABatchNumber);

            GiftDV.Sort = string.Format("{0} ASC", AGiftTable.GetGiftTransactionNumberDBName());

            foreach (DataRowView drv in GiftDV)
            {
                AGiftRow gr = (AGiftRow)drv.Row;

                Int64 donorKey = gr.DonorKey;

                GiftsDict.Add(gr.GiftTransactionNumber, donorKey);

                if (!DonorsDict.ContainsKey(donorKey))
                {
                    if (donorKey != 0)
                    {
                        PPartnerRow pr = RetrieveDonorRow(donorKey);

                        if (pr != null)
                        {
                            DonorsDict.Add(donorKey, pr.PartnerShortName);
                        }
                    }
                    else
                    {
                        DonorsDict.Add(0, "");
                    }
                }
            }

            //Add donor info to gift details
            DataView GiftDetailDV = new DataView(FMainDS.AGiftDetail);

            GiftDetailDV.RowFilter = string.Format("{0}={1}",
                                                   AGiftDetailTable.GetBatchNumberDBName(),
                                                   ABatchNumber);

            GiftDetailDV.Sort = string.Format("{0} ASC", AGiftDetailTable.GetGiftTransactionNumberDBName());

            foreach (DataRowView drv in GiftDetailDV)
            {
                GiftBatchTDSAGiftDetailRow giftDetail = (GiftBatchTDSAGiftDetailRow)drv.Row;

                Int64 donorKey = GiftsDict[giftDetail.GiftTransactionNumber];

                giftDetail.DonorKey  = donorKey;
                giftDetail.DonorName = DonorsDict[donorKey];
            }
        }
示例#4
0
        /// <summary>
        /// Select the last Gift and motivation details of the gifts that were given within the time period from one partner.
        /// </summary>
        /// <param name="ADonorKey">Partner key of the donor</param>
        /// <param name="ALedgerNumber">Ledger number</param>
        /// <param name="AStartDate">Start date of the period</param>
        /// <param name="AEndDate">End date of the period</param>
        /// <param name="ACurrency">Currency: Base or International</param>
        /// <returns>True if a gift was found; otherwise false</returns>
        private bool SelectLastGift(Int64 ADonorKey, Int64 ALedgerNumber, DateTime AStartDate, DateTime AEndDate, String ACurrency)
        {
            String StrSql = "SELECT " + AGiftTable.GetDateEnteredDBName() + ", " +
                            AGiftDetailTable.GetTableDBName() + "." + AGiftDetailTable.GetMotivationGroupCodeDBName() + ", " +
                            AGiftDetailTable.GetTableDBName() + "." + AGiftDetailTable.GetMotivationDetailCodeDBName();

            if (ACurrency == "Base")
            {
                StrSql = StrSql + ", " + AGiftDetailTable.GetGiftAmountDBName() + " AS CurrentAmount";
            }
            else
            {
                StrSql = StrSql + ", " + AGiftDetailTable.GetGiftAmountIntlDBName() + " AS CurrentAmount";
            }

            StrSql = StrSql +
                     " FROM " + AGiftTable.GetTableDBName() +
                     " , " + AGiftDetailTable.GetTableDBName() +
                     ", " + AGiftBatchTable.GetTableDBName() +

                     " WHERE " + AGiftTable.GetTableDBName() + "." + AGiftTable.GetLedgerNumberDBName() + " = " + ALedgerNumber.ToString() +
                     " AND " + AGiftDetailTable.GetTableDBName() + "." + AGiftDetailTable.GetLedgerNumberDBName() + " = " +
                     ALedgerNumber.ToString() +
                     " AND " + AGiftBatchTable.GetTableDBName() + "." + AGiftBatchTable.GetLedgerNumberDBName() + " = " + ALedgerNumber.ToString() +
                     " AND " + AGiftTable.GetTableDBName() + "." + AGiftTable.GetDonorKeyDBName() + " = " + ADonorKey.ToString() +
                     " AND " + AGiftTable.GetTableDBName() + "." + AGiftTable.GetBatchNumberDBName() + " = " + AGiftDetailTable.GetTableDBName() +
                     "." + AGiftDetailTable.GetBatchNumberDBName() +
                     " AND " + AGiftBatchTable.GetTableDBName() + "." + AGiftBatchTable.GetBatchNumberDBName() + " = " +
                     AGiftDetailTable.GetTableDBName() + "." + AGiftDetailTable.GetBatchNumberDBName() +
                     " AND " + AGiftTable.GetTableDBName() + "." + AGiftTable.GetGiftTransactionNumberDBName() + " = " +
                     AGiftDetailTable.GetTableDBName() + "." + AGiftDetailTable.GetGiftTransactionNumberDBName() +
                     " AND " + AGiftTable.GetTableDBName() + "." + AGiftTable.GetDateEnteredDBName() + " BETWEEN '" + AStartDate.ToString(
                "yyyy-MM-dd") + "' AND '" + AEndDate.ToString("yyyy-MM-dd") + "'" +
                     " AND " + AGiftBatchTable.GetTableDBName() + "." + AGiftBatchTable.GetBatchStatusDBName() + " = 'Posted'" +
                     " ORDER BY " + AGiftTable.GetTableDBName() + "." + AGiftTable.GetDateEnteredDBName() + " DESC LIMIT 1";

            DataTable Table = situation.GetDatabaseConnection().SelectDT(StrSql, "table",
                                                                         situation.GetDatabaseConnection().Transaction, new OdbcParameter[] { });

            if (Table.Rows.Count > 0)
            {
                DateTime DateEntered      = (DateTime)Table.Rows[0][AGiftTable.GetDateEnteredDBName()];
                decimal  CurrentAmount    = Convert.ToDecimal(Table.Rows[0]["CurrentAmount"]);
                String   MotivationDetail = (String)Table.Rows[0][AGiftDetailTable.GetMotivationDetailCodeDBName()];
                String   MotivationGroup  = (String)Table.Rows[0][AGiftDetailTable.GetMotivationGroupCodeDBName()];

                situation.GetParameters().Add("LastGiftDate", new TVariant(DateEntered));
                situation.GetParameters().Add("LastGiftAmount", new TVariant(CurrentAmount));
                situation.GetParameters().Add("MotivationDetail", new TVariant(MotivationDetail));
                situation.GetParameters().Add("MotivationGroup", new TVariant(MotivationGroup));

                return(true);
            }

            return(false);
        }
        private bool DonorIsAlreadyLoaded(Int64 ADonorKey, Int32 AGiftNumber)
        {
            //Check for Donor in loaded gift batches
            DataView giftDV = new DataView(FMainDS.AGift);

            giftDV.RowFilter = string.Format("{0}={1} And Not ({2}={3} And {4}={5})",
                                             AGiftTable.GetDonorKeyDBName(),
                                             ADonorKey,
                                             AGiftTable.GetBatchNumberDBName(),
                                             FBatchNumber,
                                             AGiftTable.GetGiftTransactionNumberDBName(),
                                             AGiftNumber);

            return(giftDV != null && giftDV.Count > 0);
        }
示例#6
0
        private void DeleteCurrentBatchGiftData(Int32 ABatchNumber, ref List <string> AModifiedDetailKeyRows)
        {
            DataView giftDetailView = new DataView(FMainDS.AGiftDetail);

            giftDetailView.RowFilter = String.Format("{0}={1}",
                                                     AGiftDetailTable.GetBatchNumberDBName(),
                                                     ABatchNumber);

            giftDetailView.Sort = String.Format("{0} DESC, {1} DESC",
                                                AGiftDetailTable.GetGiftTransactionNumberDBName(),
                                                AGiftDetailTable.GetDetailNumberDBName());

            foreach (DataRowView dr in giftDetailView)
            {
                AGiftDetailRow gdr = (AGiftDetailRow)dr.Row;

                if ((gdr.ModifiedDetailKey != null) && (gdr.ModifiedDetailKey.Length > 0))
                {
                    AModifiedDetailKeyRows.Add(gdr.ModifiedDetailKey);
                }

                dr.Delete();
            }

            DataView giftView = new DataView(FMainDS.AGift);

            giftView.RowFilter = String.Format("{0}={1}",
                                               AGiftTable.GetBatchNumberDBName(),
                                               ABatchNumber);

            giftView.Sort = String.Format("{0} DESC",
                                          AGiftTable.GetGiftTransactionNumberDBName());

            foreach (DataRowView dr in giftView)
            {
                dr.Delete();
            }
        }
示例#7
0
        /// <summary>
        /// Delete data from current gift batch
        /// </summary>
        /// <param name="ABatchNumber"></param>
        /// <param name="AModifiedDetailKeyRows"></param>
        public void DeleteBatchGiftData(Int32 ABatchNumber, ref List <string> AModifiedDetailKeyRows)
        {
            DataView giftDetailView = new DataView(FMainDS.AGiftDetail);

            giftDetailView.RowFilter = String.Format("{0}={1}",
                                                     AGiftDetailTable.GetBatchNumberDBName(),
                                                     ABatchNumber);

            giftDetailView.Sort = String.Format("{0} DESC, {1} DESC",
                                                AGiftDetailTable.GetGiftTransactionNumberDBName(),
                                                AGiftDetailTable.GetDetailNumberDBName());

            foreach (DataRowView dr in giftDetailView)
            {
                AGiftDetailRow gdr = (AGiftDetailRow)dr.Row;

                if (gdr.ModifiedDetail && !string.IsNullOrEmpty(gdr.ModifiedDetailKey))
                {
                    AModifiedDetailKeyRows.Add(gdr.ModifiedDetailKey);
                }

                dr.Delete();
            }

            DataView GiftView = new DataView(FMainDS.AGift);

            GiftView.RowFilter = String.Format("{0}={1}",
                                               AGiftTable.GetBatchNumberDBName(),
                                               ABatchNumber);

            GiftView.Sort = String.Format("{0} DESC",
                                          AGiftTable.GetGiftTransactionNumberDBName());

            foreach (DataRowView dr in GiftView)
            {
                dr.Delete();
            }
        }
        private void SetBatchLastGiftNumber()
        {
            DataView dv = new DataView(FMainDS.AGift);

            dv.RowFilter = String.Format("{0}={1}",
                                         AGiftTable.GetBatchNumberDBName(),
                                         FBatchNumber);

            dv.Sort = String.Format("{0} DESC",
                                    AGiftTable.GetGiftTransactionNumberDBName());

            dv.RowStateFilter = DataViewRowState.CurrentRows;

            if (dv.Count > 0)
            {
                AGiftRow transRow = (AGiftRow)dv[0].Row;
                FBatchRow.LastGiftNumber = transRow.GiftTransactionNumber;
            }
            else
            {
                FBatchRow.LastGiftNumber = 0;
            }
        }
示例#9
0
        public static bool GiftRevertAdjust(
            Int32 ALedgerNumber,
            Int32 ABatchNumber,
            Int32 AGiftDetailNumber,
            bool ABatchSelected,
            Int32 ANewBatchNumber,
            DateTime?ANewGLDateEffective,
            GiftAdjustmentFunctionEnum AFunction,
            bool ANoReceipt,
            Decimal ANewPct,
            out int AAdjustmentBatchNumber)
        {
            AAdjustmentBatchNumber = 0;
            int AdjustmentBatchNo = AAdjustmentBatchNumber;

            GiftBatchTDS GiftDS = new GiftBatchTDS();

            decimal batchGiftTotal = 0;

            ANewBatchNumber = ABatchSelected ? ANewBatchNumber : 0;

            TDBTransaction Transaction  = new TDBTransaction();
            TDataBase      db           = DBAccess.Connect("GiftRevertAdjust");
            bool           SubmissionOK = false;

            try
            {
                db.WriteTransaction(
                    ref Transaction,
                    ref SubmissionOK,
                    delegate
                {
                    // load the original gifts and gift details
                    AGiftAccess.LoadViaAGiftBatch(GiftDS, ALedgerNumber, ABatchNumber, Transaction);
                    AGiftDetailAccess.LoadViaAGiftBatch(GiftDS, ALedgerNumber, ABatchNumber, Transaction);

                    ALedgerTable ledgerTable = ALedgerAccess.LoadByPrimaryKey(ALedgerNumber, Transaction);

                    AGiftBatchRow giftBatch;

                    DateTime DateEffective;

                    if (ANewGLDateEffective.HasValue)
                    {
                        DateEffective = ANewGLDateEffective.Value;
                    }
                    else
                    {
                        AGiftBatchTable OriginalGiftBatch = AGiftBatchAccess.LoadByPrimaryKey(ALedgerNumber, ABatchNumber, Transaction);
                        DateEffective = OriginalGiftBatch[0].GlEffectiveDate;
                    }

                    // if we need to create a new gift batch
                    if (!ABatchSelected)
                    {
                        giftBatch = CreateNewGiftBatch(
                            ALedgerNumber,
                            ABatchNumber,
                            DateEffective,
                            AFunction,
                            ref GiftDS, ref ledgerTable, Transaction);
                    }
                    else     // using an existing gift batch
                    {
                        AGiftBatchAccess.LoadByPrimaryKey(GiftDS, ALedgerNumber, ANewBatchNumber, Transaction);

                        giftBatch     = GiftDS.AGiftBatch[0];
                        DateEffective = giftBatch.GlEffectiveDate;
                        //If into an existing batch, then retrieve the existing batch total
                        batchGiftTotal = giftBatch.BatchTotal;
                    }

                    AdjustmentBatchNo = giftBatch.BatchNumber;

                    //assuming new elements are added after these static borders

                    GiftDS.AGift.DefaultView.Sort = string.Format("{0}, {1}",
                                                                  AGiftTable.GetBatchNumberDBName(),
                                                                  AGiftTable.GetGiftTransactionNumberDBName());

                    GiftDS.AGiftDetail.DefaultView.Sort = string.Format("{0}, {1}, {2}",
                                                                        AGiftDetailTable.GetBatchNumberDBName(),
                                                                        AGiftDetailTable.GetGiftTransactionNumberDBName(),
                                                                        AGiftDetailTable.GetDetailNumberDBName());

                    foreach (DataRowView giftRow in GiftDS.AGift.DefaultView)
                    {
                        int cycle = 0;

                        // first cycle creates gift reversal; second cycle creates new adjusted gift (if needed)
                        do
                        {
                            AGiftRow oldGift = (AGiftRow)giftRow.Row;

                            if (oldGift.RowState != DataRowState.Added)
                            {
                                AGiftRow gift = GiftDS.AGift.NewRowTyped(true);
                                DataUtilities.CopyAllColumnValuesWithoutPK(oldGift, gift);
                                gift.LedgerNumber = giftBatch.LedgerNumber;
                                gift.BatchNumber  = giftBatch.BatchNumber;
                                // keep the same DateEntered as in the original gift if it is in the same period as the batch
                                if ((gift.DateEntered.Year != DateEffective.Year) || (gift.DateEntered.Month != DateEffective.Month))
                                {
                                    gift.DateEntered = DateEffective;
                                }
                                gift.GiftTransactionNumber = giftBatch.LastGiftNumber + 1;
                                giftBatch.LastGiftNumber++;
                                gift.LinkToPreviousGift = (cycle != 0);
                                gift.LastDetailNumber   = 0;
                                gift.FirstTimeGift      = false;

                                // do not print a receipt for reversed gifts
                                if (cycle == 0)
                                {
                                    gift.ReceiptPrinted = true;
                                    gift.PrintReceipt   = false;
                                }
                                else
                                {
                                    gift.ReceiptPrinted = false;
                                    gift.PrintReceipt   = !ANoReceipt;
                                }

                                GiftDS.AGift.Rows.Add(gift);

                                foreach (DataRowView giftDetailRow in GiftDS.AGiftDetail.DefaultView)
                                {
                                    AGiftDetailRow oldGiftDetail = (AGiftDetailRow)giftDetailRow.Row;

                                    // if gift detail belongs to gift
                                    if ((oldGiftDetail.GiftTransactionNumber == oldGift.GiftTransactionNumber) &&
                                        (oldGiftDetail.BatchNumber == oldGift.BatchNumber) &&
                                        (AFunction != GiftAdjustmentFunctionEnum.ReverseGiftDetail) ||
                                        (oldGiftDetail.DetailNumber == AGiftDetailNumber))
                                    {
                                        AddDuplicateGiftDetailToGift(ref GiftDS, ref gift, oldGiftDetail, cycle == 0, Transaction,
                                                                     AFunction,
                                                                     ANewPct);

                                        batchGiftTotal += ((cycle == 0) ? 0 : oldGiftDetail.GiftTransactionAmount);

                                        // original gift also gets marked as a reversal
                                        oldGiftDetail.ModifiedDetail = true;
                                    }
                                }
                            }

                            cycle++;
                        } while ((cycle < 2) &&
                                 (AFunction.Equals(GiftAdjustmentFunctionEnum.AdjustGift) ||
                                  AFunction.Equals(GiftAdjustmentFunctionEnum.FieldAdjust) ||
                                  AFunction.Equals(GiftAdjustmentFunctionEnum.TaxDeductiblePctAdjust)));
                    }

                    //When reversing into a new or existing batch, set batch total
                    giftBatch.BatchTotal = batchGiftTotal;

                    // save everything at the end
                    AGiftBatchAccess.SubmitChanges(GiftDS.AGiftBatch, Transaction);
                    ALedgerAccess.SubmitChanges(ledgerTable, Transaction);
                    AGiftAccess.SubmitChanges(GiftDS.AGift, Transaction);
                    AGiftDetailAccess.SubmitChanges(GiftDS.AGiftDetail, Transaction);

                    GiftDS.AGiftBatch.AcceptChanges();

                    SubmissionOK = true;
                });
            }
            catch (Exception ex)
            {
                TLogging.LogException(ex, Utilities.GetMethodSignature());
                throw new EOPAppException(Catalog.GetString("Gift Reverse/Adjust failed."), ex);
            }

            AAdjustmentBatchNumber = AdjustmentBatchNo;

            db.CloseDBConnection();

            return(SubmissionOK);
        }
示例#10
0
        private bool OnDeleteRowManual(GiftBatchTDSAGiftDetailRow ARowToDelete, ref string ACompletionMessage)
        {
            //TODO: Make this like deleton on GL Transactions form
            // e.g. pass copy to delete method on server...
            //GiftBatchTDS TempDS = (GiftBatchTDS)FMainDS.Copy();
            //TempDS.Merge(FMainDS);

            bool DeletionSuccessful = false;

            ACompletionMessage = string.Empty;

            if (FBatchRow == null)
            {
                FBatchRow = GetBatchRow();
            }

            if ((ARowToDelete == null) || (FBatchRow.BatchStatus != MFinanceConstants.BATCH_UNPOSTED))
            {
                return(false);
            }

            int  CurrentBatchNo   = ARowToDelete.BatchNumber;
            bool RowToDeleteIsNew = (ARowToDelete.RowState == DataRowState.Added);
            int  CurrentRowIndex  = GetSelectedRowIndex();

            TFrmGiftBatch FMyForm = (TFrmGiftBatch)this.ParentForm;

            GiftBatchTDS  BackupMainDS         = null;
            List <string> OriginatingDetailRef = new List <string>();

            int    SelectedDetailNumber        = ARowToDelete.DetailNumber;
            int    GiftToDeleteTransNo         = 0;
            string FilterAllGiftsOfBatch       = String.Empty;
            string FilterAllGiftDetailsOfBatch = String.Empty;

            int DetailRowCount = FGiftDetailView.Count;

            try
            {
                this.Cursor = Cursors.WaitCursor;
                //Specify current action
                FMyForm.FCurrentGiftBatchAction = Logic.TExtraGiftBatchChecks.GiftBatchAction.DELETINGTRANS;
                //Speeds up deletion of larger gift sets
                FMainDS.EnforceConstraints = false;
                // temporarily disable  New Donor Warning
                FMyForm.NewDonorWarning = false;

                //Backup the Dataset for reversion purposes
                BackupMainDS = (GiftBatchTDS)FMainDS.GetChangesTyped(false);

                //Don't run an inactive fields check on this batch
                FMyForm.GetBatchControl().UpdateUnpostedBatchDictionary(CurrentBatchNo);

                if ((ARowToDelete.ModifiedDetailKey != null) && (ARowToDelete.ModifiedDetailKey.Length > 0))
                {
                    OriginatingDetailRef.Add(ARowToDelete.ModifiedDetailKey);
                }

                //Delete current row
                ARowToDelete.RejectChanges();

                if (!RowToDeleteIsNew)
                {
                    ShowDetails(ARowToDelete);
                }

                ARowToDelete.Delete();

                //If there existed (before the delete row above) more than one detail row, then no need to delete gift header row
                if (DetailRowCount > 1)
                {
                    ACompletionMessage = Catalog.GetString("Gift Detail row deleted successfully!");

                    FGiftSelectedForDeletionFlag = false;

                    foreach (DataRowView rv in FGiftDetailView)
                    {
                        GiftBatchTDSAGiftDetailRow row = (GiftBatchTDSAGiftDetailRow)rv.Row;

                        if (row.DetailNumber > SelectedDetailNumber)
                        {
                            row.DetailNumber--;
                        }
                    }

                    FGift.LastDetailNumber--;
                }
                else
                {
                    ACompletionMessage = Catalog.GetString("Gift deleted successfully!");

                    GiftToDeleteTransNo = FGift.GiftTransactionNumber;

                    // Reduce all Gift Detail row Transaction numbers by 1 if they are greater then gift to be deleted
                    FilterAllGiftDetailsOfBatch = String.Format("{0}={1} And {2}>{3}",
                                                                AGiftDetailTable.GetBatchNumberDBName(),
                                                                FBatchNumber,
                                                                AGiftDetailTable.GetGiftTransactionNumberDBName(),
                                                                GiftToDeleteTransNo);

                    DataView giftDetailView = new DataView(FMainDS.AGiftDetail);
                    giftDetailView.RowFilter = FilterAllGiftDetailsOfBatch;
                    giftDetailView.Sort      = String.Format("{0} ASC", AGiftDetailTable.GetGiftTransactionNumberDBName());

                    foreach (DataRowView rv in giftDetailView)
                    {
                        GiftBatchTDSAGiftDetailRow row = (GiftBatchTDSAGiftDetailRow)rv.Row;

                        row.GiftTransactionNumber--;
                    }

                    //Cannot delete the gift row, just copy the data of rows above down by 1 row
                    // and then mark the top row for deletion
                    //In other words, bubble the gift row to be deleted to the top
                    FilterAllGiftsOfBatch = String.Format("{0}={1} And {2}>={3}",
                                                          AGiftTable.GetBatchNumberDBName(),
                                                          FBatchNumber,
                                                          AGiftTable.GetGiftTransactionNumberDBName(),
                                                          GiftToDeleteTransNo);

                    DataView giftView = new DataView(FMainDS.AGift);
                    giftView.RowFilter = FilterAllGiftsOfBatch;
                    giftView.Sort      = String.Format("{0} ASC", AGiftTable.GetGiftTransactionNumberDBName());

                    AGiftRow giftRowToReceive  = null;
                    AGiftRow giftRowToCopyDown = null;
                    AGiftRow giftRowCurrent    = null;

                    int currentGiftTransNo = 0;

                    foreach (DataRowView gv in giftView)
                    {
                        giftRowCurrent = (AGiftRow)gv.Row;

                        currentGiftTransNo = giftRowCurrent.GiftTransactionNumber;

                        if (currentGiftTransNo > GiftToDeleteTransNo)
                        {
                            giftRowToCopyDown = giftRowCurrent;

                            //Copy column values down
                            for (int j = 3; j < giftRowToCopyDown.Table.Columns.Count; j++)
                            {
                                //Update all columns except the pk fields that remain the same
                                if (!giftRowToCopyDown.Table.Columns[j].ColumnName.EndsWith("_text"))
                                {
                                    giftRowToReceive[j] = giftRowToCopyDown[j];
                                }
                            }
                        }

                        if (currentGiftTransNo == FBatchRow.LastGiftNumber)
                        {
                            //Mark last record for deletion
                            giftRowCurrent.GiftStatus = MFinanceConstants.MARKED_FOR_DELETION;
                        }

                        //Will always be previous row
                        giftRowToReceive = giftRowCurrent;
                    }

                    FPreviouslySelectedDetailRow = null;
                    FGiftSelectedForDeletionFlag = true;
                    FBatchRow.LastGiftNumber--;
                }

                //Save and check for inactive values and ex-workers and anonymous gifts
                //  in other unsaved Batches
                FPetraUtilsObject.SetChangedFlag();

                if (!FMyForm.SaveChangesManual(Logic.TExtraGiftBatchChecks.GiftBatchAction.DELETINGTRANS, false, false))
                {
                    FMyForm.GetBatchControl().UpdateUnpostedBatchDictionary();

                    MessageBox.Show(Catalog.GetString("The gift detail has been deleted but the changes are not saved!"),
                                    Catalog.GetString("Deletion Warning"),
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Warning);

                    ACompletionMessage = string.Empty;

                    if (FGiftSelectedForDeletionFlag)
                    {
                        FGiftSelectedForDeletionFlag = false;
                        SetBatchLastGiftNumber();
                        UpdateControlsProtection();
                    }

                    UpdateTotals();

                    return(false);
                }

                //Check if have deleted a reversing gift detail
                if (OriginatingDetailRef.Count > 0)
                {
                    TRemote.MFinance.Gift.WebConnectors.ReversedGiftReset(FLedgerNumber, OriginatingDetailRef);
                }

                //Clear current batch's gift data and reload from server
                RefreshBatchGiftData(FBatchNumber, true);

                DeletionSuccessful = true;
            }
            catch (Exception ex)
            {
                //Revert to previous state
                RevertDataSet(FMainDS, BackupMainDS, CurrentRowIndex);

                TLogging.LogException(ex, Utilities.GetMethodSignature());
                throw;
            }
            finally
            {
                FMyForm.NewDonorWarning         = true;
                FMainDS.EnforceConstraints      = true;
                FMyForm.FCurrentGiftBatchAction = Logic.TExtraGiftBatchChecks.GiftBatchAction.NONE;
                this.Cursor = Cursors.Default;
            }

            SetGiftDetailDefaultView();
            FFilterAndFindObject.ApplyFilter();
            UpdateRecordNumberDisplay();

            return(DeletionSuccessful);
        }
示例#11
0
        public static bool GiftRevertAdjust(Hashtable requestParams, out TVerificationResultCollection AMessages)
        {
            AMessages = new TVerificationResultCollection();

            Int32   ALedgerNumber   = (Int32)requestParams["ALedgerNumber"];
            Boolean batchSelected   = (Boolean)requestParams["NewBatchSelected"];
            Int32   ANewBatchNumber = 0;

            bool TaxDeductiblePercentageEnabled = Convert.ToBoolean(
                TSystemDefaults.GetSystemDefault(SharedConstants.SYSDEFAULT_TAXDEDUCTIBLEPERCENTAGE, "FALSE"));

            if (batchSelected)
            {
                ANewBatchNumber = (Int32)requestParams["NewBatchNumber"];
            }

            String Function          = (String)requestParams["Function"];
            Int32  AGiftDetailNumber = (Int32)requestParams["GiftDetailNumber"];
            Int32  AGiftNumber       = (Int32)requestParams["GiftNumber"];
            Int32  ABatchNumber      = (Int32)requestParams["BatchNumber"];

            //decimal batchHashTotal = 0;
            decimal batchGiftTotal = 0;

            GiftBatchTDS   MainDS      = new GiftBatchTDS();
            TDBTransaction Transaction = null;
            DateTime       ADateEffective;

            Transaction = DBAccess.GDBAccessObj.BeginTransaction(IsolationLevel.Serializable);

            try
            {
                ALedgerTable LedgerTable = ALedgerAccess.LoadByPrimaryKey(ALedgerNumber, Transaction);

                AGiftBatchRow giftBatch;

                if (!batchSelected)
                {
                    ADateEffective = (DateTime)requestParams["GlEffectiveDate"];

                    AGiftBatchAccess.LoadByPrimaryKey(MainDS, ALedgerNumber, ABatchNumber, Transaction);

                    AGiftBatchRow oldGiftBatch = MainDS.AGiftBatch[0];
                    TGiftBatchFunctions.CreateANewGiftBatchRow(ref MainDS, ref Transaction, ref LedgerTable, ALedgerNumber, ADateEffective);
                    giftBatch = MainDS.AGiftBatch[1];
                    giftBatch.BankAccountCode     = oldGiftBatch.BankAccountCode;
                    giftBatch.BankCostCentre      = oldGiftBatch.BankCostCentre;
                    giftBatch.CurrencyCode        = oldGiftBatch.CurrencyCode;
                    giftBatch.ExchangeRateToBase  = oldGiftBatch.ExchangeRateToBase;
                    giftBatch.MethodOfPaymentCode = oldGiftBatch.MethodOfPaymentCode;
                    giftBatch.HashTotal           = 0;

                    if (giftBatch.MethodOfPaymentCode.Length == 0)
                    {
                        giftBatch.SetMethodOfPaymentCodeNull();
                    }

                    giftBatch.BankCostCentre = oldGiftBatch.BankCostCentre;
                    giftBatch.GiftType       = oldGiftBatch.GiftType;

                    if (Function.Equals("AdjustGift"))
                    {
                        giftBatch.BatchDescription = Catalog.GetString("Gift Adjustment");
                    }
                    else
                    {
                        giftBatch.BatchDescription = Catalog.GetString("Reverse Gift");
                    }
                }
                else
                {
                    AGiftBatchAccess.LoadByPrimaryKey(MainDS, ALedgerNumber, ANewBatchNumber, Transaction);

                    giftBatch      = MainDS.AGiftBatch[0];
                    ADateEffective = giftBatch.GlEffectiveDate;
                    //If into an existing batch, then retrive the existing batch total
                    batchGiftTotal = giftBatch.BatchTotal;
                }

                if (Function.Equals("ReverseGiftBatch"))
                {
                    AGiftAccess.LoadViaAGiftBatch(MainDS, ALedgerNumber, ABatchNumber, Transaction);

                    foreach (AGiftRow gift in MainDS.AGift.Rows)
                    {
                        AGiftDetailAccess.LoadViaAGift(MainDS, ALedgerNumber, ABatchNumber, gift.GiftTransactionNumber, Transaction);
                    }
                }
                else
                {
                    AGiftAccess.LoadByPrimaryKey(MainDS, ALedgerNumber, ABatchNumber, AGiftNumber, Transaction);

                    if (Function.Equals("ReverseGiftDetail"))
                    {
                        AGiftDetailAccess.LoadByPrimaryKey(MainDS, ALedgerNumber, ABatchNumber, AGiftNumber, AGiftDetailNumber, Transaction);
                    }
                    else
                    {
                        AGiftDetailAccess.LoadViaAGift(MainDS, ALedgerNumber, ABatchNumber, AGiftNumber, Transaction);
                    }
                }

                //assuming new elements are added after these static borders

                int cycle = 0;

                MainDS.AGift.DefaultView.Sort = string.Format("{0}, {1}",
                                                              AGiftTable.GetBatchNumberDBName(),
                                                              AGiftTable.GetGiftTransactionNumberDBName());

                MainDS.AGiftDetail.DefaultView.Sort = string.Format("{0}, {1}, {2}",
                                                                    AGiftDetailTable.GetBatchNumberDBName(),
                                                                    AGiftDetailTable.GetGiftTransactionNumberDBName(),
                                                                    AGiftDetailTable.GetDetailNumberDBName());

                do
                {
                    foreach (DataRowView giftRow in MainDS.AGift.DefaultView)
                    {
                        AGiftRow oldGift = (AGiftRow)giftRow.Row;

                        if ((oldGift.BatchNumber == ABatchNumber) && (oldGift.LedgerNumber == ALedgerNumber) &&
                            (Function.Equals("ReverseGiftBatch") || (oldGift.GiftTransactionNumber == AGiftNumber)))
                        {
                            AGiftRow gift = MainDS.AGift.NewRowTyped(true);
                            DataUtilities.CopyAllColumnValuesWithoutPK(oldGift, gift);
                            gift.LedgerNumber          = giftBatch.LedgerNumber;
                            gift.BatchNumber           = giftBatch.BatchNumber;
                            gift.DateEntered           = ADateEffective;
                            gift.GiftTransactionNumber = giftBatch.LastGiftNumber + 1;
                            giftBatch.LastGiftNumber++;
                            gift.LastDetailNumber = 0;

                            MainDS.AGift.Rows.Add(gift);

                            foreach (DataRowView giftDetailRow in MainDS.AGiftDetail.DefaultView)
                            {
                                AGiftDetailRow oldGiftDetail = (AGiftDetailRow)giftDetailRow.Row;

                                if ((oldGiftDetail.GiftTransactionNumber == oldGift.GiftTransactionNumber) &&
                                    (oldGiftDetail.BatchNumber == ABatchNumber) &&
                                    (oldGiftDetail.LedgerNumber == ALedgerNumber) &&
                                    (!Function.Equals("ReverseGiftDetail") || (oldGiftDetail.DetailNumber == AGiftDetailNumber)))
                                {
                                    if ((cycle == 0) && oldGiftDetail.ModifiedDetail)
                                    {
                                        AMessages.Add(new TVerificationResult(
                                                          String.Format(Catalog.GetString("Cannot reverse or adjust Gift {0} with Detail {1} in Batch {2}"),
                                                                        oldGiftDetail.GiftTransactionNumber, oldGiftDetail.DetailNumber, oldGiftDetail.BatchNumber),
                                                          String.Format(Catalog.GetString("It was already adjusted or reversed.")),
                                                          TResultSeverity.Resv_Critical));

                                        DBAccess.GDBAccessObj.RollbackTransaction();

                                        return(false);
                                    }

                                    AGiftDetailRow giftDetail = MainDS.AGiftDetail.NewRowTyped(true);
                                    DataUtilities.CopyAllColumnValuesWithoutPK(oldGiftDetail, giftDetail);

                                    giftDetail.DetailNumber = ++gift.LastDetailNumber;

                                    giftDetail.LedgerNumber          = gift.LedgerNumber;
                                    giftDetail.BatchNumber           = giftBatch.BatchNumber;
                                    giftDetail.GiftTransactionNumber = gift.GiftTransactionNumber;
                                    //Identify the reversal source
                                    giftDetail.ModifiedDetailKey = "|" + oldGiftDetail.BatchNumber.ToString() + "|" +
                                                                   oldGiftDetail.GiftTransactionNumber.ToString() + "|" +
                                                                   oldGiftDetail.DetailNumber.ToString();

                                    decimal signum = (cycle == 0) ? -1 : 1;
                                    giftDetail.GiftTransactionAmount = signum * oldGiftDetail.GiftTransactionAmount;
                                    batchGiftTotal           += giftDetail.GiftTransactionAmount;
                                    giftDetail.GiftAmount     = signum * oldGiftDetail.GiftAmount;
                                    giftDetail.GiftAmountIntl = signum * oldGiftDetail.GiftAmountIntl;

                                    if (TaxDeductiblePercentageEnabled)
                                    {
                                        giftDetail.TaxDeductibleAmount     = signum * oldGiftDetail.TaxDeductibleAmount;
                                        giftDetail.TaxDeductibleAmountBase = signum * oldGiftDetail.TaxDeductibleAmountBase;
                                        giftDetail.TaxDeductibleAmountIntl = signum * oldGiftDetail.TaxDeductibleAmountIntl;
                                        giftDetail.NonDeductibleAmount     = signum * oldGiftDetail.NonDeductibleAmount;
                                        giftDetail.NonDeductibleAmountBase = signum * oldGiftDetail.NonDeductibleAmountBase;
                                        giftDetail.NonDeductibleAmountIntl = signum * oldGiftDetail.NonDeductibleAmountIntl;
                                    }

                                    giftDetail.GiftCommentOne   = (String)requestParams["ReversalCommentOne"];
                                    giftDetail.GiftCommentTwo   = (String)requestParams["ReversalCommentTwo"];
                                    giftDetail.GiftCommentThree = (String)requestParams["ReversalCommentThree"];
                                    giftDetail.CommentOneType   = (String)requestParams["ReversalCommentOneType"];
                                    giftDetail.CommentTwoType   = (String)requestParams["ReversalCommentTwoType"];
                                    giftDetail.CommentThreeType = (String)requestParams["ReversalCommentThreeType"];

                                    // This is used to mark both as a Reverted giftDetails, except the adjusted (new) gift

                                    giftDetail.ModifiedDetail    = (cycle == 0);
                                    oldGiftDetail.ModifiedDetail = (cycle == 0);
                                    MainDS.AGiftDetail.Rows.Add(giftDetail);
                                }
                            }
                        }
                    }

                    cycle++;
                } while ((cycle < 2) && Function.Equals("AdjustGift"));

                //When reversing into a new or existing batch, set batch total
                if (!Function.Equals("AdjustGift"))
                {
                    giftBatch.BatchTotal = batchGiftTotal;
                }

                // save everything at the end
                AGiftBatchAccess.SubmitChanges(MainDS.AGiftBatch, Transaction);

                ALedgerAccess.SubmitChanges(LedgerTable, Transaction);

                AGiftAccess.SubmitChanges(MainDS.AGift, Transaction);

                AGiftDetailAccess.SubmitChanges(MainDS.AGiftDetail, Transaction);

                MainDS.AGiftBatch.AcceptChanges();

                DBAccess.GDBAccessObj.CommitTransaction();

                return(true);
            }
            catch (Exception Exc)
            {
                TLogging.Log("An Exception occured while performing Gift Reverse/Adjust:" + Environment.NewLine + Exc.ToString());

                DBAccess.GDBAccessObj.RollbackTransaction();

                throw new EOPAppException(Catalog.GetString("Gift Reverse/Adjust failed."), Exc);
            }
        }
        /// <summary>
        /// Clear the gift data of the current batch without marking records for delete
        /// </summary>
        private bool RefreshBatchGiftData(Int32 ABatchNumber,
                                          bool AAcceptChanges       = false,
                                          bool AHandleDataSetBackup = false)
        {
            bool RetVal = false;

            //Copy and backup the current dataset
            GiftBatchTDS BackupDS = null;
            GiftBatchTDS TempDS   = (GiftBatchTDS)FMainDS.Copy();

            TempDS.Merge(FMainDS);

            if (AHandleDataSetBackup)
            {
                BackupDS = (GiftBatchTDS)FMainDS.GetChangesTyped(false);
            }

            try
            {
                this.Cursor = Cursors.WaitCursor;

                //Remove current batch gift data
                DataView giftDetailView = new DataView(TempDS.AGiftDetail);

                giftDetailView.RowFilter = String.Format("{0}={1}",
                                                         AGiftDetailTable.GetBatchNumberDBName(),
                                                         ABatchNumber);

                giftDetailView.Sort = String.Format("{0} DESC, {1} DESC",
                                                    AGiftDetailTable.GetGiftTransactionNumberDBName(),
                                                    AGiftDetailTable.GetDetailNumberDBName());

                foreach (DataRowView dr in giftDetailView)
                {
                    dr.Delete();
                }

                DataView giftView = new DataView(TempDS.AGift);

                giftView.RowFilter = String.Format("{0}={1}",
                                                   AGiftTable.GetBatchNumberDBName(),
                                                   ABatchNumber);

                giftView.Sort = String.Format("{0} DESC",
                                              AGiftTable.GetGiftTransactionNumberDBName());

                foreach (DataRowView dr in giftView)
                {
                    dr.Delete();
                }

                TempDS.AcceptChanges();

                //Clear all gift data from Main dataset gift tables
                FMainDS.AGiftDetail.Clear();
                FMainDS.AGift.Clear();

                //Bring data back in from other batches if it exists
                if (TempDS.AGift.Count > 0)
                {
                    FMainDS.AGift.Merge(TempDS.AGift);
                    FMainDS.AGiftDetail.Merge(TempDS.AGiftDetail);
                }

                //TODO: Confirm I need to AcceptChanges
                FMainDS.Merge(TRemote.MFinance.Gift.WebConnectors.LoadGiftTransactionsForBatch(FLedgerNumber, ABatchNumber));

                if (AAcceptChanges)
                {
                    FMainDS.AcceptChanges();
                }

                RetVal = true;
            }
            catch (Exception ex)
            {
                //If not revert on error then calling method will
                if (AHandleDataSetBackup)
                {
                    RevertDataSet(FMainDS, BackupDS);
                }

                TLogging.LogException(ex, Utilities.GetMethodSignature());
                throw;
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }

            return(RetVal);
        }
示例#13
0
        /// <summary>
        /// export all the Data of the batches matching the parameters to a String
        /// </summary>
        /// <param name="ARequestParams">Hashtable containing the given params </param>
        /// <param name="AExportString">Big parts of the export file as a simple String</param>
        /// <param name="AVerificationMessages">Additional messages to display in a messagebox</param>
        /// <returns>number of exported batches, -1 if cancelled, -2 if error</returns>
        public Int32 ExportAllGiftBatchData(
            Hashtable ARequestParams,
            out String AExportString,
            out TVerificationResultCollection AVerificationMessages)
        {
            //Return number of exported batches, -1 if cancelled, -2 if error
            int ReturnGiftBatchCount = 0;

            FStringWriter     = new StringWriter();
            FMainDS           = new GiftBatchTDS();
            FDelimiter        = (String)ARequestParams["Delimiter"];
            FLedgerNumber     = (Int32)ARequestParams["ALedgerNumber"];
            FDateFormatString = (String)ARequestParams["DateFormatString"];
            Boolean Summary = (Boolean)ARequestParams["Summary"];

            FUseBaseCurrency = (Boolean)ARequestParams["bUseBaseCurrency"];
            FDateForSummary  = (DateTime)ARequestParams["DateForSummary"];
            String NumberFormat = (String)ARequestParams["NumberFormat"];

            FCultureInfo      = new CultureInfo(NumberFormat.Equals("American") ? "en-US" : "de-DE");
            FTransactionsOnly = (Boolean)ARequestParams["TransactionsOnly"];
            FExtraColumns     = (Boolean)ARequestParams["ExtraColumns"];
            Int64  recipientNumber = (Int64)ARequestParams["RecipientNumber"];
            String RecipientFilter = (recipientNumber != 0) ? " AND PUB_a_gift_detail.p_recipient_key_n = " + recipientNumber : "";

            Int64  fieldNumber = (Int64)ARequestParams["FieldNumber"];
            String FieldFilter = (fieldNumber != 0) ? " AND PUB_a_gift_detail.a_recipient_ledger_number_n = " + fieldNumber : "";

            Boolean IncludeUnposted = (Boolean)ARequestParams["IncludeUnposted"];
            String  StatusFilter    =
                (IncludeUnposted) ? " AND (PUB_a_gift_batch.a_batch_status_c = 'Posted' OR PUB_a_gift_batch.a_batch_status_c = 'Unposted')"
                : " AND PUB_a_gift_batch.a_batch_status_c = 'Posted'";

            try
            {
                DBAccess.GDBAccessObj.BeginAutoReadTransaction(IsolationLevel.ReadCommitted,
                                                               ref FTransaction,
                                                               delegate
                {
                    try
                    {
                        ALedgerAccess.LoadByPrimaryKey(FMainDS, FLedgerNumber, FTransaction);
                        String BatchRangeFilter = (ARequestParams.ContainsKey(
                                                       "BatchNumberStart")) ?
                                                  " AND (PUB_a_gift_batch.a_batch_number_i >= " + (Int32)ARequestParams["BatchNumberStart"] +
                                                  " AND PUB_a_gift_batch.a_batch_number_i <= " + (Int32)ARequestParams["BatchNumberEnd"] +
                                                  ")" : "";

                        // If I've specified a BatchRange, I can't also have a DateRange:
                        String DateRangeFilter = (BatchRangeFilter == "") ?
                                                 " AND (PUB_a_gift_batch.a_gl_effective_date_d >= '" +
                                                 ((DateTime)ARequestParams["BatchDateFrom"]).ToString(
                            "yyyy-MM-dd") +
                                                 "' AND PUB_a_gift_batch.a_gl_effective_date_d <= '" +
                                                 ((DateTime)ARequestParams["BatchDateTo"]).ToString("yyyy-MM-dd") +
                                                 "')" : "";

                        string StatementCore =
                            " FROM PUB_a_gift_batch, PUB_a_gift, PUB_a_gift_detail" +
                            " WHERE PUB_a_gift_batch.a_ledger_number_i = " + FLedgerNumber +
                            RecipientFilter +
                            FieldFilter +
                            DateRangeFilter +
                            BatchRangeFilter +
                            StatusFilter +
                            " AND PUB_a_gift.a_ledger_number_i =  PUB_a_gift_batch.a_ledger_number_i" +
                            " AND PUB_a_gift.a_batch_number_i = PUB_a_gift_batch.a_batch_number_i" +
                            " AND PUB_a_gift_detail.a_ledger_number_i = PUB_a_gift_batch.a_ledger_number_i" +
                            " AND PUB_a_gift_detail.a_batch_number_i = PUB_a_gift_batch.a_batch_number_i" +
                            " AND PUB_a_gift_detail.a_gift_transaction_number_i = PUB_a_gift.a_gift_transaction_number_i";

                        string sqlStatement = "SELECT DISTINCT PUB_a_gift_batch.* " +
                                              StatementCore +
                                              " ORDER BY " + AGiftBatchTable.GetBatchNumberDBName();

                        TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(),
                                                         Catalog.GetString("Retrieving gift batch records"),
                                                         5);

                        if (TProgressTracker.GetCurrentState(DomainManager.GClientID.ToString()).CancelJob == true)
                        {
                            TProgressTracker.FinishJob(DomainManager.GClientID.ToString());
                            throw new ApplicationException(Catalog.GetString("Export of Batches was cancelled by user"));
                        }

                        DBAccess.GDBAccessObj.Select(FMainDS,
                                                     sqlStatement,
                                                     FMainDS.AGiftBatch.TableName,
                                                     FTransaction
                                                     );


                        TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(),
                                                         Catalog.GetString("Retrieving gift records"),
                                                         10);

                        if (TProgressTracker.GetCurrentState(DomainManager.GClientID.ToString()).CancelJob == true)
                        {
                            TProgressTracker.FinishJob(DomainManager.GClientID.ToString());
                            throw new ApplicationException(Catalog.GetString("Export of Batches was cancelled by user"));
                        }

                        sqlStatement = "SELECT DISTINCT PUB_a_gift.* " +
                                       StatementCore +
                                       " ORDER BY " + AGiftBatchTable.GetBatchNumberDBName() +
                                       ", " +
                                       AGiftTable.GetGiftTransactionNumberDBName();

                        DBAccess.GDBAccessObj.Select(FMainDS,
                                                     sqlStatement,
                                                     FMainDS.AGift.TableName,
                                                     FTransaction);


                        TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(),
                                                         Catalog.GetString("Retrieving gift detail records"),
                                                         15);

                        if (TProgressTracker.GetCurrentState(DomainManager.GClientID.ToString()).CancelJob == true)
                        {
                            TProgressTracker.FinishJob(DomainManager.GClientID.ToString());
                            throw new ApplicationException(Catalog.GetString("Export of Batches was cancelled by user"));
                        }

                        sqlStatement = "SELECT DISTINCT PUB_a_gift_detail.* " + StatementCore;

                        DBAccess.GDBAccessObj.Select(FMainDS,
                                                     sqlStatement,
                                                     FMainDS.AGiftDetail.TableName,
                                                     FTransaction);
                    }
                    catch (Exception ex)
                    {
                        TLogging.LogException(ex, Utilities.GetMethodSignature());
                        throw;
                    }
                });

                TProgressTracker.InitProgressTracker(DomainManager.GClientID.ToString(),
                                                     Catalog.GetString("Exporting Gift Batches"), 100);

                TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(),
                                                 Catalog.GetString("Retrieving records"),
                                                 5);

                string BaseCurrency = FMainDS.ALedger[0].BaseCurrency;
                FCurrencyCode = BaseCurrency; // Depending on FUseBaseCurrency, this will be overwritten for each gift.

                SortedDictionary <String, AGiftSummaryRow> sdSummary = new SortedDictionary <String, AGiftSummaryRow>();

                UInt32 counter = 0;

                // TProgressTracker Variables
                UInt32 GiftCounter = 0;

                AGiftSummaryRow giftSummary = null;

                FMainDS.AGiftDetail.DefaultView.Sort =
                    AGiftDetailTable.GetLedgerNumberDBName() + "," +
                    AGiftDetailTable.GetBatchNumberDBName() + "," +
                    AGiftDetailTable.GetGiftTransactionNumberDBName();

                foreach (AGiftBatchRow giftBatch in FMainDS.AGiftBatch.Rows)
                {
                    if (TProgressTracker.GetCurrentState(DomainManager.GClientID.ToString()).CancelJob == true)
                    {
                        TProgressTracker.FinishJob(DomainManager.GClientID.ToString());
                        throw new ApplicationException(Catalog.GetString("Export of Batches was cancelled by user"));
                    }

                    ReturnGiftBatchCount++;

                    TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(),
                                                     string.Format(Catalog.GetString("Batch {0}"), giftBatch.BatchNumber),
                                                     20);
                    GiftCounter = 0;

                    if (!FTransactionsOnly & !Summary)
                    {
                        WriteGiftBatchLine(giftBatch);
                    }

                    foreach (AGiftRow gift in FMainDS.AGift.Rows)
                    {
                        if (gift.BatchNumber.Equals(giftBatch.BatchNumber) && gift.LedgerNumber.Equals(giftBatch.LedgerNumber))
                        {
                            if (TProgressTracker.GetCurrentState(DomainManager.GClientID.ToString()).CancelJob == true)
                            {
                                TProgressTracker.FinishJob(DomainManager.GClientID.ToString());
                                throw new ApplicationException(Catalog.GetString("Export of Batches was cancelled by user"));
                            }

                            // Update progress tracker every 25 records
                            if (++GiftCounter % 25 == 0)
                            {
                                TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(),
                                                                 string.Format(Catalog.GetString("Batch {0} - Exporting gifts"), giftBatch.BatchNumber),
                                                                 (GiftCounter / 25 + 4) * 5 > 90 ? 90 : (GiftCounter / 25 + 4) * 5);
                            }

                            DataRowView[] selectedRowViews = FMainDS.AGiftDetail.DefaultView.FindRows(
                                new object[] { gift.LedgerNumber, gift.BatchNumber, gift.GiftTransactionNumber });

                            foreach (DataRowView rv in selectedRowViews)
                            {
                                AGiftDetailRow giftDetail = (AGiftDetailRow)rv.Row;

                                if (Summary)
                                {
                                    FCurrencyCode = FUseBaseCurrency ? BaseCurrency : giftBatch.CurrencyCode;
                                    decimal mapExchangeRateToBase = FUseBaseCurrency ? 1 : giftBatch.ExchangeRateToBase;


                                    counter++;
                                    String DictionaryKey = FCurrencyCode + ";" + giftBatch.BankCostCentre + ";" + giftBatch.BankAccountCode + ";" +
                                                           giftDetail.RecipientKey + ";" + giftDetail.MotivationGroupCode + ";" +
                                                           giftDetail.MotivationDetailCode;

                                    if (sdSummary.TryGetValue(DictionaryKey, out giftSummary))
                                    {
                                        giftSummary.GiftTransactionAmount += giftDetail.GiftTransactionAmount;
                                        giftSummary.GiftAmount            += giftDetail.GiftAmount;
                                    }
                                    else
                                    {
                                        giftSummary = new AGiftSummaryRow();

                                        /*
                                         * summary_data.a_transaction_currency_c = lv_stored_currency_c
                                         * summary_data.a_bank_cost_centre_c = a_gift_batch.a_bank_cost_centre_c
                                         * summary_data.a_bank_account_code_c = a_gift_batch.a_bank_account_code_c
                                         * summary_data.a_recipient_key_n = a_gift_detail.p_recipient_key_n
                                         * summary_data.a_motivation_group_code_c = a_gift_detail.a_motivation_group_code_c
                                         * summary_data.a_motivation_detail_code_c = a_gift_detail.a_motivation_detail_code_c
                                         * summary_data.a_exchange_rate_to_base_n = lv_exchange_rate_n
                                         * summary_data.a_gift_type_c = a_gift_batch.a_gift_type_c */
                                        giftSummary.CurrencyCode          = FCurrencyCode;
                                        giftSummary.BankCostCentre        = giftBatch.BankCostCentre;
                                        giftSummary.BankAccountCode       = giftBatch.BankAccountCode;
                                        giftSummary.RecipientKey          = giftDetail.RecipientKey;
                                        giftSummary.MotivationGroupCode   = giftDetail.MotivationGroupCode;
                                        giftSummary.MotivationDetailCode  = giftDetail.MotivationDetailCode;
                                        giftSummary.GiftTransactionAmount = giftDetail.GiftTransactionAmount;
                                        giftSummary.GiftAmount            = giftDetail.GiftAmount;

                                        sdSummary.Add(DictionaryKey, giftSummary);
                                    }

                                    //overwrite always because we want to have the last
                                    giftSummary.ExchangeRateToBase = mapExchangeRateToBase;
                                }
                                else  // not summary
                                {
                                    WriteGiftLine(gift, giftDetail);
                                }
                            }
                        }
                    }
                }

                if (Summary)
                {
                    TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(),
                                                     Catalog.GetString("Export Summary"),
                                                     95);

                    bool first = true;

                    foreach (KeyValuePair <string, AGiftSummaryRow> kvp in sdSummary)
                    {
                        if (!FTransactionsOnly && first)
                        {
                            WriteGiftBatchSummaryLine(kvp.Value);
                            first = false;
                        }

                        WriteGiftSummaryLine(kvp.Value);
                    }
                }

                TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(),
                                                 Catalog.GetString("Gift batch export successful"),
                                                 100);

                TProgressTracker.FinishJob(DomainManager.GClientID.ToString());
            }
            catch (ApplicationException)
            {
                //Show cancel condition
                ReturnGiftBatchCount = -1;
                TProgressTracker.CancelJob(DomainManager.GClientID.ToString());
            }
            catch (Exception ex)
            {
                TLogging.Log(ex.ToString());

                //Show error condition
                ReturnGiftBatchCount = -2;

                FMessages.Add(new TVerificationResult(
                                  "Exporting Gift Batches Terminated Unexpectedly",
                                  ex.Message,
                                  "An unexpected error occurred during the export of gift batches",
                                  string.Empty,
                                  TResultSeverity.Resv_Critical,
                                  Guid.Empty));

                TProgressTracker.CancelJob(DomainManager.GClientID.ToString());
            }

            if (ReturnGiftBatchCount > 0)
            {
                AExportString = FStringWriter.ToString();
            }
            else
            {
                AExportString = string.Empty;
            }

            AVerificationMessages = FMessages;

            return(ReturnGiftBatchCount);
        } // ExportAllGiftBatchData
示例#14
0
        /// <summary>
        /// Get Unsaved Batch Rows in a list
        /// </summary>
        /// <param name="ABatchToInclude">If > 0 then include in list even if unchanged</param>
        /// <returns></returns>
        public List <AGiftBatchRow> GetUnsavedBatchRowsList(int ABatchToInclude = 0)
        {
            List <AGiftBatchRow> RetVal = new List <AGiftBatchRow>();
            List <int>           BatchesWithChangesList = new List <int>();
            string BatchesWithChangesString             = string.Empty;

            DataView GiftBatchesDV = new DataView(FMainDS.AGiftBatch);

            GiftBatchesDV.RowFilter = String.Format("{0}='{1}'",
                                                    AGiftBatchTable.GetBatchStatusDBName(),
                                                    MFinanceConstants.BATCH_UNPOSTED);
            GiftBatchesDV.Sort = AGiftBatchTable.GetBatchNumberDBName() + " ASC";

            DataView GiftDV        = new DataView(FMainDS.AGift);
            DataView GiftDetailsDV = new DataView(FMainDS.AGiftDetail);

            GiftDV.Sort = String.Format("{0} ASC, {1} ASC",
                                        AGiftTable.GetBatchNumberDBName(),
                                        AGiftTable.GetGiftTransactionNumberDBName());

            GiftDetailsDV.Sort = String.Format("{0} ASC, {1} ASC, {2} ASC",
                                               AGiftDetailTable.GetBatchNumberDBName(),
                                               AGiftDetailTable.GetGiftTransactionNumberDBName(),
                                               AGiftDetailTable.GetDetailNumberDBName());

            //Add the batch number(s) of changed gift rows
            foreach (DataRowView dRV in GiftDV)
            {
                AGiftRow gR = (AGiftRow)dRV.Row;

                if (!BatchesWithChangesList.Contains(gR.BatchNumber) &&
                    (gR.RowState != DataRowState.Unchanged))
                {
                    BatchesWithChangesList.Add(gR.BatchNumber);
                }
            }

            //Generate string of all batches found with changes
            if (BatchesWithChangesList.Count > 0)
            {
                BatchesWithChangesString = String.Join(",", BatchesWithChangesList);

                //Add any other batch number(s) of changed gift details
                GiftDetailsDV.RowFilter = String.Format("{0} NOT IN ({1})",
                                                        AGiftDetailTable.GetBatchNumberDBName(),
                                                        BatchesWithChangesString);
            }

            foreach (DataRowView dRV in GiftDetailsDV)
            {
                AGiftDetailRow gDR = (AGiftDetailRow)dRV.Row;

                if (!BatchesWithChangesList.Contains(gDR.BatchNumber) &&
                    (gDR.RowState != DataRowState.Unchanged))
                {
                    BatchesWithChangesList.Add(gDR.BatchNumber);
                }
            }

            BatchesWithChangesList.Sort();

            //Get batch rows
            foreach (DataRowView dRV in GiftBatchesDV)
            {
                AGiftBatchRow giftBatchRow = (AGiftBatchRow)dRV.Row;

                if ((giftBatchRow.BatchStatus == MFinanceConstants.BATCH_UNPOSTED) &&
                    ((giftBatchRow.BatchNumber == ABatchToInclude) ||
                     BatchesWithChangesList.Contains(giftBatchRow.BatchNumber) ||
                     (giftBatchRow.RowState != DataRowState.Unchanged)))
                {
                    RetVal.Add(giftBatchRow);
                }
            }

            return(RetVal);
        }
示例#15
0
        /// <summary>
        /// Checks if the donor is a lapsed donor according to the parameters supplied
        /// </summary>
        /// <param name="ADonorKey">Partner Key of the donor</param>
        /// <param name="ARecipientKey">Partner Key of the gift recipient</param>
        /// <param name="AStartDate">Date of the first gift</param>
        /// <param name="AEndDate">Date until the gift must occure regularly</param>
        /// <param name="AFrequency">How often the gift must come</param>
        /// <param name="ATolerance">How much tolerance (in days) the gift can vary</param>
        /// <param name="ALedgerNumber">The ledger number</param>
        /// <param name="AMotivationGroup">A matching string for the gift motivation group.</param>
        /// <param name="AMotivationDetail">A matching string for the gift motivation detail</param>
        /// <param name="AIgnoreBetween">True: If this donor gave a gift in between the frequency pattern, then return false</param>
        /// <returns>True if donor is still active</returns>
        private bool IsLapsedDonor(Int64 ADonorKey, Int64 ARecipientKey, DateTime AStartDate, DateTime AEndDate, String AFrequency,
                                   int ATolerance, int ALedgerNumber,
                                   String AMotivationGroup, String AMotivationDetail, bool AIgnoreBetween)
        {
            bool ReturnValue = false;
            bool FirstTime   = true;

            DateTime StartDate = AEndDate.AddDays(-ATolerance);
            DateTime EndDate   = AEndDate.AddDays(ATolerance);

            int YearFrequency;
            int MonthFrequency;
            int DayFrequency;

            GetTimeFrequency(AFrequency, out YearFrequency, out MonthFrequency, out DayFrequency);

            DataTable Table;

            String StrSql = "SELECT " + AGiftTable.GetDateEnteredDBName() +
                            " FROM " + AGiftTable.GetTableDBName() +
                            " , " + AGiftDetailTable.GetTableDBName() +
                            " WHERE " + AGiftTable.GetTableDBName() + "." + AGiftTable.GetLedgerNumberDBName() + " = " + ALedgerNumber.ToString() +
                            " AND " + AGiftDetailTable.GetTableDBName() + "." + AGiftDetailTable.GetLedgerNumberDBName() + " = " +
                            ALedgerNumber.ToString() +
                            " AND " + AGiftTable.GetTableDBName() + "." + AGiftTable.GetDonorKeyDBName() + " = " + ADonorKey.ToString() +
                            " AND " + AGiftTable.GetTableDBName() + "." + AGiftTable.GetBatchNumberDBName() + " = " +
                            AGiftDetailTable.GetTableDBName() + "." + AGiftDetailTable.GetBatchNumberDBName() +
                            " AND " + AGiftTable.GetTableDBName() + "." + AGiftTable.GetGiftTransactionNumberDBName() + " = " +
                            AGiftDetailTable.GetTableDBName() + "." + AGiftDetailTable.GetGiftTransactionNumberDBName();

            if (ARecipientKey != 0)
            {
                StrSql = StrSql +
                         " AND " + AGiftDetailTable.GetTableDBName() + "." + AGiftDetailTable.GetRecipientKeyDBName() + " = " +
                         ARecipientKey.ToString();
            }

            if (AMotivationDetail != "%")
            {
                StrSql = StrSql +
                         " AND " + AGiftDetailTable.GetTableDBName() + "." + AGiftDetailTable.GetMotivationDetailCodeDBName() + " LIKE '" +
                         AMotivationDetail + "'";
            }

            if (AMotivationGroup != "%")
            {
                StrSql = StrSql +
                         " AND " + AGiftDetailTable.GetTableDBName() + "." + AGiftDetailTable.GetMotivationGroupCodeDBName() + " LIKE '" +
                         AMotivationGroup + "'";
            }

            StrSql = StrSql +
                     " ORDER BY " + AGiftTable.GetTableDBName() + "." + AGiftTable.GetDateEnteredDBName() + " DESC ";

            Table = situation.GetDatabaseConnection().SelectDT(StrSql, "table", situation.GetDatabaseConnection().Transaction, new OdbcParameter[] { });

            foreach (DataRow Row in Table.Rows)
            {
                DateTime DateEntered = (DateTime)Row[AGiftTable.GetDateEnteredDBName()];

                // Ok they gave a gift during this period but check that it was the last gift.
                if (FirstTime)
                {
                    if (DateEntered > EndDate)
                    {
                        break;
                    }

                    FirstTime = false;
                }

                // If the date is not within the date range then
                // check the flag to see if gifts are allowed between gifts.
                // otherwise ignore.
                if (DateEntered > EndDate)
                {
                    if (AIgnoreBetween)
                    {
                        break;
                    }

                    continue;
                }

                // If we are passed the start date and have not found a gift then this
                // donor does not have the right pattern of giving */
                if (DateEntered < StartDate)
                {
                    break;
                }

                // we have found a gift and it is within the dates we are interested in.
                // now go back to the next set of dates.
                StartDate = StartDate.AddDays(-DayFrequency);
                StartDate = StartDate.AddMonths(-MonthFrequency);
                StartDate = StartDate.AddYears(-YearFrequency);
                EndDate   = EndDate.AddDays(-DayFrequency);
                EndDate   = EndDate.AddMonths(-MonthFrequency);
                EndDate   = EndDate.AddYears(-YearFrequency);

                // we are now beyond the first gift date so stop.
                if (EndDate < AStartDate)
                {
                    ReturnValue = true;
                    break;
                }
            }

            if (!ReturnValue)
            {
                // clear this row, we don't want to display it
                // set all parameters of this row to NULL
                situation.GetParameters().Add("DONTDISPLAYROW", new TVariant(true));
            }
            else
            {
                // show this row
                situation.GetParameters().Add("DONTDISPLAYROW", new TVariant(false), -1, -1, null, null, ReportingConsts.CALCULATIONPARAMETERS);

                String Currency     = situation.GetParameters().Get("param_currency").ToString();
                bool   BaseCurrency = false;

                if (Currency == "Base")
                {
                    BaseCurrency = true;
                }

                CalculatePrviousYearsGift(AEndDate, ADonorKey, ALedgerNumber, ARecipientKey, AMotivationDetail, AMotivationGroup, BaseCurrency);
            }

            return(ReturnValue);
        }
示例#16
0
        /// <summary>
        /// Calculate the gift amount for this year and the previous two years given from this donor to this recipient.
        /// </summary>
        /// <param name="ALastGiftDate">defines the last year of the calculation</param>
        /// <param name="ADonorKey">Partner Key of the donor</param>
        /// <param name="ALedgerNumber">The ledger number</param>
        /// <param name="ARecipientKey">Partner Key of the gift recipient</param>
        /// <param name="AMotivationDetail">A matching string for the gift motivation detail</param>
        /// <param name="AMotivationGroup">A matching string for the gift motivation group.</param>
        /// <param name="ABaseCurrency">Defines if we sum up the base currency or international currency</param>
        private void CalculatePrviousYearsGift(DateTime ALastGiftDate,
                                               Int64 ADonorKey,
                                               int ALedgerNumber,
                                               Int64 ARecipientKey,
                                               String AMotivationDetail,
                                               String AMotivationGroup,
                                               bool ABaseCurrency)
        {
            DateTime SelectionEndDate   = new DateTime(ALastGiftDate.Year, 12, 31);
            DateTime SelectionStartDate = new DateTime(ALastGiftDate.Year - 2, 1, 1);

            String StrSql = "SELECT " + AGiftTable.GetDateEnteredDBName();

            if (ABaseCurrency)
            {
                StrSql = StrSql + ", " + AGiftDetailTable.GetGiftAmountDBName() + " AS CurrentAmount";
            }
            else
            {
                StrSql = StrSql + ", " + AGiftDetailTable.GetGiftAmountIntlDBName() + " AS CurrentAmount";
            }

            StrSql = StrSql +
                     " FROM " + AGiftTable.GetTableDBName() +
                     " , " + AGiftDetailTable.GetTableDBName() +
                     " WHERE " + AGiftTable.GetTableDBName() + "." + AGiftTable.GetLedgerNumberDBName() + " = " + ALedgerNumber.ToString() +
                     " AND " + AGiftDetailTable.GetTableDBName() + "." + AGiftDetailTable.GetLedgerNumberDBName() + " = " +
                     ALedgerNumber.ToString() +
                     " AND " + AGiftTable.GetTableDBName() + "." + AGiftTable.GetDonorKeyDBName() + " = " + ADonorKey.ToString() +
                     " AND " + AGiftTable.GetTableDBName() + "." + AGiftTable.GetBatchNumberDBName() + " = " + AGiftDetailTable.GetTableDBName() +
                     "." + AGiftDetailTable.GetBatchNumberDBName() +
                     " AND " + AGiftTable.GetTableDBName() + "." + AGiftTable.GetGiftTransactionNumberDBName() + " = " +
                     AGiftDetailTable.GetTableDBName() + "." + AGiftDetailTable.GetGiftTransactionNumberDBName() +
                     " AND " + AGiftTable.GetTableDBName() + "." + AGiftTable.GetDateEnteredDBName() + " BETWEEN '" + SelectionStartDate.ToString(
                "yyyy-MM-dd") + "' AND '" + SelectionEndDate.ToString("yyyy-MM-dd") + "'";

            if (ARecipientKey != 0)
            {
                StrSql = StrSql +
                         " AND " + AGiftDetailTable.GetTableDBName() + "." + AGiftDetailTable.GetRecipientKeyDBName() + " = " +
                         ARecipientKey.ToString();
            }

            if (AMotivationDetail != "%")
            {
                StrSql = StrSql +
                         " AND " + AGiftDetailTable.GetTableDBName() + "." + AGiftDetailTable.GetMotivationDetailCodeDBName() + " LIKE '" +
                         AMotivationDetail + "'";
            }

            if (AMotivationGroup != "%")
            {
                StrSql = StrSql +
                         " AND " + AGiftDetailTable.GetTableDBName() + "." + AGiftDetailTable.GetMotivationGroupCodeDBName() + " LIKE '" +
                         AMotivationGroup + "'";
            }

            DataTable Table = situation.GetDatabaseConnection().SelectDT(StrSql, "table",
                                                                         situation.GetDatabaseConnection().Transaction, new OdbcParameter[] { });

            decimal TotalYear_0 = 0.0M;
            decimal TotalYear_1 = 0.0M;
            decimal TotalYear_2 = 0.0M;

            foreach (DataRow Row in Table.Rows)
            {
                DateTime DateEntered   = (DateTime)Row[AGiftTable.GetDateEnteredDBName()];
                decimal  CurrentAmount = Convert.ToDecimal(Row["CurrentAmount"]);

                if (DateEntered.Year == ALastGiftDate.Year)
                {
                    TotalYear_0 += CurrentAmount;
                }
                else if (DateEntered.Year == ALastGiftDate.Year - 1)
                {
                    TotalYear_1 += CurrentAmount;
                }
                else if (DateEntered.Year == ALastGiftDate.Year - 2)
                {
                    TotalYear_2 += CurrentAmount;
                }
            }

            situation.GetParameters().Add("TotalYear_0", new TVariant(TotalYear_0));
            situation.GetParameters().Add("TotalYear_1", new TVariant(TotalYear_1));
            situation.GetParameters().Add("TotalYear_2", new TVariant(TotalYear_2));
        }
示例#17
0
        /// <summary>
        /// export all the Data of the batches matching the parameters to a String
        /// </summary>
        /// <param name="ARequestParams">Hashtable containing the given params </param>
        /// <param name="AExportString">Big parts of the export file as a simple String</param>
        /// <param name="AVerificationMessages">Additional messages to display in a messagebox</param>
        /// <returns>number of exported batches, -1 if cancelled, -2 if error</returns>
        public Int32 ExportAllGiftBatchData(
            Hashtable ARequestParams,
            out String AExportString,
            out TVerificationResultCollection AVerificationMessages)
        {
            //Return number of exported batches, -1 if cancelled, -2 if error
            int ReturnGiftBatchCount = 0;

            FStringWriter     = new StringWriter();
            FMainDS           = new GiftBatchTDS();
            FDelimiter        = (String)ARequestParams["Delimiter"];
            FLedgerNumber     = (Int32)ARequestParams["ALedgerNumber"];
            FDateFormatString = (String)ARequestParams["DateFormatString"];
            bool Summary = (bool)ARequestParams["Summary"];

            FUseBaseCurrency = (bool)ARequestParams["bUseBaseCurrency"];
            FDateForSummary  = (DateTime)ARequestParams["DateForSummary"];
            String NumberFormat = (String)ARequestParams["NumberFormat"];

            FCultureInfo      = new CultureInfo(NumberFormat.Equals("American") ? "en-US" : "de-DE");
            FTransactionsOnly = (bool)ARequestParams["TransactionsOnly"];
            FExtraColumns     = (bool)ARequestParams["ExtraColumns"];

            try
            {
                DBAccess.GDBAccessObj.BeginAutoReadTransaction(IsolationLevel.ReadCommitted,
                                                               ref FTransaction,
                                                               delegate
                {
                    try
                    {
                        ALedgerAccess.LoadByPrimaryKey(FMainDS, FLedgerNumber, FTransaction);

                        List <OdbcParameter> parameters = new List <OdbcParameter>();

                        SortedList <String, String> SQLCommandDefines = new SortedList <string, string>();

                        if ((bool)ARequestParams["IncludeUnposted"])
                        {
                            SQLCommandDefines.Add("INCLUDEUNPOSTED", string.Empty);
                        }

                        OdbcParameter param = new OdbcParameter("LedgerNumber", OdbcType.Int);
                        param.Value         = FLedgerNumber;
                        parameters.Add(param);

                        Int64 recipientNumber = (Int64)ARequestParams["RecipientNumber"];
                        Int64 fieldNumber     = (Int64)ARequestParams["FieldNumber"];

                        if (recipientNumber != 0)
                        {
                            SQLCommandDefines.Add("BYRECIPIENT", string.Empty);
                            param       = new OdbcParameter("RecipientNumber", OdbcType.Int);
                            param.Value = recipientNumber;
                            parameters.Add(param);
                        }

                        if (fieldNumber != 0)
                        {
                            SQLCommandDefines.Add("BYFIELD", string.Empty);
                            param       = new OdbcParameter("fieldNumber", OdbcType.Int);
                            param.Value = fieldNumber;
                            parameters.Add(param);
                        }

                        if (ARequestParams.ContainsKey("BatchNumberStart"))
                        {
                            SQLCommandDefines.Add("BYBATCHNUMBER", string.Empty);
                            param       = new OdbcParameter("BatchNumberStart", OdbcType.Int);
                            param.Value = (Int32)ARequestParams["BatchNumberStart"];
                            parameters.Add(param);
                            param       = new OdbcParameter("BatchNumberEnd", OdbcType.Int);
                            param.Value = (Int32)ARequestParams["BatchNumberEnd"];
                            parameters.Add(param);
                        }
                        else
                        {
                            SQLCommandDefines.Add("BYDATERANGE", string.Empty);
                            param       = new OdbcParameter("BatchDateFrom", OdbcType.DateTime);
                            param.Value = (DateTime)ARequestParams["BatchDateFrom"];
                            parameters.Add(param);
                            param       = new OdbcParameter("BatchDateTo", OdbcType.DateTime);
                            param.Value = (DateTime)ARequestParams["BatchDateTo"];
                            parameters.Add(param);
                        }

                        string sqlStatement = TDataBase.ReadSqlFile("Gift.GetGiftsToExport.sql", SQLCommandDefines);

                        TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(),
                                                         Catalog.GetString("Retrieving gift batch records"),
                                                         5);

                        if (TProgressTracker.GetCurrentState(DomainManager.GClientID.ToString()).CancelJob == true)
                        {
                            TProgressTracker.FinishJob(DomainManager.GClientID.ToString());
                            throw new ApplicationException(Catalog.GetString("Export of Batches was cancelled by user"));
                        }

                        DBAccess.GDBAccessObj.Select(FMainDS,
                                                     "SELECT DISTINCT PUB_a_gift_batch.* " + sqlStatement + " ORDER BY " + AGiftBatchTable.GetBatchNumberDBName(),
                                                     FMainDS.AGiftBatch.TableName,
                                                     FTransaction,
                                                     parameters.ToArray());


                        TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(),
                                                         Catalog.GetString("Retrieving gift records"),
                                                         10);

                        if (TProgressTracker.GetCurrentState(DomainManager.GClientID.ToString()).CancelJob == true)
                        {
                            TProgressTracker.FinishJob(DomainManager.GClientID.ToString());
                            throw new ApplicationException(Catalog.GetString("Export of Batches was cancelled by user"));
                        }

                        DBAccess.GDBAccessObj.Select(FMainDS,
                                                     "SELECT DISTINCT PUB_a_gift.* " + sqlStatement + " ORDER BY " + AGiftBatchTable.GetBatchNumberDBName() + ", " +
                                                     AGiftTable.GetGiftTransactionNumberDBName(),
                                                     FMainDS.AGift.TableName,
                                                     FTransaction,
                                                     parameters.ToArray());


                        TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(),
                                                         Catalog.GetString("Retrieving gift detail records"),
                                                         15);

                        if (TProgressTracker.GetCurrentState(DomainManager.GClientID.ToString()).CancelJob == true)
                        {
                            TProgressTracker.FinishJob(DomainManager.GClientID.ToString());
                            throw new ApplicationException(Catalog.GetString("Export of Batches was cancelled by user"));
                        }

                        DBAccess.GDBAccessObj.Select(FMainDS,
                                                     "SELECT DISTINCT PUB_a_gift_detail.* " + sqlStatement,
                                                     FMainDS.AGiftDetail.TableName,
                                                     FTransaction,
                                                     parameters.ToArray());
                    }
                    catch (ApplicationException ex)
                    {
                        throw ex;
                    }
                    catch (Exception ex)
                    {
                        TLogging.Log("Error in ExportAllGiftBatchData: " + ex.Message);
                        throw ex;
                    }
                });

                TProgressTracker.InitProgressTracker(DomainManager.GClientID.ToString(),
                                                     Catalog.GetString("Exporting Gift Batches"), 100);

                TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(),
                                                 Catalog.GetString("Retrieving records"),
                                                 5);

                string BaseCurrency = FMainDS.ALedger[0].BaseCurrency;
                FCurrencyCode = BaseCurrency; // Depending on FUseBaseCurrency, this will be overwritten for each gift.

                SortedDictionary <String, AGiftSummaryRow> sdSummary = new SortedDictionary <String, AGiftSummaryRow>();

                UInt32 counter = 0;

                // TProgressTracker Variables
                UInt32 GiftCounter = 0;

                AGiftSummaryRow giftSummary = null;

                FMainDS.AGiftDetail.DefaultView.Sort =
                    AGiftDetailTable.GetLedgerNumberDBName() + "," +
                    AGiftDetailTable.GetBatchNumberDBName() + "," +
                    AGiftDetailTable.GetGiftTransactionNumberDBName();

                foreach (AGiftBatchRow giftBatch in FMainDS.AGiftBatch.Rows)
                {
                    if (TProgressTracker.GetCurrentState(DomainManager.GClientID.ToString()).CancelJob == true)
                    {
                        TProgressTracker.FinishJob(DomainManager.GClientID.ToString());
                        throw new ApplicationException(Catalog.GetString("Export of Batches was cancelled by user"));
                    }

                    ReturnGiftBatchCount++;

                    TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(),
                                                     string.Format(Catalog.GetString("Batch {0}"), giftBatch.BatchNumber),
                                                     20);
                    GiftCounter = 0;

                    if (!FTransactionsOnly & !Summary)
                    {
                        WriteGiftBatchLine(giftBatch);
                    }

                    foreach (AGiftRow gift in FMainDS.AGift.Rows)
                    {
                        if (gift.BatchNumber.Equals(giftBatch.BatchNumber) && gift.LedgerNumber.Equals(giftBatch.LedgerNumber))
                        {
                            if (TProgressTracker.GetCurrentState(DomainManager.GClientID.ToString()).CancelJob == true)
                            {
                                TProgressTracker.FinishJob(DomainManager.GClientID.ToString());
                                throw new ApplicationException(Catalog.GetString("Export of Batches was cancelled by user"));
                            }

                            // Update progress tracker every 25 records
                            if (++GiftCounter % 25 == 0)
                            {
                                TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(),
                                                                 string.Format(Catalog.GetString("Batch {0} - Exporting gifts"), giftBatch.BatchNumber),
                                                                 (GiftCounter / 25 + 4) * 5 > 90 ? 90 : (GiftCounter / 25 + 4) * 5);
                            }

                            DataRowView[] selectedRowViews = FMainDS.AGiftDetail.DefaultView.FindRows(
                                new object[] { gift.LedgerNumber, gift.BatchNumber, gift.GiftTransactionNumber });

                            foreach (DataRowView rv in selectedRowViews)
                            {
                                AGiftDetailRow giftDetail = (AGiftDetailRow)rv.Row;

                                if (Summary)
                                {
                                    FCurrencyCode = FUseBaseCurrency ? BaseCurrency : giftBatch.CurrencyCode;
                                    decimal mapExchangeRateToBase = FUseBaseCurrency ? 1 : giftBatch.ExchangeRateToBase;


                                    counter++;
                                    String DictionaryKey = FCurrencyCode + ";" + giftBatch.BankCostCentre + ";" + giftBatch.BankAccountCode + ";" +
                                                           giftDetail.RecipientKey + ";" + giftDetail.MotivationGroupCode + ";" +
                                                           giftDetail.MotivationDetailCode;

                                    if (sdSummary.TryGetValue(DictionaryKey, out giftSummary))
                                    {
                                        giftSummary.GiftTransactionAmount += giftDetail.GiftTransactionAmount;
                                        giftSummary.GiftAmount            += giftDetail.GiftAmount;
                                    }
                                    else
                                    {
                                        giftSummary = new AGiftSummaryRow();

                                        /*
                                         * summary_data.a_transaction_currency_c = lv_stored_currency_c
                                         * summary_data.a_bank_cost_centre_c = a_gift_batch.a_bank_cost_centre_c
                                         * summary_data.a_bank_account_code_c = a_gift_batch.a_bank_account_code_c
                                         * summary_data.a_recipient_key_n = a_gift_detail.p_recipient_key_n
                                         * summary_data.a_motivation_group_code_c = a_gift_detail.a_motivation_group_code_c
                                         * summary_data.a_motivation_detail_code_c = a_gift_detail.a_motivation_detail_code_c
                                         * summary_data.a_exchange_rate_to_base_n = lv_exchange_rate_n
                                         * summary_data.a_gift_type_c = a_gift_batch.a_gift_type_c */
                                        giftSummary.CurrencyCode          = FCurrencyCode;
                                        giftSummary.BankCostCentre        = giftBatch.BankCostCentre;
                                        giftSummary.BankAccountCode       = giftBatch.BankAccountCode;
                                        giftSummary.RecipientKey          = giftDetail.RecipientKey;
                                        giftSummary.MotivationGroupCode   = giftDetail.MotivationGroupCode;
                                        giftSummary.MotivationDetailCode  = giftDetail.MotivationDetailCode;
                                        giftSummary.GiftTransactionAmount = giftDetail.GiftTransactionAmount;
                                        giftSummary.GiftAmount            = giftDetail.GiftAmount;

                                        sdSummary.Add(DictionaryKey, giftSummary);
                                    }

                                    //overwrite always because we want to have the last
                                    giftSummary.ExchangeRateToBase = mapExchangeRateToBase;
                                }
                                else  // not summary
                                {
                                    WriteGiftLine(gift, giftDetail);
                                }
                            }
                        }
                    }
                }

                if (Summary)
                {
                    TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(),
                                                     Catalog.GetString("Export Summary"),
                                                     95);

                    bool first = true;

                    foreach (KeyValuePair <string, AGiftSummaryRow> kvp in sdSummary)
                    {
                        if (!FTransactionsOnly && first)
                        {
                            WriteGiftBatchSummaryLine(kvp.Value);
                            first = false;
                        }

                        WriteGiftSummaryLine(kvp.Value);
                    }
                }

                TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(),
                                                 Catalog.GetString("Gift batch export successful"),
                                                 100);

                TProgressTracker.FinishJob(DomainManager.GClientID.ToString());
            }
            catch (ApplicationException)
            {
                //Show cancel condition
                ReturnGiftBatchCount = -1;
                TProgressTracker.CancelJob(DomainManager.GClientID.ToString());
            }
            catch (Exception ex)
            {
                TLogging.Log(ex.ToString());

                //Show error condition
                ReturnGiftBatchCount = -2;

                FMessages.Add(new TVerificationResult(
                                  "Exporting Gift Batches Terminated Unexpectedly",
                                  ex.Message,
                                  "An unexpected error occurred during the export of gift batches",
                                  string.Empty,
                                  TResultSeverity.Resv_Critical,
                                  Guid.Empty));

                TProgressTracker.CancelJob(DomainManager.GClientID.ToString());
            }

            if (ReturnGiftBatchCount > 0)
            {
                AExportString = FStringWriter.ToString();
            }
            else
            {
                AExportString = string.Empty;
            }

            AVerificationMessages = FMessages;

            return(ReturnGiftBatchCount);
        }
示例#18
0
        /// <summary>
        /// This report considers gifts given between the two specified dates, and can include all gifts or, if
        /// selected, those to a particular motivation, motivation detail or recipient. For the defined set of gifts
        /// and its total value, the donors are sorted into a list, starting with those who gave most, and showing
        /// the percentage that their gifts contributed to the total received (for this motivation or recipient, if
        /// specified) and the cumulative percentage, moving down the list starting with the top donor.
        /// </summary>
        /// <param name="ATotalAmount">Pre calculated value of the total gifts given with these parameters</param>
        /// <param name="ATopXPercent">Upper limit of the percentage to show in the report</param>
        /// <param name="ABottomXPercent">Lower limit of the percentage to show in the report</param>
        /// <param name="AExtract">true to use only partners from an extract</param>
        /// <param name="AExtractName">extract name</param>
        /// <param name="AStartDate">Start date of the gifts given</param>
        /// <param name="AEndDate">End date of the gifts given</param>
        /// <param name="ARecipientKey">Partner key of a specific recipient. If 0 then use all recipients</param>
        /// <param name="AMotivationGroup">Limit gifts to this motivation group. If % use all motivation groups</param>
        /// <param name="AMotivationDetail">Limit gifts to this motivation detail. If % use all motivation details</param>
        /// <returns></returns>
        private bool MakeTopDonor(decimal ATotalAmount, decimal ATopXPercent, decimal ABottomXPercent,
                                  bool AExtract, String AExtractName, DateTime AStartDate, DateTime AEndDate,
                                  Int64 ARecipientKey, String AMotivationGroup, String AMotivationDetail)
        {
            Int64         LedgerNumber = situation.GetParameters().Get("param_ledger_number_i").ToInt64();
            String        CurrencyType = situation.GetParameters().Get("param_currency").ToString();
            StringBuilder SqlString    = new StringBuilder();

            SqlString.Append("SELECT DISTINCT ");
            SqlString.Append("gift.p_donor_key_n AS DonorKey, ");
            SqlString.Append(PPartnerTable.GetTableDBName() + "." + PPartnerTable.GetPartnerShortNameDBName() + " AS ShortName, ");
            SqlString.Append(PPartnerTable.GetTableDBName() + "." + PPartnerTable.GetPartnerClassDBName() + " AS PartnerClass, ");

            if (CurrencyType == "Base")
            {
                SqlString.Append("SUM(detail." + AGiftDetailTable.GetGiftAmountDBName() + ") AS Amount ");
            }
            else
            {
                SqlString.Append("SUM(detail." + AGiftDetailTable.GetGiftAmountIntlDBName() + ") AS Amount ");
            }

            SqlString.Append(
                " FROM " + AGiftTable.GetTableDBName() + " as gift, " + AGiftDetailTable.GetTableDBName() + " as detail, " +
                PPartnerTable.GetTableDBName() + ", " + AGiftBatchTable.GetTableDBName() + " ");

            if (AExtract)
            {
                SqlString.Append(", " + MExtractTable.GetTableDBName() + ", " + MExtractMasterTable.GetTableDBName());
                SqlString.Append(
                    " WHERE gift." + AGiftTable.GetDonorKeyDBName() + " = " + MExtractTable.GetTableDBName() + "." +
                    MExtractTable.GetPartnerKeyDBName());
                SqlString.Append(
                    " AND " + MExtractTable.GetTableDBName() + "." + MExtractTable.GetExtractIdDBName() + " = " +
                    MExtractMasterTable.GetTableDBName() +
                    "." + MExtractMasterTable.GetExtractIdDBName());
                SqlString.Append(" AND " + MExtractMasterTable.GetTableDBName() + "." + MExtractMasterTable.GetExtractNameDBName() + " = '");
                SqlString.Append(AExtractName);
                SqlString.Append("' AND ");
            }
            else
            {
                SqlString.Append(" WHERE ");
            }

            SqlString.Append(" detail." + AGiftDetailTable.GetLedgerNumberDBName() + " = gift." + AGiftTable.GetLedgerNumberDBName());
            SqlString.Append(" AND detail." + AGiftDetailTable.GetBatchNumberDBName() + " = gift." + AGiftTable.GetBatchNumberDBName());
            SqlString.Append(
                " AND detail." + AGiftDetailTable.GetGiftTransactionNumberDBName() + " = gift." + AGiftTable.GetGiftTransactionNumberDBName());
            SqlString.Append(" AND gift." + AGiftTable.GetDateEnteredDBName() + " BETWEEN '");
            SqlString.Append(AStartDate.ToString("yyyy-MM-dd"));
            SqlString.Append("' AND '");
            SqlString.Append(AEndDate.ToString("yyyy-MM-dd"));
            SqlString.Append("' AND gift." + AGiftTable.GetLedgerNumberDBName() + " = ");
            SqlString.Append(LedgerNumber.ToString());
            SqlString.Append(" AND " + AGiftBatchTable.GetTableDBName() + "." + AGiftBatchTable.GetLedgerNumberDBName() + " = ");
            SqlString.Append(LedgerNumber.ToString());
            SqlString.Append(
                " AND " + AGiftBatchTable.GetTableDBName() + "." + AGiftBatchTable.GetBatchNumberDBName() + " = gift." +
                AGiftTable.GetBatchNumberDBName());
            SqlString.Append(" AND ( " + AGiftBatchTable.GetTableDBName() + "." + AGiftBatchTable.GetBatchStatusDBName() + " = 'Posted' OR ");
            SqlString.Append(AGiftBatchTable.GetTableDBName() + "." + AGiftBatchTable.GetBatchStatusDBName() + " = 'posted' ) ");
            SqlString.Append(
                " AND " + PPartnerTable.GetTableDBName() + "." + PPartnerTable.GetPartnerKeyDBName() + " = gift." + AGiftTable.GetDonorKeyDBName());

            if (ARecipientKey != 0)
            {
                SqlString.Append(" AND detail." + AGiftDetailTable.GetRecipientKeyDBName() + " = ");
                SqlString.Append(ARecipientKey.ToString());
            }

            if (AMotivationGroup != "%")
            {
                SqlString.Append(" AND  detail." + AGiftDetailTable.GetMotivationGroupCodeDBName() + " LIKE '");
                SqlString.Append(AMotivationGroup);
                SqlString.Append("' ");
            }

            if (AMotivationDetail != "%")
            {
                SqlString.Append(" AND  detail." + AGiftDetailTable.GetMotivationDetailCodeDBName() + " LIKE '");
                SqlString.Append(AMotivationDetail);
                SqlString.Append("' ");
            }

            SqlString.Append(" GROUP BY gift." + AGiftTable.GetDonorKeyDBName() + ", ");
            SqlString.Append(PPartnerTable.GetTableDBName() + "." + PPartnerTable.GetPartnerShortNameDBName() + ", ");
            SqlString.Append(PPartnerTable.GetTableDBName() + "." + PPartnerTable.GetPartnerClassDBName());
            SqlString.Append(" ORDER BY Amount DESC");

            DataTable Table = situation.GetDatabaseConnection().SelectDT(SqlString.ToString(), "table",
                                                                         situation.GetDatabaseConnection().Transaction, new OdbcParameter[] { });

            decimal CummulativeAmount = 0;
            decimal TopAmount         = ATotalAmount * ATopXPercent / 100;
            decimal BottomAmount      = ATotalAmount * ABottomXPercent / 100;

            int NumColumns = 7;
            int ChildRow   = 1;

            situation.GetResults().Clear();

            for (int Counter = 0; Counter < Table.Rows.Count; ++Counter)
            {
                decimal CurrentAmount = Convert.ToDecimal(Table.Rows[Counter]["Amount"]);

                if (CurrentAmount < 0)
                {
                    continue;
                }

                if ((CummulativeAmount <= TopAmount) &&
                    (CummulativeAmount >= BottomAmount))
                {
                    Int64  DonorKey     = Convert.ToInt64(Table.Rows[Counter]["DonorKey"]);
                    String ShortName    = (String)Table.Rows[Counter]["ShortName"];
                    String PartnerClass = (String)Table.Rows[Counter]["PartnerClass"];

                    CummulativeAmount += CurrentAmount;

                    // Transfer to results
                    TVariant[] Header      = new TVariant[NumColumns];
                    TVariant[] Description =
                    {
                        new TVariant(), new TVariant()
                    };
                    TVariant[] Columns = new TVariant[NumColumns];

                    for (int Counter2 = 0; Counter2 < NumColumns; ++Counter2)
                    {
                        Header[Counter2]  = new TVariant();
                        Columns[Counter2] = new TVariant();
                    }

                    StringBuilder       PartnerAddress = new StringBuilder();
                    PPartnerLocationRow AddressRow;

                    if (Ict.Petra.Server.MReporting.MPartner.TRptUserFunctionsPartner.GetPartnerBestAddressRow(DonorKey, situation, out AddressRow))
                    {
                        PLocationTable LocationTable = PLocationAccess.LoadByPrimaryKey(AddressRow.SiteKey,
                                                                                        AddressRow.LocationKey, situation.GetDatabaseConnection().Transaction);

                        if (LocationTable.Rows.Count > 0)
                        {
                            PLocationRow LocationRow = (PLocationRow)LocationTable.Rows[0];

                            PartnerAddress.Append(LocationRow.Locality);

                            if (LocationRow.Locality.Length > 0)
                            {
                                PartnerAddress.Append(", ");
                            }

                            PartnerAddress.Append(LocationRow.StreetName);

                            if (PartnerAddress.Length > 0)
                            {
                                PartnerAddress.Append(", ");
                            }

                            PartnerAddress.Append(LocationRow.Address3);

                            if (PartnerAddress.Length > 0)
                            {
                                PartnerAddress.Append(", ");
                            }

                            PartnerAddress.Append(LocationRow.PostalCode);
                            PartnerAddress.Append(" ");
                            PartnerAddress.Append(LocationRow.City);

                            if (LocationRow.County.Length > 0)
                            {
                                PartnerAddress.Append(", ");
                                PartnerAddress.Append(LocationRow.County);
                            }

                            PartnerAddress.Append(", ");
                            PartnerAddress.Append(LocationRow.CountryCode);
                        }
                    }

                    Columns[0] = new TVariant(DonorKey.ToString("0000000000"));
                    Columns[1] = new TVariant(PartnerClass);
                    Columns[2] = new TVariant(ShortName);
                    Columns[3] = new TVariant(CurrentAmount, "-#,##0.00;#,##0.00");
                    Columns[4] = new TVariant((CurrentAmount * 100 / ATotalAmount), "-#,##0.00;#,##0.00");
                    Columns[5] = new TVariant((CummulativeAmount * 100 / ATotalAmount), "-#,##0.00;#,##0.00");
                    Columns[6] = new TVariant(PartnerAddress.ToString());

                    situation.GetResults().AddRow(0, ChildRow++, true, 2, "", "", false,
                                                  Header, Description, Columns);
                }
                else
                {
                    CummulativeAmount += CurrentAmount;
                }
            }

            return(true);
        }
示例#19
0
        /// <summary>
        /// export all posted invoices for conference and seminar participants in this year
        /// </summary>
        public static void Export(string AOutputPath,
                                  char ACSVSeparator,
                                  string ANewLine,
                                  Int32 ALedgerNumber,
                                  Int32 AFinancialYear,
                                  string ACostCentres)
        {
            string filename = Path.GetFullPath(Path.Combine(AOutputPath, "participants.csv"));

            Console.WriteLine("Writing file: " + filename);

            TDBTransaction   Transaction = new TDBTransaction();
            AGiftDetailTable giftdetails = new AGiftDetailTable();
            AGiftTable       gifts       = new AGiftTable();
            AGiftBatchTable  batches     = new AGiftBatchTable();
            PPersonTable     persons     = new PPersonTable();

            DBAccess.ReadTransaction(ref Transaction,
                                     delegate
            {
                TDataBase db = Transaction.DataBaseObj;

                // all gift details towards a costcentre that needs to be exported
                string sql =
                    String.Format("SELECT DISTINCT D.* " +
                                  "FROM PUB_{0} AS B, PUB_{1} AS G, PUB_{2} AS D " +
                                  "WHERE B.{3} = {4} AND B.{5} = {6} AND B.{7}='{8}' " +
                                  "AND G.{3} = B.{3} AND G.{9} = B.{9} " +
                                  "AND D.{3} = G.{3} AND D.{9} = G.{9} AND D.{10} = G.{10} " +
                                  "AND D.{11} IN ({12}) " +
                                  "AND NOT D.{13} = '{14}'",
                                  AGiftBatchTable.GetTableDBName(),
                                  AGiftTable.GetTableDBName(),
                                  AGiftDetailTable.GetTableDBName(),
                                  AGiftBatchTable.GetLedgerNumberDBName(),
                                  ALedgerNumber,
                                  AGiftBatchTable.GetBatchYearDBName(),
                                  AFinancialYear,
                                  AGiftBatchTable.GetBatchStatusDBName(),
                                  MFinanceConstants.BATCH_POSTED,
                                  AGiftBatchTable.GetBatchNumberDBName(),
                                  AGiftTable.GetGiftTransactionNumberDBName(),
                                  AGiftDetailTable.GetCostCentreCodeDBName(),
                                  "'" + ACostCentres.Replace(",", "','") + "'",
                                  AGiftDetailTable.GetMotivationGroupCodeDBName(),
                                  "GIFT");

                db.SelectDT(giftdetails, sql, Transaction, null, 0, 0);

                sql = sql.Replace("SELECT DISTINCT D.*", "SELECT DISTINCT G.*");

                db.SelectDT(gifts, sql, Transaction, null, 0, 0);

                gifts.DefaultView.Sort =
                    AGiftTable.GetBatchNumberDBName() + "," +
                    AGiftTable.GetGiftTransactionNumberDBName();

                sql = sql.Replace("SELECT DISTINCT G.*", "SELECT DISTINCT B.*");

                db.SelectDT(batches, sql, Transaction, null, 0, 0);
                batches.DefaultView.Sort = AGiftTable.GetBatchNumberDBName();

                sql =
                    String.Format("SELECT DISTINCT P.* " +
                                  "FROM PUB_{0} AS B, PUB_{1} AS G, PUB_{2} AS D, PUB.{15} AS P " +
                                  "WHERE B.{3} = {4} AND B.{5} = {6} AND B.{7}='{8}' " +
                                  "AND G.{3} = B.{3} AND G.{9} = B.{9} " +
                                  "AND D.{3} = G.{3} AND D.{9} = G.{9} AND D.{10} = G.{10} " +
                                  "AND D.{11} IN ({12}) " +
                                  "AND NOT D.{13} = '{14}' " +
                                  "AND P.{16} = G.{17}",
                                  AGiftBatchTable.GetTableDBName(),
                                  AGiftTable.GetTableDBName(),
                                  AGiftDetailTable.GetTableDBName(),
                                  AGiftBatchTable.GetLedgerNumberDBName(),
                                  ALedgerNumber,
                                  AGiftBatchTable.GetBatchYearDBName(),
                                  AFinancialYear,
                                  AGiftBatchTable.GetBatchStatusDBName(),
                                  MFinanceConstants.BATCH_POSTED,
                                  AGiftBatchTable.GetBatchNumberDBName(),
                                  AGiftTable.GetGiftTransactionNumberDBName(),
                                  AGiftDetailTable.GetCostCentreCodeDBName(),
                                  "'" + ACostCentres.Replace(",", "','") + "'",
                                  AGiftDetailTable.GetMotivationGroupCodeDBName(),
                                  "GIFT",
                                  PPersonTable.GetTableDBName(),
                                  PPersonTable.GetPartnerKeyDBName(),
                                  AGiftTable.GetDonorKeyDBName());

                db.SelectDT(persons, sql, Transaction, null, 0, 0);
                persons.DefaultView.Sort = PPersonTable.GetPartnerKeyDBName();
            });

            StringBuilder sb = new StringBuilder();

            foreach (AGiftDetailRow detail in giftdetails.Rows)
            {
                AGiftRow      gift  = (AGiftRow)gifts.DefaultView.FindRows(new object[] { detail.BatchNumber, detail.GiftTransactionNumber })[0].Row;
                AGiftBatchRow batch = (AGiftBatchRow)batches.DefaultView.FindRows(detail.BatchNumber)[0].Row;

                DataRowView[] personList = persons.DefaultView.FindRows(gift.DonorKey);
                PPersonRow    person     = (personList.Length > 0 ? (PPersonRow)personList[0].Row : null);

                sb.Append(StringHelper.StrMerge(
                              new string[] {
                    "GB" + detail.BatchNumber.ToString() + "_G" + detail.GiftTransactionNumber.ToString() +
                    "_D" + detail.DetailNumber.ToString(),
                    String.Format("{0:N}", detail.GiftTransactionAmount),
                    batch.GlEffectiveDate.ToString("yyyyMMdd"),
                    gift.DonorKey.ToString(),
                    person !=
                    null ? (person.DateOfBirth.HasValue ? person.DateOfBirth.Value.ToString("yyyyMMdd") : string.Empty) : string.Empty,
                    detail.CostCentreCode,
                    batch.BatchDescription,
                    detail.GiftCommentOne,
                    detail.GiftCommentTwo
                }, ACSVSeparator));
                sb.Append(ANewLine);
            }

            StreamWriter sw = new StreamWriter(filename, false, Encoding.GetEncoding(1252));

            sw.Write(sb.ToString());
            sw.Close();
        }
示例#20
0
        private bool OnDeleteRowManual(GiftBatchTDSAGiftDetailRow ARowToDelete, ref string ACompletionMessage)
        {
            bool   deletionSuccessful   = false;
            string originatingDetailRef = string.Empty;

            ACompletionMessage = string.Empty;

            if (ARowToDelete == null)
            {
                return(deletionSuccessful);
            }

            // temporarily disable  New Donor Warning
            ((TFrmGiftBatch)this.ParentForm).NewDonorWarning = false;

            if ((ARowToDelete.RowState != DataRowState.Added) && !((TFrmGiftBatch)this.ParentForm).SaveChangesManual())
            {
                MessageBox.Show("Error in trying to save prior to deleting current gift detail!");
                return(deletionSuccessful);
            }

            ((TFrmGiftBatch)this.ParentForm).NewDonorWarning = true;

            //Backup the Dataset for reversion purposes
            GiftBatchTDS FTempDS = (GiftBatchTDS)FMainDS.Copy();

            FTempDS.Merge(FMainDS);

            if (ARowToDelete.RowState != DataRowState.Added)
            {
                //Required to deal with concurrency errors
                FMainDS.AcceptChanges();
            }

            int    selectedDetailNumber        = ARowToDelete.DetailNumber;
            int    giftToDeleteTransNo         = 0;
            string filterAllGiftsOfBatch       = String.Empty;
            string filterAllGiftDetailsOfBatch = String.Empty;

            int detailRowCount = FGiftDetailView.Count;

            try
            {
                //Speeds up deletion of larger gift sets
                FMainDS.EnforceConstraints = false;

                if (ARowToDelete.ModifiedDetailKey != null)
                {
                    originatingDetailRef = ARowToDelete.ModifiedDetailKey;
                }

                //Delete current detail row
                ARowToDelete.Delete();

                //If there existed (before the delete row above) more than one detail row, then no need to delete gift header row
                if (detailRowCount > 1)
                {
                    FGiftSelectedForDeletion = false;

                    foreach (DataRowView rv in FGiftDetailView)
                    {
                        GiftBatchTDSAGiftDetailRow row = (GiftBatchTDSAGiftDetailRow)rv.Row;

                        if (row.DetailNumber > selectedDetailNumber)
                        {
                            row.DetailNumber--;
                        }
                    }

                    FGift.LastDetailNumber--;

                    FPetraUtilsObject.SetChangedFlag();
                }
                else
                {
                    giftToDeleteTransNo = FGift.GiftTransactionNumber;

                    TLogging.Log("Delete row: " + giftToDeleteTransNo.ToString());

                    // Reduce all Gift Detail row Transaction numbers by 1 if they are greater then gift to be deleted
                    filterAllGiftDetailsOfBatch = String.Format("{0}={1} And {2}>{3}",
                                                                AGiftDetailTable.GetBatchNumberDBName(),
                                                                FBatchNumber,
                                                                AGiftDetailTable.GetGiftTransactionNumberDBName(),
                                                                giftToDeleteTransNo);

                    DataView giftDetailView = new DataView(FMainDS.AGiftDetail);
                    giftDetailView.RowFilter = filterAllGiftDetailsOfBatch;
                    giftDetailView.Sort      = String.Format("{0} ASC", AGiftDetailTable.GetGiftTransactionNumberDBName());

                    foreach (DataRowView rv in giftDetailView)
                    {
                        GiftBatchTDSAGiftDetailRow row = (GiftBatchTDSAGiftDetailRow)rv.Row;

                        row.GiftTransactionNumber--;
                    }

                    //Cannot delete the gift row, just copy the data of rows above down by 1 row
                    // and then mark the top row for deletion
                    //In other words, bubble the gift row to be deleted to the top
                    filterAllGiftsOfBatch = String.Format("{0}={1} And {2}>={3}",
                                                          AGiftTable.GetBatchNumberDBName(),
                                                          FBatchNumber,
                                                          AGiftTable.GetGiftTransactionNumberDBName(),
                                                          giftToDeleteTransNo);

                    DataView giftView = new DataView(FMainDS.AGift);
                    giftView.RowFilter = filterAllGiftsOfBatch;
                    giftView.Sort      = String.Format("{0} ASC", AGiftTable.GetGiftTransactionNumberDBName());

                    AGiftRow giftRowToReceive  = null;
                    AGiftRow giftRowToCopyDown = null;
                    AGiftRow giftRowCurrent    = null;

                    int currentGiftTransNo = 0;

                    foreach (DataRowView gv in giftView)
                    {
                        giftRowCurrent = (AGiftRow)gv.Row;

                        currentGiftTransNo = giftRowCurrent.GiftTransactionNumber;

                        if (currentGiftTransNo > giftToDeleteTransNo)
                        {
                            giftRowToCopyDown = giftRowCurrent;

                            //Copy column values down
                            for (int j = 3; j < giftRowToCopyDown.Table.Columns.Count; j++)
                            {
                                //Update all columns except the pk fields that remain the same
                                if (!giftRowToCopyDown.Table.Columns[j].ColumnName.EndsWith("_text"))
                                {
                                    giftRowToReceive[j] = giftRowToCopyDown[j];
                                }
                            }
                        }

                        if (currentGiftTransNo == FBatchRow.LastGiftNumber)
                        {
                            //Mark last record for deletion
                            giftRowCurrent.GiftStatus = MFinanceConstants.MARKED_FOR_DELETION;
                        }

                        //Will always be previous row
                        giftRowToReceive = giftRowCurrent;
                    }

                    FPreviouslySelectedDetailRow = null;

                    FPetraUtilsObject.SetChangedFlag();

                    FGiftSelectedForDeletion = true;

                    FBatchRow.LastGiftNumber--;
                }

                //Force a change in the batch row to make sure it exists in the dataset to save
                FBatchRow.DateModified = DateTime.Now;

                //Check if deleting a reversed gift detail
                if (originatingDetailRef.StartsWith("|"))
                {
                    bool ok = TRemote.MFinance.Gift.WebConnectors.ReversedGiftReset(FLedgerNumber, originatingDetailRef);

                    if (!ok)
                    {
                        throw new Exception("Error in trying to reset Modified Detail field of the originating gift detail.");
                    }
                }

                //Try to save changes
                if (((TFrmGiftBatch)this.ParentForm).SaveChangesManual())
                {
                    //Clear current batch's gift data and reload from server
                    RefreshCurrentBatchGiftData(FBatchNumber);
                }
                else
                {
                    throw new Exception("Unable to save after deleting a gift!");
                }

                ACompletionMessage = Catalog.GetString("Gift row deleted successfully!");

                deletionSuccessful = true;
            }
            catch (Exception ex)
            {
                ACompletionMessage = ex.Message;
                MessageBox.Show(ex.Message,
                                "Gift Deletion Error",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);

                //Revert to previous state
                FMainDS.Merge(FTempDS);
            }
            finally
            {
                FMainDS.EnforceConstraints = true;
                SetGiftDetailDefaultView();
                FFilterAndFindObject.ApplyFilter();
            }

            UpdateRecordNumberDisplay();

            return(deletionSuccessful);
        }
        /// <summary>
        /// auto populate new gift recipient info using the donor's last gift
        /// </summary>
        /// <param name="ADonorKey"></param>
        /// <param name="APartnerShortName"></param>
        /// <param name="AGiftTransactionNumber"></param>
        private void AutoPopulateGiftDetail(Int64 ADonorKey, String APartnerShortName, Int32 AGiftTransactionNumber)
        {
            FAutoPopulatingGiftInProcess = true;

            bool IsSplitGift = false;

            DateTime LatestUnpostedGiftDateEntered = new DateTime(1900, 1, 1);

            try
            {
                //Check for Donor in loaded gift batches
                // and record most recent date entered
                AGiftTable DonorRecentGiftsTable             = new AGiftTable();
                GiftBatchTDSAGiftDetailTable GiftDetailTable = new GiftBatchTDSAGiftDetailTable();

                AGiftRow MostRecentLoadedGiftForDonorRow = null;

                DataView giftDV = new DataView(FMainDS.AGift);

                giftDV.RowStateFilter = DataViewRowState.CurrentRows;

                giftDV.RowFilter = string.Format("{0}={1} And Not ({2}={3} And {4}={5})",
                                                 AGiftTable.GetDonorKeyDBName(),
                                                 ADonorKey,
                                                 AGiftTable.GetBatchNumberDBName(),
                                                 FBatchNumber,
                                                 AGiftTable.GetGiftTransactionNumberDBName(),
                                                 AGiftTransactionNumber);

                giftDV.Sort = String.Format("{0} DESC, {1} DESC",
                                            AGiftTable.GetDateEnteredDBName(),
                                            AGiftTable.GetGiftTransactionNumberDBName());

                if (giftDV.Count > 0)
                {
                    //Take first row = most recent date entered value
                    MostRecentLoadedGiftForDonorRow = (AGiftRow)giftDV[0].Row;
                    LatestUnpostedGiftDateEntered   = MostRecentLoadedGiftForDonorRow.DateEntered;
                    DonorRecentGiftsTable.Rows.Add((object[])MostRecentLoadedGiftForDonorRow.ItemArray.Clone());
                }

                //Check for even more recent saved gifts on server (i.e. not necessarily loaded)
                GiftDetailTable = TRemote.MFinance.Gift.WebConnectors.LoadDonorLastPostedGift(ADonorKey, FLedgerNumber, LatestUnpostedGiftDateEntered);

                if (((GiftDetailTable != null) && (GiftDetailTable.Count > 0)))
                {
                    //UnLoaded/Saved gift from donor is more recent
                    IsSplitGift = (GiftDetailTable.Count > 1);
                }
                else if (MostRecentLoadedGiftForDonorRow != null)
                {
                    //Loaded/unsaved gift from donor is more recent
                    DataView giftDetailDV = new DataView(FMainDS.AGiftDetail);

                    giftDetailDV.RowStateFilter = DataViewRowState.CurrentRows;

                    giftDetailDV.RowFilter = string.Format("{0}={1} And {2}={3}",
                                                           AGiftDetailTable.GetBatchNumberDBName(),
                                                           MostRecentLoadedGiftForDonorRow.BatchNumber,
                                                           AGiftDetailTable.GetGiftTransactionNumberDBName(),
                                                           MostRecentLoadedGiftForDonorRow.GiftTransactionNumber);

                    foreach (DataRowView drv in giftDetailDV)
                    {
                        GiftBatchTDSAGiftDetailRow gDR = (GiftBatchTDSAGiftDetailRow)drv.Row;
                        GiftDetailTable.Rows.Add((object[])gDR.ItemArray.Clone());
                    }

                    IsSplitGift = (GiftDetailTable.Count > 1);
                }
                else
                {
                    //nothing to autocopy
                    return;
                }

                // if the last gift was a split gift (multiple details) then ask the user if they would like this new gift to also be split
                if (IsSplitGift)
                {
                    GiftDetailTable.DefaultView.Sort = GiftBatchTDSAGiftDetailTable.GetDetailNumberDBName() + " ASC";

                    string Message = string.Format(Catalog.GetString(
                                                       "The last gift from this donor was a split gift.{0}{0}Here are the details:{0}"), "\n");
                    int DetailNumber = 1;

                    foreach (DataRowView dvr in GiftDetailTable.DefaultView)
                    {
                        GiftBatchTDSAGiftDetailRow Row = (GiftBatchTDSAGiftDetailRow)dvr.Row;

                        Message += DetailNumber + ")  ";

                        if (Row.RecipientKey > 0)
                        {
                            Message +=
                                string.Format(Catalog.GetString("Recipient: {0} ({1});  Motivation Group: {2};  Motivation Detail: {3};  Amount: {4}"),
                                              Row.RecipientDescription, Row.RecipientKey, Row.MotivationGroupCode, Row.MotivationDetailCode,
                                              StringHelper.FormatUsingCurrencyCode(Row.GiftTransactionAmount, GetBatchRow().CurrencyCode) +
                                              " " + FBatchRow.CurrencyCode) +
                                "\n";
                        }

                        DetailNumber++;
                    }

                    Message += "\n" + Catalog.GetString("Do you want to create the same split gift again?");

                    if (!(MessageBox.Show(Message, Catalog.GetString(
                                              "Create Split Gift"), MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                          == DialogResult.Yes))
                    {
                        if (cmbDetailMethodOfGivingCode.CanFocus)
                        {
                            cmbDetailMethodOfGivingCode.Focus();
                        }
                        else if (txtDetailReference.CanFocus)
                        {
                            txtDetailReference.Focus();
                        }

                        return;
                    }
                }

                this.Cursor = Cursors.WaitCursor;

                GiftBatchTDSAGiftDetailRow giftDetailRow = (GiftBatchTDSAGiftDetailRow)GiftDetailTable.DefaultView[0].Row;

                // Handle first row, which is FPreviouslySelectedDetailRow
                txtDetailDonorKey.Text     = String.Format("{0:0000000000}", ADonorKey);
                txtDetailRecipientKey.Text = String.Format("{0:0000000000}", giftDetailRow.RecipientKey);
                cmbDetailMotivationGroupCode.SetSelectedString(giftDetailRow.MotivationGroupCode);
                txtDetailMotivationDetailCode.Text = giftDetailRow.MotivationDetailCode;
                cmbMotivationDetailCode.SetSelectedString(giftDetailRow.MotivationDetailCode);
                chkDetailConfidentialGiftFlag.Checked = giftDetailRow.ConfidentialGiftFlag;
                // Change #5481
                chkDetailChargeFlag.Checked = true;
                cmbDetailMethodOfPaymentCode.SetSelectedString(FBatchMethodOfPayment, -1);
                cmbDetailMethodOfGivingCode.SetSelectedString(giftDetailRow.MethodOfGivingCode, -1);

                //Handle mailing code
                if (FSETAutoCopyIncludeMailingCodeFlag)
                {
                    cmbDetailMailingCode.SetSelectedString(giftDetailRow.MailingCode, -1);
                }
                else
                {
                    cmbDetailMailingCode.SelectedIndex = -1;
                }

                //Copy the comments and comment types if required
                if (FSETAutoCopyIncludeCommentsFlag)
                {
                    txtDetailGiftCommentOne.Text = giftDetailRow.GiftCommentOne;
                    cmbDetailCommentOneType.SetSelectedString(giftDetailRow.CommentOneType);
                    txtDetailGiftCommentTwo.Text = giftDetailRow.GiftCommentTwo;
                    cmbDetailCommentTwoType.SetSelectedString(giftDetailRow.CommentTwoType);
                    txtDetailGiftCommentThree.Text = giftDetailRow.GiftCommentThree;
                    cmbDetailCommentThreeType.SetSelectedString(giftDetailRow.CommentThreeType);
                }

                //Handle tax fields on current row
                if (FSETUseTaxDeductiblePercentageFlag)
                {
                    bool taxDeductible = (giftDetailRow.IsTaxDeductibleNull() ? true : giftDetailRow.TaxDeductible);
                    giftDetailRow.TaxDeductible = taxDeductible;

                    try
                    {
                        FPetraUtilsObject.SuppressChangeDetection = true;
                        chkDetailTaxDeductible.Checked            = taxDeductible;
                        EnableTaxDeductibilityPct(taxDeductible);
                    }
                    finally
                    {
                        FPetraUtilsObject.SuppressChangeDetection = false;
                    }

                    if (!IsSplitGift)
                    {
                        //Most commonly not a split gift (?)
                        if (!taxDeductible)
                        {
                            txtDeductiblePercentage.NumberValueDecimal = 0.0m;
                        }

                        txtTaxDeductAmount.NumberValueDecimal = 0.0m;
                        txtNonDeductAmount.NumberValueDecimal = 0.0m;
                    }
                    else
                    {
                        if (taxDeductible)
                        {
                            //In case the tax percentage has changed or null values in amount fields
                            ReconcileTaxDeductibleAmounts(giftDetailRow);
                        }
                        else
                        {
                            //Changing this will update the unbound amount textboxes
                            txtDeductiblePercentage.NumberValueDecimal = 0.0m;
                        }
                    }
                }

                //Process values that are not bound to a control
                giftDetailRow.ReceiptPrinted = false;
                giftDetailRow.ReceiptNumber  = 0;

                //Now process other gift details if they exist
                if (IsSplitGift)
                {
                    //Only copy amount to first row if copying split gifts
                    txtDetailGiftTransactionAmount.NumberValueDecimal = giftDetailRow.GiftTransactionAmount;

                    // clear previous validation errors.
                    // otherwise we get an error if the user has changed the control immediately after changing the donor key.
                    FPetraUtilsObject.VerificationResultCollection.Clear();

                    bool SelectEndRow = (FBatchRow.LastGiftNumber == FPreviouslySelectedDetailRow.GiftTransactionNumber);

                    //Just retain other details to add
                    giftDetailRow.Delete();
                    GiftDetailTable.AcceptChanges();

                    foreach (DataRowView drv in GiftDetailTable.DefaultView)
                    {
                        GiftBatchTDSAGiftDetailRow detailRow = (GiftBatchTDSAGiftDetailRow)drv.Row;

                        //______________________
                        //Update basic field values
                        detailRow.LedgerNumber          = FLedgerNumber;
                        detailRow.BatchNumber           = FBatchNumber;
                        detailRow.GiftTransactionNumber = AGiftTransactionNumber;
                        detailRow.DetailNumber          = ++FGift.LastDetailNumber;
                        detailRow.DonorName             = APartnerShortName;
                        detailRow.DonorClass            = FPreviouslySelectedDetailRow.DonorClass;
                        detailRow.DateEntered           = FGift.DateEntered;
                        detailRow.MethodOfPaymentCode   = FPreviouslySelectedDetailRow.MethodOfPaymentCode;
                        detailRow.ReceiptPrinted        = false;
                        detailRow.ReceiptNumber         = 0;
                        // Change #5481
                        detailRow.ChargeFlag = true;

                        if (!FSETAutoCopyIncludeMailingCodeFlag)
                        {
                            detailRow.MailingCode = string.Empty;
                        }

                        //______________________
                        //process recipient details to get most recent data
                        Int64         partnerKey       = detailRow.RecipientKey;
                        string        partnerShortName = string.Empty;
                        TPartnerClass partnerClass;
                        bool          recipientIsValid = true;

                        if (TServerLookup.TMPartner.GetPartnerShortName(partnerKey, out partnerShortName, out partnerClass))
                        {
                            detailRow.RecipientDescription = partnerShortName;
                            detailRow.RecipientClass       = partnerClass.ToString();

                            if (partnerClass == TPartnerClass.FAMILY)
                            {
                                detailRow.RecipientLedgerNumber = TRemote.MFinance.Gift.WebConnectors.GetRecipientFundNumber(partnerKey,
                                                                                                                             FGift.DateEntered);
                                detailRow.RecipientField       = detailRow.RecipientLedgerNumber;
                                detailRow.RecipientKeyMinistry = string.Empty;
                            }
                            else
                            {
                                //Class - UNIT
                                Int64  field;
                                string keyMinName;

                                recipientIsValid = TFinanceControls.GetRecipientKeyMinData(partnerKey, out field, out keyMinName);

                                detailRow.RecipientLedgerNumber = field;
                                detailRow.RecipientField        = field;
                                detailRow.RecipientKeyMinistry  = keyMinName;

                                if (!recipientIsValid)
                                {
                                    string msg =
                                        String.Format(Catalog.GetString(
                                                          "Gift: {0}, Detail: {1} has a recipient: '{2}-{3}' that is an inactive Key Ministry!"),
                                                      AGiftTransactionNumber,
                                                      detailRow.DetailNumber,
                                                      partnerKey,
                                                      keyMinName);
                                    MessageBox.Show(msg, Catalog.GetString(
                                                        "Copying Previous Split Gift"), MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                }
                            }
                        }
                        else
                        {
                            recipientIsValid = false;
                            string msg = String.Format(Catalog.GetString("Gift: {0}, Detail: {1} has an invalid Recipient key: '{2}'!"),
                                                       AGiftTransactionNumber,
                                                       detailRow.DetailNumber,
                                                       partnerKey);
                            MessageBox.Show(msg, Catalog.GetString("Copying Previous Split Gift"), MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }

                        //______________________
                        //Process motivation
                        if (string.IsNullOrEmpty(detailRow.MotivationGroupCode))
                        {
                            detailRow.MotivationGroupCode = string.Empty;
                            string msg = String.Format(Catalog.GetString("Gift: {0}, Detail: {1} has no Motivation Group!"),
                                                       AGiftTransactionNumber,
                                                       detailRow.DetailNumber);
                            MessageBox.Show(msg, Catalog.GetString("Copying Previous Split Gift"), MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                        else if (string.IsNullOrEmpty(detailRow.MotivationDetailCode))
                        {
                            detailRow.MotivationDetailCode = string.Empty;
                            string msg = String.Format(Catalog.GetString("Gift: {0}, Detail: {1} has no Motivation Detail!"),
                                                       AGiftTransactionNumber,
                                                       detailRow.DetailNumber);
                            MessageBox.Show(msg, Catalog.GetString("Copying Previous Split Gift"), MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                        else
                        {
                            AMotivationDetailRow motivationDetailRow = null;
                            string motivationGroup  = detailRow.MotivationGroupCode;
                            string motivationDetail = detailRow.MotivationDetailCode;

                            motivationDetailRow = (AMotivationDetailRow)FMainDS.AMotivationDetail.Rows.Find(
                                new object[] { FLedgerNumber, motivationGroup, motivationDetail });

                            if (motivationDetailRow != null)
                            {
                                if (partnerKey > 0)
                                {
                                    bool partnerIsMissingLink = false;

                                    detailRow.CostCentreCode = TRemote.MFinance.Gift.WebConnectors.RetrieveCostCentreCodeForRecipient(FLedgerNumber,
                                                                                                                                      partnerKey,
                                                                                                                                      detailRow.RecipientLedgerNumber,
                                                                                                                                      detailRow.DateEntered,
                                                                                                                                      motivationGroup,
                                                                                                                                      motivationDetail,
                                                                                                                                      out partnerIsMissingLink);
                                }
                                else
                                {
                                    if (motivationGroup != MFinanceConstants.MOTIVATION_GROUP_GIFT)
                                    {
                                        detailRow.RecipientDescription = motivationGroup;
                                    }
                                    else
                                    {
                                        detailRow.RecipientDescription = string.Empty;
                                    }

                                    detailRow.CostCentreCode = motivationDetailRow.CostCentreCode;
                                }

                                detailRow.AccountCode = motivationDetailRow.AccountCode;

                                if (FSETUseTaxDeductiblePercentageFlag && string.IsNullOrEmpty(motivationDetailRow.TaxDeductibleAccountCode))
                                {
                                    detailRow.TaxDeductibleAccountCode = string.Empty;

                                    string msg = String.Format(Catalog.GetString(
                                                                   "Gift: {0}, Detail: {1} has  Motivation Detail: {2} which has no Tax Deductible Account!" +
                                                                   "This can be added in Finance / Setup / Motivation Details.{3}{3}" +
                                                                   "Unless this is changed it will be impossible to assign a Tax Deductible Percentage to this gift."),
                                                               AGiftTransactionNumber,
                                                               detailRow.DetailNumber,
                                                               motivationDetail,
                                                               Environment.NewLine);
                                    MessageBox.Show(msg, Catalog.GetString(
                                                        "Copying Previous Split Gift"), MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                }
                                else
                                {
                                    detailRow.TaxDeductibleAccountCode = motivationDetailRow.TaxDeductibleAccountCode;
                                }
                            }
                            else
                            {
                                string msg =
                                    String.Format(Catalog.GetString(
                                                      "Gift: {0}, Detail: {1} has Motivation Group and Detail codes ('{2} : {3}') not found in the database!"),
                                                  AGiftTransactionNumber,
                                                  detailRow.DetailNumber,
                                                  motivationGroup,
                                                  motivationDetail);
                                MessageBox.Show(msg, Catalog.GetString("Copying Previous Split Gift"), MessageBoxButtons.OK, MessageBoxIcon.Warning);

                                detailRow.TaxDeductible = false;
                            }
                        }

                        //______________________
                        //Handle tax fields
                        detailRow.TaxDeductiblePct = RetrieveTaxDeductiblePct((recipientIsValid ? detailRow.RecipientKey : 0),
                                                                              detailRow.TaxDeductible);

                        AGiftDetailRow giftDetails = (AGiftDetailRow)detailRow;
                        TaxDeductibility.UpdateTaxDeductibiltyAmounts(ref giftDetails);

                        //______________________
                        //Process comments
                        if (!FSETAutoCopyIncludeCommentsFlag)
                        {
                            detailRow.SetCommentOneTypeNull();
                            detailRow.SetCommentTwoTypeNull();
                            detailRow.SetCommentThreeTypeNull();
                            detailRow.SetGiftCommentOneNull();
                            detailRow.SetGiftCommentTwoNull();
                            detailRow.SetGiftCommentThreeNull();
                        }

                        detailRow.AcceptChanges();
                        detailRow.SetAdded();
                    }

                    //Add in the new records (latter two arguments put in to parallel recurring form)
                    FMainDS.AGiftDetail.Merge(GiftDetailTable, false, MissingSchemaAction.Ignore);

                    int indexOfLatestRow = FMainDS.AGiftDetail.Rows.Count - 1;

                    //Select last row added
                    if (SelectEndRow)
                    {
                        grdDetails.SelectRowInGrid(grdDetails.Rows.Count - 1);
                    }
                    else if (!SelectDetailRowByDataTableIndex(indexOfLatestRow))
                    {
                        if (!FFilterAndFindObject.IsActiveFilterEqualToBase)
                        {
                            MessageBox.Show(
                                MCommonResourcestrings.StrNewRecordIsFiltered,
                                MCommonResourcestrings.StrAddNewRecordTitle,
                                MessageBoxButtons.OK, MessageBoxIcon.Information);
                            FFilterAndFindObject.FilterPanelControls.ClearAllDiscretionaryFilters();

                            if (FFilterAndFindObject.FilterFindPanel.ShowApplyFilterButton != TUcoFilterAndFind.FilterContext.None)
                            {
                                FFilterAndFindObject.ApplyFilter();
                            }

                            SelectDetailRowByDataTableIndex(indexOfLatestRow);
                        }
                    }

                    ClearKeyMinistries();
                    cmbMotivationDetailCode.Clear();
                    mniRecipientHistory.Enabled = false;
                    btnDeleteAll.Enabled        = btnDelete.Enabled;
                    UpdateRecordNumberDisplay();
                    FLastDonor = -1;
                }
                else
                {
                    txtDetailDonorKey.FocusTextBoxPartAfterFindScreenCloses = false;
                    txtDetailGiftTransactionAmount.Focus();
                }

                FPetraUtilsObject.SetChangedFlag();
            }
            finally
            {
                this.Cursor = Cursors.Default;
                FAutoPopulatingGiftInProcess = false;
            }
        }
示例#22
0
        private bool OnDeleteRowManual(GiftBatchTDSAGiftDetailRow ARowToDelete, ref string ACompletionMessage)
        {
            bool DeletionSuccessful = false;

            List <string> OriginatingDetailRef = new List <string>();

            ACompletionMessage = string.Empty;

            if (ARowToDelete == null)
            {
                return(DeletionSuccessful);
            }

            bool RowToDeleteIsNew = (ARowToDelete.RowState == DataRowState.Added);

            if (!RowToDeleteIsNew)
            {
                try
                {
                    // temporarily disable  New Donor Warning
                    ((TFrmGiftBatch)this.ParentForm).NewDonorWarning = false;

                    //Return modified row to last saved state to avoid validation failures
                    ARowToDelete.RejectChanges();
                    ShowDetails(ARowToDelete);

                    if (!((TFrmGiftBatch)this.ParentForm).SaveChanges())
                    {
                        MessageBox.Show(Catalog.GetString("Error in trying to save prior to deleting current gift detail!"),
                                        Catalog.GetString("Deletion Error"),
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);

                        return(DeletionSuccessful);
                    }
                }
                finally
                {
                    ((TFrmGiftBatch)this.ParentForm).NewDonorWarning = true;
                }
            }

            //Backup the Dataset for reversion purposes
            GiftBatchTDS BackupMainDS = (GiftBatchTDS)FMainDS.Copy();

            BackupMainDS.Merge(FMainDS);

            //To be used later....Pass copy to delete method.
            //GiftBatchTDS TempDS = (GiftBatchTDS)FMainDS.Copy();
            //TempDS.Merge(FMainDS);

            int    SelectedDetailNumber        = ARowToDelete.DetailNumber;
            int    GiftToDeleteTransNo         = 0;
            string FilterAllGiftsOfBatch       = String.Empty;
            string FilterAllGiftDetailsOfBatch = String.Empty;

            int DetailRowCount = FGiftDetailView.Count;

            try
            {
                this.Cursor = Cursors.WaitCursor;

                //Speeds up deletion of larger gift sets
                FMainDS.EnforceConstraints = false;

                if ((ARowToDelete.ModifiedDetailKey != null) && (ARowToDelete.ModifiedDetailKey.Length > 0))
                {
                    OriginatingDetailRef.Add(ARowToDelete.ModifiedDetailKey);
                }

                //Delete current detail row
                ARowToDelete.Delete();

                //If there existed (before the delete row above) more than one detail row, then no need to delete gift header row
                if (DetailRowCount > 1)
                {
                    ACompletionMessage = Catalog.GetString("Gift Detail row deleted successfully!");

                    FGiftSelectedForDeletion = false;

                    foreach (DataRowView rv in FGiftDetailView)
                    {
                        GiftBatchTDSAGiftDetailRow row = (GiftBatchTDSAGiftDetailRow)rv.Row;

                        if (row.DetailNumber > SelectedDetailNumber)
                        {
                            row.DetailNumber--;
                        }
                    }

                    FGift.LastDetailNumber--;

                    FPetraUtilsObject.SetChangedFlag();
                }
                else
                {
                    ACompletionMessage = Catalog.GetString("Gift deleted successfully!");

                    GiftToDeleteTransNo = FGift.GiftTransactionNumber;

                    // Reduce all Gift Detail row Transaction numbers by 1 if they are greater then gift to be deleted
                    FilterAllGiftDetailsOfBatch = String.Format("{0}={1} And {2}>{3}",
                                                                AGiftDetailTable.GetBatchNumberDBName(),
                                                                FBatchNumber,
                                                                AGiftDetailTable.GetGiftTransactionNumberDBName(),
                                                                GiftToDeleteTransNo);

                    DataView giftDetailView = new DataView(FMainDS.AGiftDetail);
                    giftDetailView.RowFilter = FilterAllGiftDetailsOfBatch;
                    giftDetailView.Sort      = String.Format("{0} ASC", AGiftDetailTable.GetGiftTransactionNumberDBName());

                    foreach (DataRowView rv in giftDetailView)
                    {
                        GiftBatchTDSAGiftDetailRow row = (GiftBatchTDSAGiftDetailRow)rv.Row;

                        row.GiftTransactionNumber--;
                    }

                    //Cannot delete the gift row, just copy the data of rows above down by 1 row
                    // and then mark the top row for deletion
                    //In other words, bubble the gift row to be deleted to the top
                    FilterAllGiftsOfBatch = String.Format("{0}={1} And {2}>={3}",
                                                          AGiftTable.GetBatchNumberDBName(),
                                                          FBatchNumber,
                                                          AGiftTable.GetGiftTransactionNumberDBName(),
                                                          GiftToDeleteTransNo);

                    DataView giftView = new DataView(FMainDS.AGift);
                    giftView.RowFilter = FilterAllGiftsOfBatch;
                    giftView.Sort      = String.Format("{0} ASC", AGiftTable.GetGiftTransactionNumberDBName());

                    AGiftRow giftRowToReceive  = null;
                    AGiftRow giftRowToCopyDown = null;
                    AGiftRow giftRowCurrent    = null;

                    int currentGiftTransNo = 0;

                    foreach (DataRowView gv in giftView)
                    {
                        giftRowCurrent = (AGiftRow)gv.Row;

                        currentGiftTransNo = giftRowCurrent.GiftTransactionNumber;

                        if (currentGiftTransNo > GiftToDeleteTransNo)
                        {
                            giftRowToCopyDown = giftRowCurrent;

                            //Copy column values down
                            for (int j = 3; j < giftRowToCopyDown.Table.Columns.Count; j++)
                            {
                                //Update all columns except the pk fields that remain the same
                                if (!giftRowToCopyDown.Table.Columns[j].ColumnName.EndsWith("_text"))
                                {
                                    giftRowToReceive[j] = giftRowToCopyDown[j];
                                }
                            }
                        }

                        if (currentGiftTransNo == FBatchRow.LastGiftNumber)
                        {
                            //Mark last record for deletion
                            giftRowCurrent.GiftStatus = MFinanceConstants.MARKED_FOR_DELETION;
                        }

                        //Will always be previous row
                        giftRowToReceive = giftRowCurrent;
                    }

                    FPreviouslySelectedDetailRow = null;

                    FPetraUtilsObject.SetChangedFlag();

                    FGiftSelectedForDeletion = true;

                    FBatchRow.LastGiftNumber--;
                }

                //Try to save changes
                if (((TFrmGiftBatch)this.ParentForm).SaveChangesManual())
                {
                    //Check if have deleted a reversing gift detail
                    if (OriginatingDetailRef.Count > 0)
                    {
                        TRemote.MFinance.Gift.WebConnectors.ReversedGiftReset(FLedgerNumber, OriginatingDetailRef);
                    }

                    //Clear current batch's gift data and reload from server
                    RefreshCurrentBatchGiftData(FBatchNumber, true);
                }
                else
                {
                    throw new Exception("Unable to save after deleting a gift!");
                }

                DeletionSuccessful = true;
            }
            catch (Exception ex)
            {
                //Revert to previous state
                RevertDataSet(FMainDS, BackupMainDS);

                TLogging.LogException(ex, Utilities.GetMethodSignature());
                throw;
            }
            finally
            {
                FMainDS.EnforceConstraints = true;
                SetGiftDetailDefaultView();
                FFilterAndFindObject.ApplyFilter();
                this.Cursor = Cursors.Default;
            }

            UpdateRecordNumberDisplay();

            return(DeletionSuccessful);
        }
        /// <summary>
        /// Method to cancel a specified batch
        /// </summary>
        /// <param name="ACurrentBatchRow"></param>
        /// <returns></returns>
        public bool CancelBatch(AGiftBatchRow ACurrentBatchRow)
        {
            //Assign default value(s)
            bool CancellationSuccessful = false;

            string CancelMessage     = string.Empty;
            string CompletionMessage = string.Empty;

            List <string> ModifiedDetailKeys = new List <string>();

            if ((ACurrentBatchRow == null) || (ACurrentBatchRow.BatchStatus != MFinanceConstants.BATCH_UNPOSTED))
            {
                return(CancellationSuccessful);
            }

            int CurrentBatchNo = ACurrentBatchRow.BatchNumber;

            CancelMessage = String.Format(Catalog.GetString("Are you sure you want to cancel gift batch number: {0}?"),
                                          ACurrentBatchRow.BatchNumber);

            if ((MessageBox.Show(CancelMessage,
                                 "Cancel Batch",
                                 MessageBoxButtons.YesNo,
                                 MessageBoxIcon.Question,
                                 MessageBoxDefaultButton.Button2) != System.Windows.Forms.DialogResult.Yes))
            {
                return(CancellationSuccessful);
            }

            //Backup the Dataset for reversion purposes
            GiftBatchTDS BackupMainDS = (GiftBatchTDS)FMainDS.Copy();

            BackupMainDS.Merge(FMainDS);

            try
            {
                FMyForm.Cursor = Cursors.WaitCursor;

                //Normally need to set the message parameters before the delete is performed if requiring any of the row values
                CompletionMessage = String.Format(Catalog.GetString("Batch no.: {0} cancelled successfully."),
                                                  ACurrentBatchRow.BatchNumber);

                FMyForm.GetBatchControl().UndoModifiedBatchRow(ACurrentBatchRow, true);

                //Load all journals for current Batch
                //clear any transactions currently being editied in the Transaction Tab
                FMyForm.GetTransactionsControl().ClearCurrentSelection();

                //Delete transactions
                DataView GiftDV       = new DataView(FMainDS.AGift);
                DataView GiftDetailDV = new DataView(FMainDS.AGiftDetail);

                GiftDV.AllowDelete       = true;
                GiftDetailDV.AllowDelete = true;

                GiftDV.RowFilter = String.Format("{0}={1}",
                                                 AGiftTable.GetBatchNumberDBName(),
                                                 CurrentBatchNo);

                GiftDV.Sort = AGiftTable.GetGiftTransactionNumberDBName() + " DESC";

                GiftDetailDV.RowFilter = String.Format("{0}={1}",
                                                       AGiftDetailTable.GetBatchNumberDBName(),
                                                       CurrentBatchNo);

                GiftDetailDV.Sort = String.Format("{0} DESC, {1} DESC",
                                                  AGiftDetailTable.GetGiftTransactionNumberDBName(),
                                                  AGiftDetailTable.GetDetailNumberDBName());

                foreach (DataRowView drv in GiftDetailDV)
                {
                    AGiftDetailRow gdr = (AGiftDetailRow)drv.Row;

                    // if the gift detail being cancelled is a reversed gift
                    if (gdr.ModifiedDetail && !string.IsNullOrEmpty(gdr.ModifiedDetailKey))
                    {
                        ModifiedDetailKeys.Add(gdr.ModifiedDetailKey);
                    }

                    gdr.Delete();
                }

                for (int i = 0; i < GiftDV.Count; i++)
                {
                    GiftDV.Delete(i);
                }

                //Batch is only cancelled and never deleted
                ACurrentBatchRow.BatchTotal     = 0;
                ACurrentBatchRow.LastGiftNumber = 0;
                ACurrentBatchRow.BatchStatus    = MFinanceConstants.BATCH_CANCELLED;

                FPetraUtilsObject.SetChangedFlag();

                // save first
                if (FMyForm.SaveChanges())
                {
                    if (ModifiedDetailKeys.Count > 0)
                    {
                        TRemote.MFinance.Gift.WebConnectors.ReversedGiftReset(FLedgerNumber, ModifiedDetailKeys);
                    }

                    MessageBox.Show(CompletionMessage,
                                    "Batch Cancelled",
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Information);
                }
                else
                {
                    throw new Exception(Catalog.GetString("The batch failed to save after being cancelled! Reopen the form and retry."));
                }

                CancellationSuccessful = true;
            }
            catch (Exception ex)
            {
                //Revert to previous state
                FMainDS.Merge(BackupMainDS);

                CompletionMessage = ex.Message;
                MessageBox.Show(CompletionMessage,
                                "Cancellation Error",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);

                TLogging.LogException(ex, Utilities.GetMethodSignature());
                throw;
            }
            finally
            {
                FMyForm.Cursor = Cursors.Default;
            }

            return(CancellationSuccessful);
        }
示例#24
0
        public static Int32 FieldChangeAdjustment(Int32 ALedgerNumber,
                                                  Int64 ARecipientKey,
                                                  DateTime AStartDate,
                                                  DateTime AEndDate,
                                                  Int64 AOldField,
                                                  DateTime ADateCorrection,
                                                  bool AWithReceipt)
        {
            TDBTransaction Transaction = DBAccess.GDBAccessObj.BeginTransaction(IsolationLevel.ReadCommitted);
            GiftBatchTDS   oldGiftDS   = new GiftBatchTDS();

            try
            {
                // find all gifts that need reversing.
                // criteria:
                // posted gift batches only
                // no adjusted/reversed gifts
                // date of gift batch in specified date range
                // recipient field is the old field
                string SqlStmt = TDataBase.ReadSqlFile("Gift.GetGiftsToReverse.sql");

                List <OdbcParameter> parameters = new List <OdbcParameter>();
                OdbcParameter        param      = new OdbcParameter("LedgerNumber", OdbcType.Int);
                param.Value = ALedgerNumber;
                parameters.Add(param);
                param       = new OdbcParameter("StartDate", OdbcType.Date);
                param.Value = AStartDate;
                parameters.Add(param);
                param       = new OdbcParameter("EndDate", OdbcType.Date);
                param.Value = AEndDate;
                parameters.Add(param);
                param       = new OdbcParameter("RecipientKey", OdbcType.BigInt);
                param.Value = ARecipientKey;
                parameters.Add(param);
                param       = new OdbcParameter("OldField", OdbcType.BigInt);
                param.Value = AOldField;
                parameters.Add(param);

                DBAccess.GDBAccessObj.Select(oldGiftDS, SqlStmt, oldGiftDS.AGiftDetail.TableName, Transaction, parameters.ToArray());

                // load the gift and the gift batch records if they have not been loaded yet
                foreach (AGiftDetailRow giftdetail in oldGiftDS.AGiftDetail.Rows)
                {
                    oldGiftDS.AGift.DefaultView.RowFilter = String.Format("{0} = {1} and {2} = {3}",
                                                                          AGiftTable.GetBatchNumberDBName(),
                                                                          giftdetail.BatchNumber,
                                                                          AGiftTable.GetGiftTransactionNumberDBName(),
                                                                          giftdetail.GiftTransactionNumber);

                    if (oldGiftDS.AGift.DefaultView.Count == 0)
                    {
                        AGiftTable tempGiftTable =
                            AGiftAccess.LoadByPrimaryKey(giftdetail.LedgerNumber,
                                                         giftdetail.BatchNumber,
                                                         giftdetail.GiftTransactionNumber,
                                                         Transaction);
                        oldGiftDS.AGift.Merge(tempGiftTable);
                    }

                    oldGiftDS.AGiftBatch.DefaultView.RowFilter = String.Format("{0} = {1}",
                                                                               AGiftTable.GetBatchNumberDBName(),
                                                                               giftdetail.BatchNumber);

                    if (oldGiftDS.AGiftBatch.DefaultView.Count == 0)
                    {
                        AGiftBatchTable tempGiftBatchTable =
                            AGiftBatchAccess.LoadByPrimaryKey(giftdetail.LedgerNumber,
                                                              giftdetail.BatchNumber,
                                                              Transaction);
                        oldGiftDS.AGiftBatch.Merge(tempGiftBatchTable);
                    }
                }

                DBAccess.GDBAccessObj.RollbackTransaction();
            }
            catch (Exception)
            {
                DBAccess.GDBAccessObj.RollbackTransaction();
                throw;
            }

            // we need to create a gift batch for each set of gifts with the same Currency, BankAccountCode, BankCostCentre, and Gift Type
            SortedList <string, GiftBatchTDS> NewGiftBatches = new SortedList <string, GiftBatchTDS>();

            foreach (GiftBatchTDSAGiftDetailRow oldGiftDetail in oldGiftDS.AGiftDetail.Rows)
            {
                // get the gift batch row for this detail
                oldGiftDS.AGiftBatch.DefaultView.RowFilter =
                    String.Format("{0} = {1}",
                                  AGiftTable.GetBatchNumberDBName(), oldGiftDetail.BatchNumber);

                AGiftBatchRow oldGiftBatch = (AGiftBatchRow)oldGiftDS.AGiftBatch.DefaultView[0].Row;

                GiftBatchTDS GiftDS = CreateNewGiftBatch(NewGiftBatches, oldGiftBatch, ADateCorrection);

                AGiftBatchRow giftbatchRow = GiftDS.AGiftBatch[0];

                // get the gift row for this detail
                DataView v = oldGiftDS.AGift.DefaultView;
                v.RowFilter =
                    String.Format("{0} = {1} and {2} = {3}",
                                  AGiftTable.GetBatchNumberDBName(), oldGiftDetail.BatchNumber,
                                  AGiftTable.GetGiftTransactionNumberDBName(), oldGiftDetail.GiftTransactionNumber);

                AGiftRow oldGift = (AGiftRow)v[0].Row;

                AGiftRow gift = GiftDS.AGift.NewRowTyped();
                gift.LedgerNumber          = giftbatchRow.LedgerNumber;
                gift.BatchNumber           = giftbatchRow.BatchNumber;
                gift.GiftTransactionNumber = giftbatchRow.LastGiftNumber + 1;
                gift.DonorKey    = oldGift.DonorKey;
                gift.DateEntered = ADateCorrection;
                giftbatchRow.LastGiftNumber++;
                GiftDS.AGift.Rows.Add(gift);

                if (!AWithReceipt)
                {
                    gift.ReceiptLetterCode = "NO*RECET";
                }

                // reverse the original gift
                GiftBatchTDSAGiftDetailRow detail = GiftDS.AGiftDetail.NewRowTyped();

                DataUtilities.CopyAllColumnValues(oldGiftDetail, detail);

                detail.LedgerNumber          = gift.LedgerNumber;
                detail.BatchNumber           = gift.BatchNumber;
                detail.GiftTransactionNumber = gift.GiftTransactionNumber;
                detail.DetailNumber          = gift.LastDetailNumber + 1;
                detail.GiftAmount            = detail.GiftAmount * -1;
                detail.GiftAmountIntl        = detail.GiftAmountIntl * -1;
                detail.GiftTransactionAmount = detail.GiftTransactionAmount * -1;
                gift.LastDetailNumber++;

                GiftDS.AGiftDetail.Rows.Add(detail);

                // create the detail for the corrected gift to the new field
                detail = GiftDS.AGiftDetail.NewRowTyped();

                DataUtilities.CopyAllColumnValues(oldGiftDetail, detail);

                detail.LedgerNumber          = gift.LedgerNumber;
                detail.BatchNumber           = gift.BatchNumber;
                detail.GiftTransactionNumber = gift.GiftTransactionNumber;
                detail.DetailNumber          = gift.LastDetailNumber + 1;
                detail.GiftCommentOne        = String.Format(Catalog.GetString("posted on {0}"), oldGiftBatch.GlEffectiveDate.ToShortDateString());
                gift.LastDetailNumber++;

                // TODO: calculate costcentre code from current commitment; this currently is done only at time of posting
                // detail.RecipientLedgerNumber = oldGiftDetail.RecipientLedgerNumber;
                // detail.CostCentreCode = oldGiftDetail.CostCentreCode;

                GiftDS.AGiftDetail.Rows.Add(detail);

                // TODO: how to make sure that the gl transaction is marked as System generated? avoid display on HOSA?

                // mark original gift detail as modified
                oldGiftDetail.ModifiedDetail = true;
            }

            TVerificationResultCollection VerificationResult;

            TSubmitChangesResult result = TSubmitChangesResult.scrOK;

            for (Int32 batchCounter = 0; batchCounter < NewGiftBatches.Count; batchCounter++)
            {
                if (result == TSubmitChangesResult.scrOK)
                {
                    GiftBatchTDS GiftDS = NewGiftBatches.Values[batchCounter];
                    result = TGiftTransactionWebConnector.SaveGiftBatchTDS(ref GiftDS, out VerificationResult);
                }
            }

            if (result == TSubmitChangesResult.scrOK)
            {
                result = TGiftTransactionWebConnector.SaveGiftBatchTDS(ref oldGiftDS, out VerificationResult);

                if ((result == TSubmitChangesResult.scrOK) && (NewGiftBatches.Count > 0))
                {
                    return(NewGiftBatches.Values[0].AGiftBatch[0].BatchNumber);
                }
            }

            return(-1);
        }
示例#25
0
        public static bool GiftRevertAdjust(Hashtable requestParams, out int AAdjustmentBatchNumber, GiftBatchTDS AGiftDS)
        {
            AAdjustmentBatchNumber = 0;
            int AdjustmentBatchNo = AAdjustmentBatchNumber;

            if ((AGiftDS == null) || (AGiftDS.AGiftDetail == null) || (AGiftDS.AGiftDetail.Rows.Count == 0))
            {
                TLogging.Log("Empty dataset sent to GiftRevertAdjust");
                return(false);
            }

            Int32   ALedgerNumber = (Int32)requestParams["ALedgerNumber"];
            Boolean BatchSelected = (Boolean)requestParams["NewBatchSelected"];
            GiftAdjustmentFunctionEnum Function = (GiftAdjustmentFunctionEnum)requestParams["Function"];
            Int32 GiftDetailNumber = (Int32)requestParams["GiftDetailNumber"];
            bool  NoReceipt        = (Boolean)requestParams["NoReceipt"];

            DateTime DateEffective;
            decimal  batchGiftTotal  = 0;
            Int32    ANewBatchNumber = (BatchSelected ? (Int32)requestParams["NewBatchNumber"] : 0);

            TDBTransaction Transaction  = null;
            bool           SubmissionOK = false;

            try
            {
                DBAccess.GDBAccessObj.GetNewOrExistingAutoTransaction(IsolationLevel.Serializable,
                                                                      ref Transaction,
                                                                      ref SubmissionOK,
                                                                      delegate
                {
                    ALedgerTable ledgerTable = ALedgerAccess.LoadByPrimaryKey(ALedgerNumber, Transaction);

                    AGiftBatchRow giftBatch;

                    // if we need to create a new gift batch
                    if (!BatchSelected)
                    {
                        giftBatch = CreateNewGiftBatch(requestParams, ref AGiftDS, out DateEffective, ref ledgerTable, Transaction);
                    }
                    else     // using an existing gift batch
                    {
                        AGiftBatchAccess.LoadByPrimaryKey(AGiftDS, ALedgerNumber, ANewBatchNumber, Transaction);

                        giftBatch     = AGiftDS.AGiftBatch[0];
                        DateEffective = giftBatch.GlEffectiveDate;
                        //If into an existing batch, then retrive the existing batch total
                        batchGiftTotal = giftBatch.BatchTotal;
                    }

                    AdjustmentBatchNo = giftBatch.BatchNumber;

                    //assuming new elements are added after these static borders

                    AGiftDS.AGift.DefaultView.Sort = string.Format("{0}, {1}",
                                                                   AGiftTable.GetBatchNumberDBName(),
                                                                   AGiftTable.GetGiftTransactionNumberDBName());

                    AGiftDS.AGiftDetail.DefaultView.Sort = string.Format("{0}, {1}, {2}",
                                                                         AGiftDetailTable.GetBatchNumberDBName(),
                                                                         AGiftDetailTable.GetGiftTransactionNumberDBName(),
                                                                         AGiftDetailTable.GetDetailNumberDBName());

                    foreach (DataRowView giftRow in AGiftDS.AGift.DefaultView)
                    {
                        int cycle = 0;

                        // first cycle creates gift reversal; second cycle creates new adjusted gift (if needed)
                        do
                        {
                            AGiftRow oldGift = (AGiftRow)giftRow.Row;

                            if (oldGift.RowState != DataRowState.Added)
                            {
                                AGiftRow gift = AGiftDS.AGift.NewRowTyped(true);
                                DataUtilities.CopyAllColumnValuesWithoutPK(oldGift, gift);
                                gift.LedgerNumber          = giftBatch.LedgerNumber;
                                gift.BatchNumber           = giftBatch.BatchNumber;
                                gift.DateEntered           = DateEffective;
                                gift.GiftTransactionNumber = giftBatch.LastGiftNumber + 1;
                                giftBatch.LastGiftNumber++;
                                gift.LinkToPreviousGift = (cycle != 0);
                                gift.LastDetailNumber   = 0;

                                // do not print a receipt for reversed gifts
                                if (cycle == 0)
                                {
                                    gift.ReceiptPrinted = true;
                                    gift.PrintReceipt   = false;
                                }
                                else
                                {
                                    gift.ReceiptPrinted = false;
                                    gift.PrintReceipt   = !NoReceipt;
                                }

                                AGiftDS.AGift.Rows.Add(gift);

                                foreach (DataRowView giftDetailRow in AGiftDS.AGiftDetail.DefaultView)
                                {
                                    AGiftDetailRow oldGiftDetail = (AGiftDetailRow)giftDetailRow.Row;

                                    // if gift detail belongs to gift
                                    if ((oldGiftDetail.GiftTransactionNumber == oldGift.GiftTransactionNumber) &&
                                        (oldGiftDetail.BatchNumber == oldGift.BatchNumber) &&
                                        (!Function.Equals(GiftAdjustmentFunctionEnum.ReverseGiftDetail) ||
                                         (oldGiftDetail.DetailNumber == GiftDetailNumber)))
                                    {
                                        AddDuplicateGiftDetailToGift(ref AGiftDS, ref gift, oldGiftDetail, cycle == 0, Transaction,
                                                                     requestParams);

                                        batchGiftTotal += oldGiftDetail.GiftTransactionAmount * ((cycle == 0) ? -1 : 1);

                                        // original gift also gets marked as a reversal
                                        oldGiftDetail.ModifiedDetail = true;
                                    }
                                }
                            }

                            cycle++;
                        } while ((cycle < 2) &&
                                 (Function.Equals(GiftAdjustmentFunctionEnum.AdjustGift) ||
                                  Function.Equals(GiftAdjustmentFunctionEnum.FieldAdjust) ||
                                  Function.Equals(GiftAdjustmentFunctionEnum.TaxDeductiblePctAdjust)));
                    }

                    //When reversing into a new or existing batch, set batch total
                    if (!Function.Equals(GiftAdjustmentFunctionEnum.AdjustGift))
                    {
                        giftBatch.BatchTotal = batchGiftTotal;
                    }

                    // save everything at the end
                    AGiftBatchAccess.SubmitChanges(AGiftDS.AGiftBatch, Transaction);
                    ALedgerAccess.SubmitChanges(ledgerTable, Transaction);
                    AGiftAccess.SubmitChanges(AGiftDS.AGift, Transaction);
                    AGiftDetailAccess.SubmitChanges(AGiftDS.AGiftDetail, Transaction);

                    AGiftDS.AGiftBatch.AcceptChanges();

                    SubmissionOK = true;
                });
            }
            catch (Exception ex)
            {
                TLogging.LogException(ex, Utilities.GetMethodSignature());
                throw new EOPAppException(Catalog.GetString("Gift Reverse/Adjust failed."), ex);
            }

            AAdjustmentBatchNumber = AdjustmentBatchNo;

            return(SubmissionOK);
        }