Beispiel #1
0
        public static bool DeletePartner(Int64 APartnerKey, out TVerificationResultCollection AVerificationResult)
        {
            string ShortName;
            TPartnerClass PartnerClass;
            TStdPartnerStatusCode PartnerStatusCode;
            bool ResultValue = false;

            AVerificationResult = null;
            ResultValue = true;

            TDBTransaction Transaction = null;
            bool SubmissionOK = false;

            DBAccess.GDBAccessObj.GetNewOrExistingAutoTransaction(IsolationLevel.Serializable, TEnforceIsolationLevel.eilMinimum,
                ref Transaction, ref SubmissionOK,
                delegate
                {
                    ResultValue =
                        MCommonMain.RetrievePartnerShortName(APartnerKey, out ShortName, out PartnerClass, out PartnerStatusCode, Transaction);

                    /* s_user - delete not allowed by CanPartnerBeDeleted */
                    if (ResultValue)
                    {
                        ResultValue = DeleteEntries(PRecentPartnersTable.GetTableDBName(),
                            PRecentPartnersTable.GetPartnerKeyDBName(),
                            APartnerKey, Transaction);
                    }

                    if (ResultValue)
                    {
                        ResultValue = DeleteEntries(PPartnerGraphicTable.GetTableDBName(),
                            PPartnerGraphicTable.GetPartnerKeyDBName(),
                            APartnerKey, Transaction);
                    }

                    /* Delete extract entries before possibly attempting to delete a  */
                    /* location record referenced in the extract.  Decrease key count */
                    /* in m_extract_master.                                           */
                    if (ResultValue)
                    {
                        // first make sure that extract master tables are up to date
                        // (decrease key count by number of rows to be deleted)
                        MExtractMasterTable ExtractMasterTable;
                        MExtractMasterRow ExtractMasterRow;
                        MExtractTable ExtractTable = MExtractAccess.LoadViaPPartner(APartnerKey, Transaction);

                        foreach (DataRow Row in ExtractTable.Rows)
                        {
                            ExtractMasterTable = MExtractMasterAccess.LoadByPrimaryKey(((MExtractRow)Row).ExtractId, Transaction);
                            ExtractMasterRow = (MExtractMasterRow)ExtractMasterTable.Rows[0];
                            ExtractMasterRow.KeyCount = ExtractMasterRow.KeyCount - 1;
                            MExtractMasterAccess.SubmitChanges(ExtractMasterTable, Transaction);
                        }

                        // now delete the actual extract entries
                        ResultValue = DeleteEntries(MExtractTable.GetTableDBName(),
                            MExtractTable.GetPartnerKeyDBName(),
                            APartnerKey, Transaction);
                    }

                    // Delete Partner Location. If locations were only used by this partner then also delete location record.
                    if (ResultValue)
                    {
                        PPartnerLocationTable PartnerLocationTable = PPartnerLocationAccess.LoadViaPPartner(APartnerKey, Transaction);
                        PPartnerLocationTable OtherPartnerLocationTable;
                        PPartnerLocationRow PartnerLocationRow;
                        PLocationRow LocationRow;
                        PLocationTable LocationTableToDelete = new PLocationTable();

                        foreach (DataRow Row in PartnerLocationTable.Rows)
                        {
                            PartnerLocationRow = (PPartnerLocationRow)Row;
                            OtherPartnerLocationTable = PPartnerLocationAccess.LoadViaPLocation(PartnerLocationRow.SiteKey,
                                PartnerLocationRow.LocationKey,
                                Transaction);

                            // if there is only one partner left using this location (which must be this one) then delete location
                            if ((OtherPartnerLocationTable.Count == 1)
                                && (PartnerLocationRow.LocationKey != 0))
                            {
                                LocationRow = LocationTableToDelete.NewRowTyped();
                                LocationRow.SiteKey = PartnerLocationRow.SiteKey;
                                LocationRow.LocationKey = PartnerLocationRow.LocationKey;
                                LocationTableToDelete.Rows.Add(LocationRow);
                            }
                        }

                        // now first delete the partner locations
                        ResultValue = DeleteEntries(PPartnerLocationTable.GetTableDBName(),
                            PPartnerLocationTable.GetPartnerKeyDBName(),
                            APartnerKey, Transaction);

                        // and now locations if they don't refer to any partners any longer
                        foreach (DataRow RowToDelete in LocationTableToDelete.Rows)
                        {
                            LocationRow = (PLocationRow)RowToDelete;
                            PLocationAccess.DeleteByPrimaryKey(LocationRow.SiteKey, LocationRow.LocationKey, Transaction);
                        }
                    }

                    if (ResultValue)
                    {
                        TSearchCriteria[] PartnerAttributeAccessSC = new TSearchCriteria[] {
                            new TSearchCriteria(PPartnerAttributeTable.GetPartnerKeyDBName(),
                                APartnerKey)
                        };

                        if (PPartnerAttributeAccess.CountUsingTemplate(PartnerAttributeAccessSC, Transaction) > 0)
                        {
                            PPartnerAttributeAccess.DeleteUsingTemplate(PartnerAttributeAccessSC, Transaction);
                        }
                    }

                    if (ResultValue)
                    {
                        ResultValue = ZeroEntries(PChurchTable.GetTableDBName(),
                            PChurchTable.GetContactPartnerKeyDBName(),
                            APartnerKey, Transaction);
                    }

                    if (ResultValue)
                    {
                        ResultValue = ZeroEntries(POrganisationTable.GetTableDBName(),
                            POrganisationTable.GetContactPartnerKeyDBName(),
                            APartnerKey, Transaction);
                    }

                    if (ResultValue)
                    {
                        ResultValue = ZeroEntries(PBankTable.GetTableDBName(),
                            PBankTable.GetContactPartnerKeyDBName(),
                            APartnerKey, Transaction);
                    }

                    if (ResultValue)
                    {
                        ResultValue = ZeroEntries(PVenueTable.GetTableDBName(),
                            PVenueTable.GetContactPartnerKeyDBName(),
                            APartnerKey, Transaction);
                    }

                    // Delete Partner Banking Details.
                    // If Banking Details were only used by this partner then also delete Banking Details record.
                    if (ResultValue)
                    {
                        PPartnerBankingDetailsTable PartnerBankingDetailsTable =
                            PPartnerBankingDetailsAccess.LoadViaPPartner(APartnerKey, Transaction);
                        PPartnerBankingDetailsTable OtherPartnerBankingDetailsTable;
                        PPartnerBankingDetailsRow PartnerBankingDetailsRow;
                        PBankingDetailsRow BankingDetailsRow;
                        PBankingDetailsTable BankingDetailsTableToDelete = new PBankingDetailsTable();

                        foreach (DataRow Row in PartnerBankingDetailsTable.Rows)
                        {
                            PartnerBankingDetailsRow = (PPartnerBankingDetailsRow)Row;
                            OtherPartnerBankingDetailsTable = PPartnerBankingDetailsAccess.LoadViaPBankingDetails(
                                PartnerBankingDetailsRow.BankingDetailsKey,
                                Transaction);

                            // if there is only one partner left using this banking details record (which must be this one) then delete banking details
                            if (OtherPartnerBankingDetailsTable.Count == 1)
                            {
                                BankingDetailsRow = BankingDetailsTableToDelete.NewRowTyped();
                                BankingDetailsRow.BankingDetailsKey = PartnerBankingDetailsRow.BankingDetailsKey;
                                BankingDetailsTableToDelete.Rows.Add(BankingDetailsRow);
                            }
                        }

                        // now first delete the partner banking details
                        ResultValue = DeleteEntries(PPartnerBankingDetailsTable.GetTableDBName(),
                            PPartnerBankingDetailsTable.GetPartnerKeyDBName(),
                            APartnerKey, Transaction);

                        // and now banking details if they don't refer to any partners any longer
                        foreach (DataRow RowToDelete in BankingDetailsTableToDelete.Rows)
                        {
                            BankingDetailsRow = (PBankingDetailsRow)RowToDelete;
                            PBankingDetailsAccess.DeleteByPrimaryKey(BankingDetailsRow.BankingDetailsKey, Transaction);
                        }
                    }

                    if (ResultValue)
                    {
                        ResultValue = DeleteEntries(PPartnerTypeTable.GetTableDBName(),
                            PPartnerTypeTable.GetPartnerKeyDBName(),
                            APartnerKey, Transaction);
                    }

                    if (ResultValue)
                    {
                        ResultValue = DeleteEntries(PPartnerRelationshipTable.GetTableDBName(),
                            PPartnerRelationshipTable.GetPartnerKeyDBName(),
                            APartnerKey, Transaction);
                    }

                    if (ResultValue)
                    {
                        ResultValue = DeleteEntries(PPartnerRelationshipTable.GetTableDBName(),
                            PPartnerRelationshipTable.GetRelationKeyDBName(),
                            APartnerKey, Transaction);
                    }

                    if (ResultValue)
                    {
                        ResultValue = DeleteEntries(PCustomisedGreetingTable.GetTableDBName(),
                            PCustomisedGreetingTable.GetPartnerKeyDBName(),
                            APartnerKey, Transaction);
                    }

                    if (ResultValue)
                    {
                        ResultValue = DeleteEntries(PSubscriptionTable.GetTableDBName(),
                            PSubscriptionTable.GetPartnerKeyDBName(),
                            APartnerKey, Transaction);
                    }

                    // delete reminders before contacts
                    if (ResultValue)
                    {
                        ResultValue = DeleteEntries(PPartnerReminderTable.GetTableDBName(),
                            PPartnerReminderTable.GetPartnerKeyDBName(),
                            APartnerKey, Transaction);
                    }

                    var partnerContacts = MPartner.Partner.WebConnectors.TContactsWebConnector.GetPartnerContactLogData(APartnerKey).PPartnerContact
                                          .AsEnumerable().Select(r =>
                        {
                            var id = r.ItemArray[PPartnerContactTable.ColumnContactLogIdId];
                            return new { ContactLogId = id, deleteThis = !TContactsWebConnector.IsContactLogAssociatedWithMoreThanOnePartner((long)id) };
                        });

                    // Delete contact attributes before deleting contacts
                    if (ResultValue)
                    {
                        String SqlStmt;

                        foreach (var row in partnerContacts)
                        {
                            if (row.deleteThis)
                            {
                                try
                                {
                                    // build sql statement for deletion
                                    SqlStmt = "DELETE FROM " + PPartnerContactAttributeTable.GetTableDBName() +
                                              " WHERE " + PPartnerContactAttributeTable.GetContactIdDBName() +
                                              " IN (SELECT " + PPartnerContactTable.GetContactLogIdDBName() +
                                              " FROM " + PPartnerContactTable.GetTableDBName() +
                                              " WHERE " + PPartnerContactTable.GetPartnerKeyDBName() + " = " + APartnerKey.ToString() +
                                              " AND " + PPartnerContactTable.GetContactLogIdDBName() + " = " + row.ContactLogId + ")";

                                    DBAccess.GDBAccessObj.ExecuteNonQuery(SqlStmt, Transaction);
                                }
                                catch (Exception Exc)
                                {
                                    TLogging.Log(
                                        "An Exception occured during the deletion of " + PPartnerContactAttributeTable.GetTableDBName() +
                                        " while deleting a partner: " + Environment.NewLine + Exc.ToString());

                                    throw;
                                }
                            }
                        }
                    }

                    if (ResultValue)
                    {
                        ResultValue = DeleteEntries(PPartnerContactTable.GetTableDBName(),
                            PPartnerContactTable.GetPartnerKeyDBName(),
                            APartnerKey, Transaction);
                    }

                    // Delete any would-be orphaned ContactLog records
                    if (ResultValue)
                    {
                        foreach (var r in partnerContacts.Where(p => p.deleteThis))
                        {
                            PContactLogAccess.DeleteByPrimaryKey((long)r.ContactLogId, Transaction);
                        }
                    }

                    if (ResultValue)
                    {
                        ResultValue = DeleteEntries(AEmailDestinationTable.GetTableDBName(),
                            AEmailDestinationTable.GetPartnerKeyDBName(),
                            APartnerKey, Transaction);
                    }

                    if (ResultValue)
                    {
                        ResultValue = ZeroEntries(AMotivationDetailTable.GetTableDBName(),
                            AMotivationDetailTable.GetRecipientKeyDBName(),
                            APartnerKey, Transaction);
                    }

                    /* a_recurring_gift - delete not allowed by CanPartnerBeDeleted */
                    /* a_recurring_gift_detail - delete not allowed by CanPartnerBeDeleted */
                    /* a_gift - delete not allowed by CanPartnerBeDeleted */
                    /* a_gift_detail - delete not allowed by CanPartnerBeDeleted */
                    /* a_ap_supplier - delete not allowed by CanPartnerBeDeleted */

                    if (ResultValue)
                    {
                        ResultValue = ZeroEntries(PmDocumentTable.GetTableDBName(),
                            PmDocumentTable.GetContactPartnerKeyDBName(),
                            APartnerKey, Transaction);
                    }

                    if (ResultValue)
                    {
                        ResultValue = DeleteEntries(PDataLabelValuePartnerTable.GetTableDBName(),
                            PDataLabelValuePartnerTable.GetPartnerKeyDBName(),
                            APartnerKey, Transaction);
                    }

                    if (ResultValue)
                    {
                        ResultValue = ZeroEntries(PDataLabelValuePartnerTable.GetTableDBName(),
                            PDataLabelValuePartnerTable.GetValuePartnerKeyDBName(),
                            APartnerKey, Transaction);
                    }

                    if (ResultValue)
                    {
                        ResultValue = ZeroEntries(PDataLabelValueApplicationTable.GetTableDBName(),
                            PDataLabelValueApplicationTable.GetValuePartnerKeyDBName(),
                            APartnerKey, Transaction);
                    }

                    if (ResultValue)
                    {
                        ResultValue = DeleteEntries(PmJobAssignmentTable.GetTableDBName(),
                            PmJobAssignmentTable.GetPartnerKeyDBName(),
                            APartnerKey, Transaction);
                    }

                    if (ResultValue)
                    {
                        ResultValue = DeleteEntries(PTaxTable.GetTableDBName(),
                            PTaxTable.GetPartnerKeyDBName(),
                            APartnerKey, Transaction);
                    }

                    if (ResultValue)
                    {
                        ResultValue = DeleteEntries(PPartnerInterestTable.GetTableDBName(),
                            PPartnerInterestTable.GetPartnerKeyDBName(),
                            APartnerKey, Transaction);
                    }

                    if (ResultValue)
                    {
                        ResultValue = DeleteEntries(PPartnerMergeTable.GetTableDBName(),
                            PPartnerMergeTable.GetMergeFromDBName(),
                            APartnerKey, Transaction);
                    }

                    if (ResultValue)
                    {
                        ResultValue = DeleteEntries(PPartnerMergeTable.GetTableDBName(),
                            PPartnerMergeTable.GetMergeToDBName(),
                            APartnerKey, Transaction);
                    }

                    if (ResultValue)
                    {
                        ResultValue = DeleteEntries(PPartnerGiftDestinationTable.GetTableDBName(),
                            PPartnerGiftDestinationTable.GetPartnerKeyDBName(),
                            APartnerKey, Transaction);
                    }

                    if (ResultValue)
                    {
                        ResultValue = DeleteEntries(PPartnerCommentTable.GetTableDBName(),
                            PPartnerCommentTable.GetPartnerKeyDBName(),
                            APartnerKey, Transaction);
                    }

                    if (ResultValue)
                    {
                        ResultValue = ZeroEntries(PFoundationTable.GetTableDBName(),
                            PFoundationTable.GetContactPartnerDBName(),
                            APartnerKey, Transaction);
                    }

                    if (ResultValue)
                    {
                        ResultValue = ZeroEntries(PFoundationProposalTable.GetTableDBName(),
                            PFoundationProposalTable.GetPartnerSubmittedByDBName(),
                            APartnerKey, Transaction);
                    }

                    // now delete partner class specific information
                    if (ResultValue)
                    {
                        switch (PartnerClass)
                        {
                            case TPartnerClass.FAMILY:
                                ResultValue = DeleteFamily(APartnerKey, Transaction);
                                break;

                            case TPartnerClass.PERSON:
                                ResultValue = DeletePerson(APartnerKey, Transaction);
                                break;

                            case TPartnerClass.UNIT:
                                ResultValue = DeleteUnit(APartnerKey, Transaction);
                                break;

                            case TPartnerClass.ORGANISATION:
                                ResultValue = DeleteOrganisation(APartnerKey, Transaction);
                                break;

                            case TPartnerClass.CHURCH:
                                ResultValue = DeleteChurch(APartnerKey, Transaction);
                                break;

                            case TPartnerClass.BANK:
                                ResultValue = DeleteBank(APartnerKey, Transaction);
                                break;

                            case TPartnerClass.VENUE:
                                ResultValue = DeleteVenue(APartnerKey, Transaction);
                                break;

                            default:
                                break;
                        }
                    }

                    // finally delete p_partner record itself
                    if (ResultValue)
                    {
                        ResultValue = DeleteEntries(PPartnerTable.GetTableDBName(),
                            PPartnerTable.GetPartnerKeyDBName(),
                            APartnerKey, Transaction);

                        SubmissionOK = true;
                    }
                });

            return ResultValue;
        }
        /// <summary>
        /// check the location change; validate and take other required action
        /// eg. change the location of family members, promote address changes
        /// </summary>
        /// <param name="ALocationRow"></param>
        /// <param name="APartnerKey"></param>
        /// <param name="AResponseDS"></param>
        /// <param name="ASubmitChangesTransaction"></param>
        /// <param name="AAddressAddedPromotionDT"></param>
        /// <param name="AChangeLocationParametersDT"></param>
        /// <param name="APartnerLocationTable"></param>
        /// <param name="AVerificationResult"></param>
        /// <param name="ACreateLocation"></param>
        /// <param name="AOriginalLocationKey"></param>
        /// <returns></returns>
        private static TSubmitChangesResult PerformLocationChangeChecks(PLocationRow ALocationRow,
            Int64 APartnerKey,
            ref PartnerAddressAggregateTDS AResponseDS,
            TDBTransaction ASubmitChangesTransaction,
            ref PartnerAddressAggregateTDSAddressAddedOrChangedPromotionTable AAddressAddedPromotionDT,
            ref PartnerAddressAggregateTDSChangePromotionParametersTable AChangeLocationParametersDT,
            ref PPartnerLocationTable APartnerLocationTable,
            ref TVerificationResultCollection AVerificationResult,
            out Boolean ACreateLocation,
            out TLocationPK AOriginalLocationKey)
        {
            TSubmitChangesResult ReturnValue;
            DataView PropagateLocationParametersDV;
            DataView PropagateLocationParametersDV2;
            Boolean UpdateLocation;

            Int64[] CreateLocationOtherPartnerKeys;
            PartnerAddressAggregateTDSChangePromotionParametersTable ChangePromotionParametersDT;
            PLocationTable NewLocationTable;
            PLocationRow NewLocationRowSaved;
            Int32 NewLocationLocationKey;
            PPartnerLocationRow PartnerLocationRowForChangedLocation;

            DataSet PartnerLocationModifyDS;
            int Counter;
            Int64 OldLocationKey;
            OdbcParameter[] ParametersArray;
            String OtherPartnerKeys = "";

            AOriginalLocationKey = null;
//          TLogging.LogAtLevel(9, "PerformLocationChangeChecks: AAddressAddedPromotionDT.Rows.Count: " + AAddressAddedPromotionDT.Rows.Count.ToString());

            if (CheckLocationChange(ALocationRow, APartnerKey, ref AAddressAddedPromotionDT, ASubmitChangesTransaction, out UpdateLocation,
                    out ACreateLocation, out CreateLocationOtherPartnerKeys, out ChangePromotionParametersDT))
            {
                // Check if there is a Parameter Row for the LocationKey we are looking at
                PropagateLocationParametersDV = new DataView(AAddressAddedPromotionDT,
                    PartnerAddressAggregateTDSAddressAddedOrChangedPromotionTable.GetSiteKeyDBName() + " = " + ALocationRow.SiteKey.ToString() +
                    " AND " +
                    PartnerAddressAggregateTDSAddressAddedOrChangedPromotionTable.GetLocationKeyDBName() + " = " +
                    ALocationRow.LocationKey.ToString() +
                    " AND " + PartnerAddressAggregateTDSAddressAddedOrChangedPromotionTable.GetLocationChangeDBName() + " = true AND " +
                    PartnerAddressAggregateTDSAddressAddedOrChangedPromotionTable.GetAnswerProcessedClientSideDBName() + " = false",
                    "",
                    DataViewRowState.CurrentRows);

                if (PropagateLocationParametersDV.Count > 0)
                {
//                  TLogging.LogAtLevel(9, "PerformLocationChangeChecks: Location " + ALocationRow.LocationKey.ToString() +
//                          ": Location has been changed, decision on propagation is needed.");

                    /*
                     * More information is needed (usually via user interaction)
                     * -> stop processing here and return parameters
                     * (usually used for UI interaction)
                     */
                    if (AResponseDS == null)
                    {
//                      TLogging.LogAtLevel(9, TLogging.Log("PerformLocationChangeChecks: Creating AResponseDS.");
                        AResponseDS = new PartnerAddressAggregateTDS(MPartnerConstants.PARTNERADDRESSAGGREGATERESPONSE_DATASET);
                    }

//                  TLogging.LogAtLevel(9, "PerformLocationChangeChecks: AAddressAddedPromotionDT.Rows.Count: " + AAddressAddedPromotionDT.Rows.Count.ToString());
                    AResponseDS.Merge(AAddressAddedPromotionDT);
//                  TLogging.LogAtLevel(9, "PerformLocationChangeChecks: Merged AAddressAddedPromotionDT into AResponseDS.");
                    AResponseDS.Merge(ChangePromotionParametersDT);
//                  TLogging.LogAtLevel(9, "PerformLocationChangeChecks: Merged ChangePromotionParametersDT into AResponseDS.");
//                  TLogging.LogAtLevel(9, "PerformLocationChangeChecks: AResponseDS.Tables[" + MPartnerConstants.ADDRESSADDEDORCHANGEDPROMOTION_TABLENAME +
//                      "].Rows.Count: " + AResponseDS.Tables[MPartnerConstants.ADDRESSADDEDORCHANGEDPROMOTION_TABLENAME].Rows.Count.ToString());
                    return TSubmitChangesResult.scrInfoNeeded;
                }
                else
                {
//                  TLogging.LogAtLevel(9, "PerformLocationChangeChecks: User made his/her choice regarding Location Change promotion; now processing...");

                    /*
                     * User made his/her choice regarding Location Change promotion; now process it
                     */
                    if (ACreateLocation)
                    {
                        OldLocationKey = ALocationRow.LocationKey;
                        AOriginalLocationKey = new TLocationPK(
                            Convert.ToInt64(ALocationRow[PLocationTable.GetSiteKeyDBName(),
                                                         DataRowVersion.Original]),
                            Convert.ToInt32(ALocationRow[PLocationTable.GetLocationKeyDBName(),
                                                         DataRowVersion.Original]));

                        // ALocationRow.LocationKey;
//                      TLogging.LogAtLevel(9, "PerformLocationChangeChecks: Location " + AOriginalLocationKey.LocationKey.ToString() + ": should be created.");

                        /*
                         * Create and save NEW Location that holds the same data than the changed
                         * Location.
                         */
                        NewLocationTable = new PLocationTable();
                        NewLocationRowSaved = NewLocationTable.NewRowTyped(false);
                        NewLocationRowSaved.ItemArray = DataUtilities.DestinationSaveItemArray(NewLocationRowSaved, ALocationRow);
                        NewLocationRowSaved.LocationKey = -1;
                        NewLocationTable.Rows.Add(NewLocationRowSaved);

                        // Submit the NEW Location to the DB
                        PLocationAccess.SubmitChanges(NewLocationTable, ASubmitChangesTransaction);

                        // The DB gives us a LocationKey from a Sequence. Remember this one.
                        NewLocationLocationKey = (Int32)NewLocationRowSaved.LocationKey;
//                      TLogging.LogAtLevel(9, "PerformLocationChangeChecks: New Location created! Its Location Key is: " + NewLocationLocationKey.ToString());

                        // Add the new row to the LocationTable that is beeing processed as well
                        // NewLocationCurrentTableRow := (ALocationRow.Table as PLocationTable).NewRowTyped(false);
                        // NewLocationCurrentTableRow.ItemArray := NewLocationRowSaved.ItemArray;
                        // ALocationRow.Table.Rows.Add(NewLocationCurrentTableRow);
                        // Make the row unchanged so that it isn't picked up as a 'new Address'
                        // and that it doesn't get saved later. Will be sent back to the Partner
                        // Edit screen lateron.
                        // NewLocationCurrentTableRow.AcceptChanges;

                        /*
                         * Update the reference from the changed Location to the new Location in
                         * the Partner's PartnerLocation DataTable. This will be saved later in
                         * the call to SubmitChanges in the main loop of the SubmitData function.
                         */
                        PartnerLocationRowForChangedLocation =
                            (PPartnerLocationRow)APartnerLocationTable.Rows.Find(new object[] { APartnerKey, ALocationRow.SiteKey,
                                                                                                ALocationRow.LocationKey });
                        PartnerLocationRowForChangedLocation.LocationKey = NewLocationLocationKey;

                        // Now delete the changed Location so that it doesn't get saved!
                        // ALocationRow.Delete;
                        // ALocationRow.AcceptChanges;
                        // Overwrite the Location that should be replaced with the data of the new Location
                        ALocationRow.ItemArray = NewLocationRowSaved.ItemArray;
                        PropagateLocationParametersDV2 = new DataView(AAddressAddedPromotionDT,
                            PartnerAddressAggregateTDSAddressAddedOrChangedPromotionTable.GetSiteKeyDBName() + " = " +
                            NewLocationRowSaved.SiteKey.ToString() + " AND " +
                            PartnerAddressAggregateTDSAddressAddedOrChangedPromotionTable.GetLocationKeyDBName() + " = " +
                            OldLocationKey.ToString() +
                            " AND " + PartnerAddressAggregateTDSAddressAddedOrChangedPromotionTable.GetLocationChangeDBName() + " = true AND " +
                            PartnerAddressAggregateTDSAddressAddedOrChangedPromotionTable.GetAnswerProcessedClientSideDBName() + " = true",
                            "",
                            DataViewRowState.CurrentRows);
                        ((PartnerAddressAggregateTDSAddressAddedOrChangedPromotionRow)(PropagateLocationParametersDV2[0].Row)).LocationKey =
                            ALocationRow.LocationKey;

                        if (CreateLocationOtherPartnerKeys.Length > 0)
                        {
//                          TLogging.LogAtLevel(9, "PerformLocationChangeChecks: Created Location " + NewLocationLocationKey.ToString() +
//                              ": should be assigned to " + Convert.ToInt32(CreateLocationOtherPartnerKeys.Length).ToString() + " Partners...");

                            // Build list of PartnerKeys for IN (x,y) clause in the SQL statement
                            for (Counter = 0; Counter <= CreateLocationOtherPartnerKeys.Length - 1; Counter += 1)
                            {
                                OtherPartnerKeys = OtherPartnerKeys + CreateLocationOtherPartnerKeys[Counter].ToString() + ',';
                            }

                            // remove last ','
                            OtherPartnerKeys = OtherPartnerKeys.Substring(0, OtherPartnerKeys.Length - 1);

                            // Load data for all the other selected Partners that reference
                            // the PartnerLocation
                            PartnerLocationModifyDS = new DataSet();
                            PartnerLocationModifyDS.Tables.Add(new PPartnerLocationTable());
                            ParametersArray = new OdbcParameter[2];
                            ParametersArray[0] = new OdbcParameter("", OdbcType.Decimal, 10);
                            ParametersArray[0].Value = (System.Object)(NewLocationRowSaved.SiteKey);
                            ParametersArray[1] = new OdbcParameter("", OdbcType.Int);
                            ParametersArray[1].Value = (System.Object)(AOriginalLocationKey.LocationKey);
                            PartnerLocationModifyDS = DBAccess.GDBAccessObj.Select(PartnerLocationModifyDS,
                                "SELECT * " + "FROM PUB_" + PPartnerLocationTable.GetTableDBName() + ' ' + "WHERE " +
                                PPartnerLocationTable.GetPartnerKeyDBName() + " IN (" + OtherPartnerKeys + ") " + "AND " +
                                PPartnerLocationTable.GetSiteKeyDBName() + " = ? " + "AND " + PPartnerLocationTable.GetLocationKeyDBName() + " = ?",
                                PPartnerLocationTable.GetTableName(),
                                ASubmitChangesTransaction,
                                ParametersArray);

                            // Change the LocationKey for every one of those PartnerLocation
                            // DataRows to point to the NEW Location
                            for (Counter = 0; Counter <= CreateLocationOtherPartnerKeys.Length - 1; Counter += 1)
                            {
                                ((PPartnerLocationTable)PartnerLocationModifyDS.Tables[0])[Counter].LocationKey = NewLocationLocationKey;
                            }

                            // Submit the changes to those PartnerLocations to the DB
                            PPartnerLocationAccess.SubmitChanges((PPartnerLocationTable)PartnerLocationModifyDS.Tables[0],
                                ASubmitChangesTransaction);
                        }
                        else
                        {
//                          TLogging.LogAtLevel(9, "PerformLocationChangeChecks: Created Location " + NewLocationLocationKey.ToString() + ": should not be assigned to any other Partners...");

                            /*
                             * Don't need to do anything here - the just created Location got already
                             * assigned to the Partner we are currently working with.
                             */
                        }
                    }
                    else if (UpdateLocation)
                    {
//                      TLogging.LogAtLevel(9, "PerformLocationChangeChecks: Location " + ALocationRow.LocationKey.ToString() +
//                              ": should simply get updated; therefore the Locations of ALL Partners will be changed...");

                        /*
                         * Don't need to do anything here - the changed Location will be saved
                         * in the call to SubmitChanges in the main loop of the SubmitData function.
                         */
                    }
                }

                ReturnValue = TSubmitChangesResult.scrOK;
            }
            else
            {
                TLogging.LogAtLevel(9, "PerformLocationChangeChecks: Location " + ALocationRow.LocationKey.ToString() +
                    ": User cancelled the selection - stopping the whole saving process!");

                /*
                 * User cancelled the selection - stop the whole saving process!
                 */
                AVerificationResult.Add(new TVerificationResult("Location Change Promotion: Information",
                        "No changes were saved because the Location Change Promotion dialog was cancelled by the user.", "Saving cancelled by user",
                        "",
                        TResultSeverity.Resv_Noncritical));
                ReturnValue = TSubmitChangesResult.scrError;
            }

            return ReturnValue;
        }
Beispiel #3
0
        public static bool CreateNewLedger(Int32 ANewLedgerNumber,
            String ALedgerName,
            String ACountryCode,
            String ABaseCurrency,
            String AIntlCurrency,
            DateTime ACalendarStartDate,
            Int32 ANumberOfPeriods,
            Int32 ACurrentPeriod,
            Int32 ANumberOfFwdPostingPeriods,
            bool IchIsAsset,
            bool AActivateGiftProcessing,
            Int32 AStartingReceiptNumber,
            bool AActivateAccountsPayable,
            out TVerificationResultCollection AVerificationResult)
        {
            AVerificationResult = null;
            bool AllOK = false;

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

            try
            {
                // check if such a ledger already exists
                ALedgerTable tempLedger = ALedgerAccess.LoadByPrimaryKey(ANewLedgerNumber, Transaction);

                if (tempLedger.Count > 0)
                {
                    AVerificationResult = new TVerificationResultCollection();
                    string msg = String.Format(Catalog.GetString(
                            "There is already a ledger with number {0}. Please choose another number."), ANewLedgerNumber);
                    AVerificationResult.Add(new TVerificationResult(Catalog.GetString("Creating Ledger"), msg, TResultSeverity.Resv_Critical));

                    return false;
                }

                if ((ANewLedgerNumber <= 1) || (ANewLedgerNumber > 9999))
                {
                    // ledger number 1 does not work, because the root unit has partner key 1000000.
                    AVerificationResult = new TVerificationResultCollection();
                    string msg = String.Format(Catalog.GetString(
                            "Invalid number {0} for a ledger. Please choose a number between 2 and 9999."), ANewLedgerNumber);
                    AVerificationResult.Add(new TVerificationResult(Catalog.GetString("Creating Ledger"), msg, TResultSeverity.Resv_Critical));

                    return false;
                }

                Int64 PartnerKey = Convert.ToInt64(ANewLedgerNumber) * 1000000L;
                GLSetupTDS MainDS = new GLSetupTDS();

                ALedgerRow ledgerRow = MainDS.ALedger.NewRowTyped();
                ledgerRow.LedgerNumber = ANewLedgerNumber;
                ledgerRow.LedgerName = ALedgerName;
                ledgerRow.CurrentPeriod = ACurrentPeriod;
                ledgerRow.NumberOfAccountingPeriods = ANumberOfPeriods;
                ledgerRow.NumberFwdPostingPeriods = ANumberOfFwdPostingPeriods;
                ledgerRow.BaseCurrency = ABaseCurrency;
                ledgerRow.IntlCurrency = AIntlCurrency;
                ledgerRow.ActualsDataRetention = 11;
                ledgerRow.GiftDataRetention = 11;
                ledgerRow.BudgetDataRetention = 2;
                ledgerRow.CountryCode = ACountryCode;
                ledgerRow.ForexGainsLossesAccount = "5003";
                ledgerRow.PartnerKey = PartnerKey;

                if (ANumberOfPeriods == 12)
                {
                    ledgerRow.CalendarMode = true;
                }
                else
                {
                    ledgerRow.CalendarMode = false;
                }

                MainDS.ALedger.Rows.Add(ledgerRow);

                PPartnerRow partnerRow;

                if (!PPartnerAccess.Exists(PartnerKey, Transaction))
                {
                    partnerRow = MainDS.PPartner.NewRowTyped();
                    ledgerRow.PartnerKey = PartnerKey;
                    partnerRow.PartnerKey = PartnerKey;
                    partnerRow.PartnerShortName = ALedgerName;
                    partnerRow.StatusCode = MPartnerConstants.PARTNERSTATUS_ACTIVE;
                    partnerRow.PartnerClass = MPartnerConstants.PARTNERCLASS_UNIT;
                    MainDS.PPartner.Rows.Add(partnerRow);

                    // create or use addresses (only if partner record is created here as
                    // otherwise we assume that Partner has address already)
                    PLocationRow locationRow;
                    PLocationTable LocTemplateTable;
                    PLocationTable LocResultTable;
                    PLocationRow LocTemplateRow;
                    StringCollection LocTemplateOperators;

                    // find address with country set
                    LocTemplateTable = new PLocationTable();
                    LocTemplateRow = LocTemplateTable.NewRowTyped(false);
                    LocTemplateRow.SiteKey = 0;
                    LocTemplateRow.StreetName = Catalog.GetString("No valid address on file");
                    LocTemplateRow.CountryCode = ACountryCode;
                    LocTemplateOperators = new StringCollection();

                    LocResultTable = PLocationAccess.LoadUsingTemplate(LocTemplateRow, LocTemplateOperators, Transaction);

                    if (LocResultTable.Count > 0)
                    {
                        locationRow = (PLocationRow)LocResultTable.Rows[0];
                    }
                    else
                    {
                        // no location record exists yet: create new one
                        locationRow = MainDS.PLocation.NewRowTyped();
                        locationRow.SiteKey = 0;
                        locationRow.LocationKey = (int)DBAccess.GDBAccessObj.GetNextSequenceValue(
                            TSequenceNames.seq_location_number.ToString(), Transaction);
                        locationRow.StreetName = Catalog.GetString("No valid address on file");
                        locationRow.CountryCode = ACountryCode;
                        MainDS.PLocation.Rows.Add(locationRow);
                    }

                    // now create partner location record
                    PPartnerLocationRow partnerLocationRow = MainDS.PPartnerLocation.NewRowTyped();
                    partnerLocationRow.SiteKey = locationRow.SiteKey;
                    partnerLocationRow.PartnerKey = PartnerKey;
                    partnerLocationRow.LocationKey = locationRow.LocationKey;
                    partnerLocationRow.DateEffective = DateTime.Today;
                    MainDS.PPartnerLocation.Rows.Add(partnerLocationRow);
                }
                else
                {
                    // partner record already exists in database -> update ledger name
                    PPartnerAccess.LoadByPrimaryKey(MainDS, PartnerKey, Transaction);
                    partnerRow = (PPartnerRow)MainDS.PPartner.Rows[0];
                    partnerRow.PartnerShortName = ALedgerName;
                }

                PPartnerTypeAccess.LoadViaPPartner(MainDS, PartnerKey, Transaction);
                PPartnerTypeRow partnerTypeRow;

                // only create special type "LEDGER" if it does not exist yet
                if (MainDS.PPartnerType.Rows.Find(new object[] { PartnerKey, MPartnerConstants.PARTNERTYPE_LEDGER }) == null)
                {
                    partnerTypeRow = MainDS.PPartnerType.NewRowTyped();
                    partnerTypeRow.PartnerKey = PartnerKey;
                    partnerTypeRow.TypeCode = MPartnerConstants.PARTNERTYPE_LEDGER;
                    MainDS.PPartnerType.Rows.Add(partnerTypeRow);
                }

                if (!PUnitAccess.Exists(PartnerKey, Transaction))
                {
                    PUnitRow unitRow = MainDS.PUnit.NewRowTyped();
                    unitRow.PartnerKey = PartnerKey;
                    unitRow.UnitName = ALedgerName;
                    MainDS.PUnit.Rows.Add(unitRow);
                }

                String ModuleId = "LEDGER" + ANewLedgerNumber.ToString("0000");

                if (!SModuleAccess.Exists(ModuleId, Transaction))
                {
                    SModuleRow moduleRow = MainDS.SModule.NewRowTyped();
                    moduleRow.ModuleId = ModuleId;
                    moduleRow.ModuleName = moduleRow.ModuleId;
                    MainDS.SModule.Rows.Add(moduleRow);
                }

                // if this is the first ledger, make it the default site
                SSystemDefaultsTable systemDefaults = SSystemDefaultsAccess.LoadByPrimaryKey("SiteKey", Transaction);

                if (systemDefaults.Rows.Count == 0)
                {
                    SSystemDefaultsRow systemDefaultsRow = MainDS.SSystemDefaults.NewRowTyped();
                    systemDefaultsRow.DefaultCode = SharedConstants.SYSDEFAULT_SITEKEY;
                    systemDefaultsRow.DefaultDescription = "there has to be one site key for the database";
                    systemDefaultsRow.DefaultValue = PartnerKey.ToString("0000000000");
                    MainDS.SSystemDefaults.Rows.Add(systemDefaultsRow);
                }

                //TODO: Calendar vs Financial Date Handling - Need to review this
                // create calendar
                // at the moment we only support financial years that start on the first day of a month
                // and currently only 12 or 13 periods are allowed and a maximum of 8 forward periods
                DateTime periodStartDate = ACalendarStartDate;

                for (Int32 periodNumber = 1; periodNumber <= ANumberOfPeriods + ANumberOfFwdPostingPeriods; periodNumber++)
                {
                    AAccountingPeriodRow accountingPeriodRow = MainDS.AAccountingPeriod.NewRowTyped();
                    accountingPeriodRow.LedgerNumber = ANewLedgerNumber;
                    accountingPeriodRow.AccountingPeriodNumber = periodNumber;
                    accountingPeriodRow.PeriodStartDate = periodStartDate;

                    if ((ANumberOfPeriods == 13)
                        && (periodNumber == 12))
                    {
                        // in case of 12 periods the second last period represents the last month except for the very last day
                        accountingPeriodRow.PeriodEndDate = periodStartDate.AddMonths(1).AddDays(-2);
                    }
                    else if ((ANumberOfPeriods == 13)
                             && (periodNumber == 13))
                    {
                        // in case of 13 periods the last period just represents the very last day of the financial year
                        accountingPeriodRow.PeriodEndDate = periodStartDate;
                    }
                    else
                    {
                        accountingPeriodRow.PeriodEndDate = periodStartDate.AddMonths(1).AddDays(-1);
                    }

                    accountingPeriodRow.AccountingPeriodDesc = periodStartDate.ToString("MMMM");
                    MainDS.AAccountingPeriod.Rows.Add(accountingPeriodRow);
                    periodStartDate = accountingPeriodRow.PeriodEndDate.AddDays(1);
                }

                // mark cached table for accounting periods to be refreshed
                TCacheableTablesManager.GCacheableTablesManager.MarkCachedTableNeedsRefreshing(
                    TCacheableFinanceTablesEnum.AccountingPeriodList.ToString());

                AAccountingSystemParameterRow accountingSystemParameterRow = MainDS.AAccountingSystemParameter.NewRowTyped();
                accountingSystemParameterRow.LedgerNumber = ANewLedgerNumber;
                accountingSystemParameterRow.ActualsDataRetention = ledgerRow.ActualsDataRetention;
                accountingSystemParameterRow.GiftDataRetention = ledgerRow.GiftDataRetention;
                accountingSystemParameterRow.NumberFwdPostingPeriods = ledgerRow.NumberFwdPostingPeriods;
                accountingSystemParameterRow.NumberOfAccountingPeriods = ledgerRow.NumberOfAccountingPeriods;
                accountingSystemParameterRow.BudgetDataRetention = ledgerRow.BudgetDataRetention;
                MainDS.AAccountingSystemParameter.Rows.Add(accountingSystemParameterRow);

                // activate GL subsystem (this is always active)
                ASystemInterfaceRow systemInterfaceRow = MainDS.ASystemInterface.NewRowTyped();
                systemInterfaceRow.LedgerNumber = ANewLedgerNumber;

                systemInterfaceRow.SubSystemCode = CommonAccountingSubSystemsEnum.GL.ToString();
                systemInterfaceRow.SetUpComplete = true;
                MainDS.ASystemInterface.Rows.Add(systemInterfaceRow);


                ATransactionTypeRow transactionTypeRow;

                // TODO: this might be different for other account or costcentre names
                transactionTypeRow = MainDS.ATransactionType.NewRowTyped();
                transactionTypeRow.LedgerNumber = ANewLedgerNumber;
                transactionTypeRow.SubSystemCode = CommonAccountingSubSystemsEnum.GL.ToString();
                transactionTypeRow.TransactionTypeCode = CommonAccountingTransactionTypesEnum.ALLOC.ToString();
                transactionTypeRow.DebitAccountCode = "BAL SHT";
                transactionTypeRow.CreditAccountCode = "BAL SHT";
                transactionTypeRow.TransactionTypeDescription = "Allocation Journal";
                transactionTypeRow.SpecialTransactionType = true;
                MainDS.ATransactionType.Rows.Add(transactionTypeRow);

                transactionTypeRow = MainDS.ATransactionType.NewRowTyped();
                transactionTypeRow.LedgerNumber = ANewLedgerNumber;
                transactionTypeRow.SubSystemCode = CommonAccountingSubSystemsEnum.GL.ToString();
                transactionTypeRow.TransactionTypeCode = CommonAccountingTransactionTypesEnum.REALLOC.ToString();
                transactionTypeRow.DebitAccountCode = "BAL SHT";
                transactionTypeRow.CreditAccountCode = "BAL SHT";
                transactionTypeRow.TransactionTypeDescription = "Reallocation Journal";
                transactionTypeRow.SpecialTransactionType = true;
                MainDS.ATransactionType.Rows.Add(transactionTypeRow);

                transactionTypeRow = MainDS.ATransactionType.NewRowTyped();
                transactionTypeRow.LedgerNumber = ANewLedgerNumber;
                transactionTypeRow.SubSystemCode = CommonAccountingSubSystemsEnum.GL.ToString();
                transactionTypeRow.TransactionTypeCode = CommonAccountingTransactionTypesEnum.REVAL.ToString();
                transactionTypeRow.DebitAccountCode = "5003";
                transactionTypeRow.CreditAccountCode = "5003";
                transactionTypeRow.TransactionTypeDescription = "Foreign Exchange Revaluation";
                transactionTypeRow.SpecialTransactionType = true;
                MainDS.ATransactionType.Rows.Add(transactionTypeRow);

                transactionTypeRow = MainDS.ATransactionType.NewRowTyped();
                transactionTypeRow.LedgerNumber = ANewLedgerNumber;
                transactionTypeRow.SubSystemCode = CommonAccountingSubSystemsEnum.GL.ToString();
                transactionTypeRow.TransactionTypeCode = CommonAccountingTransactionTypesEnum.STD.ToString();
                transactionTypeRow.DebitAccountCode = MFinanceConstants.ACCOUNT_BAL_SHT;
                transactionTypeRow.CreditAccountCode = MFinanceConstants.ACCOUNT_BAL_SHT;
                transactionTypeRow.TransactionTypeDescription = "Standard Journal";
                transactionTypeRow.SpecialTransactionType = false;
                MainDS.ATransactionType.Rows.Add(transactionTypeRow);


                AValidLedgerNumberTable validLedgerNumberTable = AValidLedgerNumberAccess.LoadByPrimaryKey(ANewLedgerNumber, PartnerKey, Transaction);

                if (validLedgerNumberTable.Rows.Count == 0)
                {
                    AValidLedgerNumberRow validLedgerNumberRow = MainDS.AValidLedgerNumber.NewRowTyped();
                    validLedgerNumberRow.PartnerKey = PartnerKey;
                    validLedgerNumberRow.LedgerNumber = ANewLedgerNumber;

                    // TODO can we assume that ledger 4 is used for international clearing?
                    // but in the empty database, that ledger and therefore p_partner with key 4000000 does not exist
                    // validLedgerNumberRow.IltProcessingCentre = 4000000;

                    validLedgerNumberRow.CostCentreCode = (ANewLedgerNumber * 100).ToString("0000");
                    MainDS.AValidLedgerNumber.Rows.Add(validLedgerNumberRow);
                }

                ACostCentreTypesRow costCentreTypesRow = MainDS.ACostCentreTypes.NewRowTyped();
                costCentreTypesRow.LedgerNumber = ANewLedgerNumber;
                costCentreTypesRow.CostCentreType = "Local";
                costCentreTypesRow.Deletable = false;
                MainDS.ACostCentreTypes.Rows.Add(costCentreTypesRow);
                costCentreTypesRow = MainDS.ACostCentreTypes.NewRowTyped();
                costCentreTypesRow.LedgerNumber = ANewLedgerNumber;
                costCentreTypesRow.CostCentreType = "Foreign";
                costCentreTypesRow.Deletable = false;
                MainDS.ACostCentreTypes.Rows.Add(costCentreTypesRow);

                ImportDefaultAccountHierarchy(ref MainDS, ANewLedgerNumber, ref AVerificationResult);
                ImportDefaultCostCentreHierarchy(ref MainDS, ANewLedgerNumber, ALedgerName);
                ImportDefaultMotivations(ref MainDS, ANewLedgerNumber);
                ImportDefaultAdminGrantsPayableReceivable(ref MainDS, ANewLedgerNumber);

                // TODO: modify UI navigation yml file etc?
                // TODO: permissions for which users?

                GLSetupTDSAccess.SubmitChanges(MainDS);

                // activate gift processing subsystem
                if (AActivateGiftProcessing)
                {
                    ActivateGiftProcessingSubsystem(ANewLedgerNumber, AStartingReceiptNumber);
                }

                // activate accounts payable subsystem
                if (AActivateAccountsPayable)
                {
                    ActivateAccountsPayableSubsystem(ANewLedgerNumber);
                }

                // give the current user access permissions to this new ledger
                SUserModuleAccessPermissionTable moduleAccessPermissionTable = new SUserModuleAccessPermissionTable();

                SUserModuleAccessPermissionRow moduleAccessPermissionRow = moduleAccessPermissionTable.NewRowTyped();
                moduleAccessPermissionRow.UserId = UserInfo.GUserInfo.UserID;
                moduleAccessPermissionRow.ModuleId = "LEDGER" + ANewLedgerNumber.ToString("0000");
                moduleAccessPermissionRow.CanAccess = true;
                moduleAccessPermissionTable.Rows.Add(moduleAccessPermissionRow);


                SUserModuleAccessPermissionAccess.SubmitChanges(moduleAccessPermissionTable, Transaction);

                // create system analysis types for the new ledger
                AAnalysisTypeAccess.LoadAll(MainDS, Transaction);
                AAnalysisTypeTable NewAnalysisTypes = new AAnalysisTypeTable();

                foreach (AAnalysisTypeRow AnalysisTypeRow in MainDS.AAnalysisType.Rows)
                {
                    if (AnalysisTypeRow.SystemAnalysisType
                        && !NewAnalysisTypes.Rows.Contains(new Object[] { ANewLedgerNumber, AnalysisTypeRow.AnalysisTypeCode }))
                    {
                        AAnalysisTypeRow NewAnalysisType = NewAnalysisTypes.NewRowTyped();
                        NewAnalysisType.ItemArray = (object[])AnalysisTypeRow.ItemArray.Clone();
                        NewAnalysisType.LedgerNumber = ANewLedgerNumber;
                        NewAnalysisTypes.Rows.Add(NewAnalysisType);
                    }
                }

                AAnalysisTypeAccess.SubmitChanges(NewAnalysisTypes, Transaction);


                AllOK = true;
            }
            catch (Exception Exc)
            {
                TLogging.Log("An Exception occured during the creation of a new Ledger:" + Environment.NewLine + Exc.ToString());

                DBAccess.GDBAccessObj.RollbackTransaction();

                throw;
            }
            finally
            {
                if (AllOK)
                {
                    DBAccess.GDBAccessObj.CommitTransaction();

                    //
                    // If the user has specified that ICH is an asset,
                    // I need to re-write it into the hierarchy:
                    if (IchIsAsset)
                    {
                        RewireIchIsAsset(ANewLedgerNumber);
                    }
                }
                else
                {
                    DBAccess.GDBAccessObj.RollbackTransaction();
                }
            }

            return AllOK;
        }