Esempio n. 1
0
        /// <summary>
        /// Informs any Form that is registered in TFormsList about a specific 'Forms Message'
        /// that is being 'broadcasted'.
        /// </summary>
        /// <remarks>The individual Form can choose to 'listen' to such 'Forms Message' broadcasts
        /// by implementing the Method 'ProcessFormsMessage'. Once this is done, the Forms'
        /// 'ProcessFormsMessage' Method will be called each time a 'Forms Message' broadcast occurs.
        /// </remarks>
        /// <param name="AFormsMessage">An instance of a 'Forms Message'. This can be inspected
        /// for parameters in the Method Body of a Forms' 'ProcessFormsMessage' Method and
        /// the Form can use those to choose whether to react on the Message, or not.</param>
        /// <returns>The Number of Forms that reacted on the 'Forms Message'.</returns>
        public int BroadcastFormMessage(TFormsMessage AFormsMessage)
        {
            System.Windows.Forms.Form FormInstance;
            IDictionaryEnumerator     DictEnum;
            int FormsThatReacted = 0;

            DictEnum = this.GetEnumerator();

            while (DictEnum.MoveNext())
            {
                FormInstance = (System.Windows.Forms.Form)DictEnum.Value;

                var        Type   = FormInstance.GetType();
                MethodInfo Method = Type.GetMethod("ProcessFormsMessage");

                // Does form contain the method "ProcessFormsMessage"?
                // If so, call it.
                if ((Method != null) && ((bool)Method.Invoke(FormInstance, new object[] { AFormsMessage }) == true))
                {
//                    MessageBox.Show("BroadcastFormMessage: FormInstance = " + FormInstance.Name);
                    FormsThatReacted++;
                }
            }

//            MessageBox.Show("FormsThatListened: " + FormsThatListened.ToString());
            return(FormsThatReacted);
        }
        // carry out the adjustment
        /// <summary>
        /// Carry out a Tax Deductible Pct adjustment.
        /// </summary>
        /// <param name="ARecipientKey"></param>
        /// <param name="ANewPct"></param>
        /// <param name="AValidFrom"></param>
        /// <param name="ANoReceipt"></param>
        /// <param name="AParentForm"></param>
        public static void TaxDeductiblePctAdjustment(Int64 ARecipientKey, decimal ANewPct, DateTime AValidFrom, bool ANoReceipt, Form AParentForm)
        {
            GiftBatchTDS GiftBatchDS = new GiftBatchTDS();

            // get all the data needed for this Field Adjustment
            if (!GetAllDataNeeded(ref GiftBatchDS, ARecipientKey, ANewPct, AValidFrom, AParentForm))
            {
                return;
            }

            // show the list of gifts to be adjusted and ask the user for confirmation
            TFrmGiftFieldAdjustmentConfirmation ConfirmationForm = new TFrmGiftFieldAdjustmentConfirmation(AParentForm);
            ConfirmationForm.MainDS = GiftBatchDS;
            ConfirmationForm.Text = Catalog.GetString("Confirm Tax Deductible Percentage Adjustment");

            if (ConfirmationForm.ShowDialog() == System.Windows.Forms.DialogResult.Cancel)
            {
                return;
            }

            // Carry out the gift adjustment
            TFrmGiftFieldAdjustment.GiftAdjustment(GiftBatchDS, ANewPct, ANoReceipt, AParentForm);

            // refresh gift batch screen
            TFormsMessage broadcastMessage = new TFormsMessage(TFormsMessageClassEnum.mcRefreshGiftBatches, AParentForm.ToString());
            TFormsList.GFormsList.BroadcastFormMessage(broadcastMessage);
        }
        /// <summary>
        /// Determines the changes in the screen's dataset and submits them to the
        /// Server.
        /// </summary>
        /// <param name="AInspectDS">The screen's dataset
        /// </param>
        /// <returns>True if saving of data succeeded, otherwise false.</returns>
        private Boolean SaveChanges(ref PartnerEditTDS AInspectDS)
        {
            Boolean ReturnValue = false;
            PartnerEditTDS SubmitDS = null;
            TSubmitChangesResult SubmissionResult;

            TVerificationResultCollection VerificationResult;
            TVerificationResult VerificationResultItem;

            System.Windows.Forms.DialogResult UnitParentAssignment;
            int RowIndex;
            int NumRows;
            Int32 MaxColumn;
            Boolean SavedPartnerIsNewPartner = false;
            bool PartnerAttributesOrRelationsChanged = false;
            System.Int32 ChangedColumns;
#if SHOWCHANGES
            String DebugMessage;
#endif
#if DATASETDEBUGGING
            Int16 TmpRowCounter;
            string TmpDebugString = String.Empty;
#endif
            // Be sure to fire the OnLeave event on the active control of any user control
            FPetraUtilsObject.ForceOnLeaveForActiveControl();

            FPetraUtilsObject.OnDataSavingStart(this, new System.EventArgs());

            // Don't allow saving if user is still editing a Detail of a List
            if (FPetraUtilsObject.InDetailEditMode())
            {
                ReturnValue = false;
                return ReturnValue;
            }

            // Make sure that DataBinding writes the value of the active Control to the underlying DataSource!
            TDataBinding.EnsureDataChangesAreStored(this);

            GetDataFromControls();

            // Clear any validation errors so that the following call to ValidateAllData starts with a 'clean slate'.
            FPetraUtilsObject.VerificationResultCollection.Clear();

            if (ValidateAllData())
            {
                // Ask the user about non-critical warnings, if they are the only 'errors' in the collection
                if (FPetraUtilsObject.VerificationResultCollection.HasOnlyNonCriticalErrors
                    && (TDataValidation.ProcessAnyDataValidationWarnings(FPetraUtilsObject.VerificationResultCollection,
                            MCommonResourcestrings.StrFormSaveDataAnywayQuestion, this.GetType()) == false))
                {
                    return false;
                }

                // Fire the DataSavingValidated event, which is the last chance to cancel the save
                System.ComponentModel.CancelEventArgs eCancel = new System.ComponentModel.CancelEventArgs(false);
                FPetraUtilsObject.OnDataSavingValidated(this, eCancel);

                if (eCancel.Cancel == true)
                {
                    return false;
                }

                foreach (DataTable InspectDT in AInspectDS.Tables)
                {
                    foreach (DataRow InspectDR in InspectDT.Rows)
                    {
                        InspectDR.EndEdit();
                    }
                }

                if (FPetraUtilsObject.HasChanges)
                {
                    FPetraUtilsObject.WriteToStatusBar(MCommonResourcestrings.StrSavingDataInProgress);
                    this.Cursor = Cursors.WaitCursor;

                    /* $IFDEF SHOWCHANGES MessageBox.Show('SaveChanges: AInspectDS.PLocation.Rows[0].HasVersion(DataRowVersion.Original): ' + AInspectDS.PLocation.Rows[0].HasVersion(DataRowVersion.Original).ToString + '; LocationKey: ' +
                     *AInspectDS.PLocation.Row[0].LocationKey.ToString); $ENDIF */

                    /* $IFDEF SHOWCHANGES MessageBox.Show('SaveChanges: AInspectDS.PLocation.Rows[1].HasVersion(DataRowVersion.Original): ' + AInspectDS.PLocation.Rows[1].HasVersion(DataRowVersion.Original).ToString + '; LocationKey: ' +
                     *AInspectDS.PLocation.Row[1].LocationKey.ToString); $ENDIF */
                    if (!FPetraUtilsObject.SubmitChangesContinue)
                    {
                        foreach (DataTable InspectDT in AInspectDS.Tables)
                        {
                            // MessageBox.Show('inspectDataTable: ' + InspectDT.ToString);
                            if ((InspectDT.TableName != PLocationTable.GetTableName()) && (InspectDT.TableName != PPartnerLocationTable.GetTableName()))
                            {
                                MaxColumn = InspectDT.Columns.Count;
                                ChangedColumns = DataUtilities.AcceptChangesForUnmodifiedRows(InspectDT, MaxColumn);

                                if (ChangedColumns != 0)
                                {
#if SHOWCHANGES
                                    MessageBox.Show(InspectDT.TableName + " - changed colums: " + ChangedColumns.ToString());
#endif
                                }
                            }
                            else if (InspectDT.TableName == PLocationTable.GetTableName())
                            {
                                MaxColumn = new PLocationTable().Columns.Count;

                                // MessageBox.Show('PLocation MaxColumn: ' + MaxColumn.ToString);
                                ChangedColumns = DataUtilities.AcceptChangesForUnmodifiedRows(AInspectDS.PLocation, MaxColumn, true);

                                if (ChangedColumns != 0)
                                {
#if SHOWCHANGES
                                    MessageBox.Show(PLocationTable.GetTableName() + " - changed colums: " + ChangedColumns.ToString());
#endif
                                }
                            }
                            else
                            {
                                MaxColumn = new PPartnerLocationTable().Columns.Count;

                                // MessageBox.Show('PPartnerLocation MaxColumn: ' + MaxColumn.ToString);
                                ChangedColumns = DataUtilities.AcceptChangesForUnmodifiedRows(AInspectDS.PPartnerLocation,
                                    MaxColumn,
                                    true);

                                if (ChangedColumns != 0)
                                {
#if SHOWCHANGES
                                    MessageBox.Show(PPartnerLocationTable.GetTableName() + " - changed colums: " + ChangedColumns.ToString());
#endif
                                }
                            }

#if SHOWCHANGES
                            foreach (DataRow InspectDR in InspectDT.Rows)
                            {
                                DebugMessage = InspectDT.ToString();

                                if ((InspectDR.RowState == DataRowState.Modified) || (InspectDR.RowState == DataRowState.Added))
                                {
                                    ChangedColumns = 0;

                                    if (InspectDR.RowState == DataRowState.Modified)
                                    {
                                        DebugMessage = DebugMessage + " --- changed columns:" + Environment.NewLine;
                                    }
                                    else
                                    {
                                        DebugMessage = DebugMessage + " --- inserted Row. Column contents:" + Environment.NewLine;
                                    }

                                    for (int Counter1 = 0; Counter1 <= MaxColumn - 1; Counter1 += 1)
                                    {
                                        if ((InspectDR.RowState == DataRowState.Added) || (InspectDR != InspectDR[Counter1, DataRowVersion.Current]))
                                        {
                                            ChangedColumns = ChangedColumns + 1;
                                            DebugMessage = DebugMessage + "  " + (InspectDT.Columns[Counter1].ColumnName).ToString() + ": " +
                                                           InspectDR[Counter1, DataRowVersion.Current].ToString() + Environment.NewLine;
                                        }
                                    }

                                    if (ChangedColumns != 0)
                                    {
                                        MessageBox.Show(DebugMessage);
                                    }
                                    else
                                    {
                                        DebugMessage = DebugMessage + "  NO changed columns.";
                                        MessageBox.Show(DebugMessage);
                                    }
                                }
                                // (inspectDataRow.RowState = DataRowState.Modified) or (inspectDataRow.RowState = DataRowState.Added)
                                else
                                {
                                    // MessageBox.Show('inspectDataRow.RowState: ' + inspectDataRow.RowState.ToString("G"));
                                    if (InspectDR.RowState == DataRowState.Deleted)
                                    {
                                        DebugMessage = DebugMessage + " --- deleted Row. Original Column[0] contents: " +
                                                       InspectDR[0, DataRowVersion.Original].ToString();
                                        MessageBox.Show(DebugMessage);
                                    }
                                }
                            }
                            // for inspectDataRow in inspectDataTable.Rows do
#endif
                        }

                        // for inspectDataTable in inspectDataSet.Tables do
                    }

                    // If changes have been made to pm_staff_data (commitments) then update the partner's family's Gift Destination records
                    TGiftDestination GiftDestination = new TGiftDestination();

                    if (GiftDestination.UpdateGiftDestination(ref AInspectDS))
                    {
                        // set the gift destination on this screen and all other open partner edit screens for the same family
                        SetGiftDestinationAllScreens();
                    }

                    SubmitDS = AInspectDS.GetChangesTyped(true);

                    if (SubmitDS == null)
                    {
                        // There is nothing to be saved.
                        // Update UI
                        FPetraUtilsObject.WriteToStatusBar(MCommonResourcestrings.StrSavingDataNothingToSave);
                        this.Cursor = Cursors.Default;

                        // We don't have unsaved changes anymore
                        FPetraUtilsObject.DisableSaveButton();

                        return true;
                    }

                    if ((SubmitDS.Tables.Contains(PPartnerAttributeTable.GetTableName()))
                        || (SubmitDS.Tables.Contains(PPartnerRelationshipTable.GetTableName())))
                    {
                        PartnerAttributesOrRelationsChanged = true;
                    }

#if DATASETDEBUGGING
                    TLogging.Log("Before submitting data to the Server. Client DataSet: " + SubmitDS.GetXml());
#endif
                    // Submit changes to the PETRAServer
                    try
                    {
                        if (!FPetraUtilsObject.SubmitChangesContinue)
                        {
                            FResponseDS = null;
                            SubmissionResult = FPartnerEditUIConnector.SubmitChanges(ref SubmitDS, ref FResponseDS, out VerificationResult);
                        }
                        else
                        {
                            SubmissionResult = FPartnerEditUIConnector.SubmitChangesContinue(out SubmitDS, ref FResponseDS, out VerificationResult);
                        }
                    }
                    catch (ESecurityDBTableAccessDeniedException Exp)
                    {
                        FPetraUtilsObject.WriteToStatusBar(MCommonResourcestrings.StrSavingDataException);
                        this.Cursor = Cursors.Default;

                        TMessages.MsgSecurityException(Exp, this.GetType());

                        ReturnValue = false;
                        FPetraUtilsObject.OnDataSaved(this, new TDataSavedEventArgs(ReturnValue));
                        return ReturnValue;
                    }
                    catch (EDBConcurrencyException Exp)
                    {
                        FPetraUtilsObject.WriteToStatusBar(MCommonResourcestrings.StrSavingDataException);
                        this.Cursor = Cursors.Default;

                        TMessages.MsgDBConcurrencyException(Exp, this.GetType());

                        ReturnValue = false;
                        FPetraUtilsObject.OnDataSaved(this, new TDataSavedEventArgs(ReturnValue));
                        return ReturnValue;
                    }
                    catch (Exception)
                    {
                        FPetraUtilsObject.WriteToStatusBar(MCommonResourcestrings.StrSavingDataException);
                        this.Cursor = Cursors.Default;

                        FPetraUtilsObject.OnDataSaved(this, new TDataSavedEventArgs(ReturnValue));
                        throw;
                    }

                    switch (SubmissionResult)
                    {
                        case TSubmitChangesResult.scrOK:

                            SavedPartnerIsNewPartner = IsNewPartner(AInspectDS);

                            // MessageBox.Show('DUMMY: ' + (SubmitDS.Tables['Locations'].Rows[0]['DUMMY']).ToString() );
                            if ((SharedTypes.PartnerClassStringToEnum(AInspectDS.PPartner[0].PartnerClass) == TPartnerClass.UNIT)
                                && SavedPartnerIsNewPartner)
                            {
                                /*
                                 * A new Partner of PartnerClass UNIT has been created
                                 * -- give option to assign 'Parent' in Unit Hierarchy
                                 */
                                UnitParentAssignment = MessageBox.Show(StrQueryUnitParent,
                                    StrQueryUnitParentTitle,
                                    MessageBoxButtons.YesNo,
                                    MessageBoxIcon.Question,
                                    MessageBoxDefaultButton.Button1);

                                if (UnitParentAssignment == System.Windows.Forms.DialogResult.Yes)
                                {
                                    TFrmUnitHierarchy HierarchyForm = new TFrmUnitHierarchy(this.ParentForm);

                                    HierarchyForm.Show();
                                    HierarchyForm.ShowThisUnit(AInspectDS.PPartner[0].PartnerKey);
                                }
                            }

#if DATASETDEBUGGING
                            TLogging.Log("After submtting returned Server DataSet: " + SubmitDS.GetXml());
                            MessageBox.Show("Before CleanupAddressesBeforeMerge");
#endif
                            // Get rid of any new Addresses; they are returned back with different LocationKeys (based on a Sequence)
                            ucoLowerPart.CleanupAddressesBeforeMerge();
#if DATASETDEBUGGING
                            MessageBox.Show("After CleanupAddressesBeforeMerge");

                            if ((SubmitDS.PLocation != null)
                                && (SubmitDS.PLocation.Rows.Count > 0))
                            {
                                MessageBox.Show(
                                    "Location[0] LocationKey: " + SubmitDS.PLocation[0].LocationKey.ToString() +
                                    "; PartnerLocation[0] LocationKey: " +
                                    SubmitDS.PPartnerLocation[0].LocationKey.ToString());
                            }
#endif

                            // Delete all added Rows in the original dataset. They will automatically
                            // be put back in with the Merge. If added Rows are deleted they will
                            // be removed from the Row collection on the server. In that case the
                            // client will not be aware of that. For modified Rows: if they are
                            // deleted on the server they will not be taken out of the collection
                            // but come back to the client as being marked as 'Deleted'. Therefore
                            // with deleting the added Rows beforehand we are making sure that
                            // the dataset on the client is synchronized with the one on the server.
                            foreach (DataTable t in AInspectDS.Tables)
                            {
                                if ((t == AInspectDS.PBankingDetails)
                                    || (t == AInspectDS.PPartnerBankingDetails)
                                    || (t == AInspectDS.PDataLabelValuePartner))
                                {
                                    NumRows = t.Rows.Count;

                                    for (RowIndex = NumRows - 1; RowIndex >= 0; RowIndex -= 1)
                                    {
                                        DataRow InspectDR = t.Rows[RowIndex];

                                        // delete all added Rows.
                                        if (InspectDR.RowState == DataRowState.Added)
                                        {
                                            InspectDR.Delete();
                                        }
                                    }
                                }
                            }

                            // Update UserDefaults, if necessary
                            MaintainUserDefaults();

                            if (SubmitDS.Tables.Contains(PPartnerTaxDeductiblePctTable.GetTableName()))
                            {
                                UpdateTaxDeductiblePct();
                            }

                            // Call AcceptChanges to get rid now of any deleted columns before we Merge with the result from the Server
                            AInspectDS.AcceptChanges();
#if DATASETDEBUGGING
                            TLogging.Log("After getting rid now of any deleted columns   Client DataSet: " + AInspectDS.GetXml());

                            if (AInspectDS.Tables.Contains(PLocationTable.GetTableName()))
                            {
                                for (TmpRowCounter = 0; TmpRowCounter < AInspectDS.Tables[PLocationTable.GetTableName()].Rows.Count; TmpRowCounter++)
                                {
                                    TmpDebugString = TmpDebugString + PLocationTable.GetTableName() + ".Row[" + TmpRowCounter.ToString() +
                                                     "]: PLocationKey: " +
                                                     AInspectDS.Tables[PLocationTable.GetTableName()].Rows[TmpRowCounter][PLocationTable.
                                                                                                                          GetLocationKeyDBName()].
                                                     ToString() + "(); PSiteKey: " +
                                                     AInspectDS.Tables[PLocationTable.GetTableName()].Rows[TmpRowCounter][PLocationTable.
                                                                                                                          GetSiteKeyDBName()].
                                                     ToString() + "(); Modification TimeStamp: " +
                                                     AInspectDS.Tables[PLocationTable.GetTableName()].Rows[TmpRowCounter][PLocationTable.
                                                                                                                          GetModificationIdDBName()].
                                                     ToString() + "\r\n";
                                }
                            }

                            if (AInspectDS.Tables.Contains(PPartnerLocationTable.GetTableName()))
                            {
                                TmpDebugString = TmpDebugString + "\r\n";

                                for (TmpRowCounter = 0;
                                     TmpRowCounter < AInspectDS.Tables[PPartnerLocationTable.GetTableName()].Rows.Count;
                                     TmpRowCounter++)
                                {
                                    TmpDebugString = TmpDebugString + PPartnerLocationTable.GetTableName() + ".Row[" + TmpRowCounter.ToString() +
                                                     "]: PLocationKey: " +
                                                     AInspectDS.Tables[PPartnerLocationTable.GetTableName()].Rows[TmpRowCounter][
                                        PPartnerLocationTable.GetLocationKeyDBName()].ToString() + "(); PSiteKey: " +
                                                     AInspectDS.Tables[PPartnerLocationTable.GetTableName()].Rows[TmpRowCounter][
                                        PPartnerLocationTable.GetSiteKeyDBName()].ToString() + "(); PPartnerKey: " +
                                                     AInspectDS.Tables[PPartnerLocationTable.GetTableName()].Rows[TmpRowCounter][
                                        PPartnerLocationTable.GetPartnerKeyDBName()].ToString() + "(); Modification TimeStamp: " +
                                                     AInspectDS.Tables[PPartnerLocationTable.GetTableName()].Rows[TmpRowCounter][
                                        PPartnerLocationTable.GetModificationIdDBName()].ToString() + "\r\n";
                                }

                                MessageBox.Show(TmpDebugString, "DEBUG: PLocation / PPartnerLocation local contents  [#1]");
                            }
#endif
                            // Merge back with data from the Server (eg. for getting Sequence values)
                            AInspectDS.Merge(SubmitDS, false);
#if DATASETDEBUGGING
                            TLogging.Log("After Merge back with data from the Server  Server DataSet: " + SubmitDS.GetXml());
                            TLogging.Log("After Merge back with data from the Server  Client DataSet: " + AInspectDS.GetXml());

                            if (AInspectDS.Tables.Contains(PLocationTable.GetTableName()))
                            {
                                TmpDebugString = "";

                                for (TmpRowCounter = 0; TmpRowCounter < AInspectDS.Tables[PLocationTable.GetTableName()].Rows.Count; TmpRowCounter++)
                                {
                                    TmpDebugString = TmpDebugString + PLocationTable.GetTableName() + ".Row[" + TmpRowCounter.ToString() +
                                                     "]: PLocationKey: " +
                                                     AInspectDS.Tables[PLocationTable.GetTableName()].Rows[TmpRowCounter][PLocationTable.
                                                                                                                          GetLocationKeyDBName()].
                                                     ToString() + "(); PSiteKey: " +
                                                     AInspectDS.Tables[PLocationTable.GetTableName()].Rows[TmpRowCounter][PLocationTable.
                                                                                                                          GetSiteKeyDBName()].
                                                     ToString() + "(); Modification TimeStamp: " +
                                                     AInspectDS.Tables[PLocationTable.GetTableName()].Rows[TmpRowCounter][PLocationTable.
                                                                                                                          GetModificationIdDBName()].
                                                     ToString() + "\r\n";
                                }
                            }

                            if (AInspectDS.Tables.Contains(PPartnerLocationTable.GetTableName()))
                            {
                                TmpDebugString = TmpDebugString + "\r\n";

                                for (TmpRowCounter = 0;
                                     TmpRowCounter < AInspectDS.Tables[PPartnerLocationTable.GetTableName()].Rows.Count;
                                     TmpRowCounter++)
                                {
                                    TmpDebugString = TmpDebugString + PPartnerLocationTable.GetTableName() + ".Row[" + TmpRowCounter.ToString() +
                                                     "]: PLocationKey: " +
                                                     AInspectDS.Tables[PPartnerLocationTable.GetTableName()].Rows[TmpRowCounter][
                                        PPartnerLocationTable.GetLocationKeyDBName()].ToString() + "(); PSiteKey: " +
                                                     AInspectDS.Tables[PPartnerLocationTable.GetTableName()].Rows[TmpRowCounter][
                                        PPartnerLocationTable.GetSiteKeyDBName()].ToString() + "(); PPartnerKey: " +
                                                     AInspectDS.Tables[PPartnerLocationTable.GetTableName()].Rows[TmpRowCounter][
                                        PPartnerLocationTable.GetPartnerKeyDBName()].ToString() + "(); Modification TimeStamp: " +
                                                     AInspectDS.Tables[PPartnerLocationTable.GetTableName()].Rows[TmpRowCounter][
                                        PPartnerLocationTable.GetModificationIdDBName()].ToString() + "\r\n";
                                }

                                MessageBox.Show(TmpDebugString, "DEBUG: PLocation / PPartnerLocation local contents  [#2]");
                            }
#endif

                            ucoUpperPart.UpdateStatusUpdatedDate();  // this is to refresh 'Status Updated' if it has been changed in the ComboBox and then saved...

                            ucoLowerPart.RefreshRecordsAfterMerge();
                            ucoLowerPart.RefreshPersonnelDataAfterMerge(PartnerAttributesOrRelationsChanged);

                            // Call AcceptChanges so that we don't have any changed data anymore!
                            AInspectDS.AcceptChanges();
#if DATASETDEBUGGING
                            TLogging.Log("After calling AcceptChanges on the Client DataSet: " + AInspectDS.GetXml());
#endif
                            // Update UI
                            FPetraUtilsObject.WriteToStatusBar(MCommonResourcestrings.StrSavingDataSuccessful);
                            this.Cursor = Cursors.Default;
                            EnableSave(false);

                            // If the screen was opened for a NEW Partner, remove the 'NEW:' indicator from the Window Title Bar and
                            // set this Partner to be the "Last Used Partner".
                            if (SavedPartnerIsNewPartner)
                            {
                                FPetraUtilsObject.HasNewData = false;
                                SetScreenCaption();

                                // Set Partner to be the "Last Used Partner"
                                TUserDefaults.NamedDefaults.SetLastPartnerWorkedWith(AInspectDS.PPartner[0].PartnerKey,
                                    TLastPartnerUse.lpuMailroomPartner, SharedTypes.PartnerClassStringToEnum(FPartnerClass));
                            }

                            // We don't have unsaved changes anymore
                            FPetraUtilsObject.DisableSaveButton();
                            FPetraUtilsObject.SubmitChangesContinue = false;

                            // Assign PartnerKey. This is needed in case this was a new Partner before saving!
                            FPartnerKey = AInspectDS.PPartner[0].PartnerKey;

                            ReturnValue = true;
                            FPetraUtilsObject.OnDataSaved(this, new TDataSavedEventArgs(ReturnValue));

                            if ((VerificationResult != null)
                                && (VerificationResult.HasCriticalOrNonCriticalErrors))
                            {
                                TDataValidation.ProcessAnyDataValidationErrors(false, VerificationResult,
                                    this.GetType(), null);
                            }

                            break;

                        case TSubmitChangesResult.scrError:
                            this.Cursor = Cursors.Default;

                            if (!(VerificationResult.Contains((System.Object) "Location Change Promotion: Information")))
                            {
                                FPetraUtilsObject.WriteToStatusBar(MCommonResourcestrings.StrSavingDataErrorOccured);

                                TDataValidation.ProcessAnyDataValidationErrors(false, VerificationResult,
                                    this.GetType(), null);
                            }
                            else
                            {
                                FPetraUtilsObject.WriteToStatusBar(MCommonResourcestrings.StrSavingDataCancelled);

                                VerificationResultItem = (TVerificationResult)VerificationResult.FindBy(
                                    (object)"Location Change Promotion: Information");

                                MessageBox.Show(VerificationResultItem.ResultText,
                                    VerificationResultItem.ResultTextCaption, MessageBoxButtons.OK,
                                    MessageBoxIcon.Information);
                            }

                            FPetraUtilsObject.SubmitChangesContinue = false;

                            ReturnValue = false;
                            FPetraUtilsObject.OnDataSaved(this, new TDataSavedEventArgs(ReturnValue));
                            break;

                        case TSubmitChangesResult.scrNothingToBeSaved:

                            // If there were no changes discovered then still need to call AcceptChanges to get rid now of
                            // any deleted columns
                            AInspectDS.AcceptChanges();

                            // Update UI
                            this.Cursor = Cursors.Default;
                            FPetraUtilsObject.WriteToStatusBar(MCommonResourcestrings.StrSavingDataNothingToSave);

                            // We don't have unsaved changes anymore
                            EnableSave(false);
                            FPetraUtilsObject.HasChanges = false;

                            ReturnValue = true;
                            FPetraUtilsObject.OnDataSaved(this, new TDataSavedEventArgs(ReturnValue));
                            break;

                        case TSubmitChangesResult.scrInfoNeeded:
                            this.Cursor = Cursors.Default;
#if DATASETDEBUGGING
                            for (int Counter2 = 0; Counter2 < FResponseDS.Tables.Count; Counter2++)
                            {
                                MessageBox.Show(
                                    "Table #" + Counter2.ToString() + "'s name is " + FResponseDS.Tables[Counter2].TableName + ". It has " +
                                    FResponseDS.Tables[Counter2].Rows.Count.ToString() + " Rows. Type: " +
                                    FResponseDS.Tables[Counter2].GetType().ToString());
                            }

                            if (FResponseDS.Tables.Contains(MPartnerConstants.EXISTINGLOCATIONPARAMETERS_TABLENAME))
                            {
                                MessageBox.Show("FResponseDS Type: " + FResponseDS.GetType().ToString());
                                MessageBox.Show(MPartnerConstants.EXISTINGLOCATIONPARAMETERS_TABLENAME + " Type: " +
                                    FResponseDS.Tables[MPartnerConstants.EXISTINGLOCATIONPARAMETERS_TABLENAME].GetType().ToString());
                                MessageBox.Show(
                                    "FResponseDS.Tables[" + MPartnerConstants.EXISTINGLOCATIONPARAMETERS_TABLENAME + "].Rows.Count: " +
                                    FResponseDS.Tables[MPartnerConstants.EXISTINGLOCATIONPARAMETERS_TABLENAME].Rows.Count.ToString());
                                // Check if there is a Parameter Row that is not yet processed
                                DataView ExistingLocationParametersDV = new DataView(
                                    FResponseDS.Tables[MPartnerConstants.EXISTINGLOCATIONPARAMETERS_TABLENAME],
                                    PartnerAddressAggregateTDSSimilarLocationParametersTable.GetAnswerProcessedClientSideDBName() +
                                    " = false", "", DataViewRowState.CurrentRows);

                                if (ExistingLocationParametersDV.Count > 0)
                                {
                                    MessageBox.Show("ExistingLocationParametersDV.Count: " + ExistingLocationParametersDV.Count.ToString());
                                    MessageBox.Show(
                                        "Row[0].LocationKey: " +
                                        (ExistingLocationParametersDV[0].Row as PartnerAddressAggregateTDSSimilarLocationParametersRow).LocationKey.
                                        ToString());
                                }
                            }
#endif
                            ucoLowerPart.SimilarLocationsProcessing(
                            (PartnerAddressAggregateTDSSimilarLocationParametersTable)FResponseDS.Tables[MPartnerConstants.
                                                                                                         EXISTINGLOCATIONPARAMETERS_TABLENAME]);
#if DATASETDEBUGGING
                            if (FResponseDS.Tables[MPartnerConstants.EXISTINGLOCATIONPARAMETERS_TABLENAME].Rows.Count > 0)
                            {
                                MessageBox.Show("Reuse?: " + (FResponseDS.Tables[MPartnerConstants.EXISTINGLOCATIONPARAMETERS_TABLENAME]
                                                              as PartnerAddressAggregateTDSSimilarLocationParametersTable)[0].AnswerReuse.ToString());
                            }

                            if (FResponseDS.Tables.Contains(MPartnerConstants.ADDRESSADDEDORCHANGEDPROMOTION_TABLENAME))
                            {
                                MessageBox.Show(MPartnerConstants.ADDRESSADDEDORCHANGEDPROMOTION_TABLENAME + " Type: " +
                                    FResponseDS.Tables[MPartnerConstants.ADDRESSADDEDORCHANGEDPROMOTION_TABLENAME].GetType().ToString());
                                MessageBox.Show(
                                    "FResponseDS.Tables[" + MPartnerConstants.ADDRESSADDEDORCHANGEDPROMOTION_TABLENAME + "].Rows.Count: " +
                                    FResponseDS.Tables[MPartnerConstants.ADDRESSADDEDORCHANGEDPROMOTION_TABLENAME].Rows.Count.ToString());
                                //Check if there is a Parameter Row that is not yet processed
                                DataView AddressAddedOrChangedParametersDV = new DataView(
                                    FResponseDS.Tables[MPartnerConstants.ADDRESSADDEDORCHANGEDPROMOTION_TABLENAME],
                                    PartnerAddressAggregateTDSAddressAddedOrChangedPromotionTable.GetAnswerProcessedClientSideDBName() +
                                    " = false", "", DataViewRowState.CurrentRows);

                                if (AddressAddedOrChangedParametersDV.Count > 0)
                                {
                                    MessageBox.Show("AddressAddedOrChangedParametersDV.Count: " + AddressAddedOrChangedParametersDV.Count.ToString());
                                    MessageBox.Show(
                                        "Row[0].LocationKey: " +
                                        (AddressAddedOrChangedParametersDV[0].Row as PartnerAddressAggregateTDSAddressAddedOrChangedPromotionRow).
                                        LocationKey.
                                        ToString());
                                }
                            }
#endif
                            ucoLowerPart.AddressAddedOrChangedProcessing(
                            (PartnerAddressAggregateTDSAddressAddedOrChangedPromotionTable)
                            FResponseDS.Tables[MPartnerConstants.ADDRESSADDEDORCHANGEDPROMOTION_TABLENAME],
                            (PartnerAddressAggregateTDSChangePromotionParametersTable)
                            FResponseDS.Tables[MPartnerConstants.ADDRESSCHANGEPROMOTIONPARAMETERS_TABLENAME]);
#if DATASETDEBUGGING
                            MessageBox.Show("After AddressAddedOrChangedProcessing");
#endif
                            // Recursive call!
                            FPetraUtilsObject.SubmitChangesContinue = true;
                            ReturnValue = SaveChanges(ref AInspectDS);

                            return ReturnValue;
                    }
                }
                else
                {
                    // Update UI
                    FPetraUtilsObject.WriteToStatusBar(MCommonResourcestrings.StrSavingDataNothingToSave);
                    this.Cursor = Cursors.Default;
                    EnableSave(false);

                    // We don't have unsaved changes anymore
                    FPetraUtilsObject.HasChanges = false;

                    ReturnValue = true;
                    FPetraUtilsObject.OnDataSaved(this, new TDataSavedEventArgs(ReturnValue));
                }
            }
            else
            {
                FPetraUtilsObject.OnDataSaved(this, new TDataSavedEventArgs(false));
            }

            // if the partner has been saved then broadcast a message to any listening forms to inform them
            if (ReturnValue)
            {
                TFormsMessage BroadcastMessage;
                TFormsMessage BroadcastMessageGiftDestination;
                String PartnerShortNameForBroadcast;
                long FamilyPartnerKey;
                String FamilyShortName;

                if (SavedPartnerIsNewPartner)
                {
                    BroadcastMessage = new TFormsMessage(TFormsMessageClassEnum.mcNewPartnerSaved,
                        FCallerContext);
                }
                else
                {
                    BroadcastMessage = new TFormsMessage(TFormsMessageClassEnum.mcExistingPartnerSaved,
                        FCallerContext);
                }

                if (!FMainDS.PPartner[0].IsPartnerShortNameNull())
                {
                    PartnerShortNameForBroadcast = FMainDS.PPartner[0].PartnerShortName;
                }
                else
                {
                    PartnerShortNameForBroadcast = String.Empty;
                }

                BroadcastMessage.SetMessageDataPartner(
                    FPartnerKey,
                    SharedTypes.PartnerClassStringToEnum(FPartnerClass),
                    PartnerShortNameForBroadcast,
                    FMainDS.PPartner[0].StatusCode);

                TFormsList.GFormsList.BroadcastFormMessage(BroadcastMessage);

                if ((SubmitDS.PPartnerGiftDestination != null) && (SubmitDS.PPartnerGiftDestination.Rows.Count > 0))
                {
                    BroadcastMessageGiftDestination = new TFormsMessage(TFormsMessageClassEnum.mcPersonnelCommitmentChanged,
                        FCallerContext);

                    if (FPartnerClass == TPartnerClass.FAMILY.ToString())
                    {
                        FamilyPartnerKey = FPartnerKey;
                        FamilyShortName = PartnerShortNameForBroadcast;
                    }
                    else
                    {
                        FamilyPartnerKey = ((PPersonRow)FMainDS.PPerson.Rows[0]).FamilyKey;
                        FamilyShortName = String.Empty;
                    }

                    BroadcastMessageGiftDestination.SetMessageDataPartner(
                        FamilyPartnerKey,
                        TPartnerClass.FAMILY,
                        FamilyShortName,
                        FMainDS.PPartner[0].StatusCode);

                    TFormsList.GFormsList.BroadcastFormMessage(BroadcastMessageGiftDestination);
                }
            }

            return ReturnValue;
        }
        /// <summary>
        /// A payment made to a supplier needs to be reversed.
        /// It's done by creating and posting a set of matching "negatives" -
        /// In the simplest case this is a single credit note matching an invoice
        /// but it could be more complex. These negative documents are payed using
        /// a standard call to PostAPPayments.
        ///
        /// After the reversal, I'll also create and post new copies of all
        /// the invoices / credit notes that made up the original payment.
        /// </summary>
        /// <param name="ALedgerNumber"></param>
        /// <param name="APaymentNumber"></param>
        public void ReversePayment(Int32 ALedgerNumber, Int32 APaymentNumber)
        {
            AccountsPayableTDS TempDS = TRemote.MFinance.AP.WebConnectors.LoadAPPayment(ALedgerNumber, APaymentNumber);

            if (TempDS.AApPayment.Rows.Count == 0) // Invalid Payment number?
            {
                MessageBox.Show(Catalog.GetString("The referenced payment Connot be loaded."), Catalog.GetString("Error"));
                return;
            }

            TempDS.AApDocument.DefaultView.Sort = AApDocumentTable.GetApDocumentIdDBName();

            //
            // First I'll check that the amounts add up:
            //
            Decimal PaidDocumentsTotal = 0.0m;

            foreach (AApDocumentPaymentRow PaymentRow in TempDS.AApDocumentPayment.Rows)
            {
                Int32 DocIdx = TempDS.AApDocument.DefaultView.Find(PaymentRow.ApDocumentId);
                AApDocumentRow DocumentRow = TempDS.AApDocument[DocIdx];

                if (DocumentRow.CreditNoteFlag)
                {
                    PaidDocumentsTotal -= DocumentRow.TotalAmount;
                }
                else
                {
                    PaidDocumentsTotal += DocumentRow.TotalAmount;
                }
            }

            //
            // If this is a partial payment, I can't deal with that here...
            //
            if (PaidDocumentsTotal != TempDS.AApPayment[0].Amount)
            {
                String ErrorMsg =
                    String.Format(Catalog.GetString(
                            "This Payment cannot be reversed automatically because the total amount of the referenced documents ({0:n2} {1}) differs from the amount in the payment ({2:n2} {3})."),
                        PaidDocumentsTotal, TempDS.AApSupplier[0].CurrencyCode, TempDS.AApPayment[0].Amount, TempDS.AApSupplier[0].CurrencyCode);
                MessageBox.Show(ErrorMsg, Catalog.GetString("Reverse Payment"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            // Find out if this payment was already reversed,
            // because if it was, perhaps the user doesn't really want to
            // reverse it again?
            this.Cursor = Cursors.WaitCursor;

            if (TRemote.MFinance.AP.WebConnectors.WasThisPaymentReversed(ALedgerNumber, APaymentNumber))
            {
                this.Cursor = Cursors.Default;
                MessageBox.Show(Catalog.GetString("Cannot reverse Payment - there is already a matching reverse transaction."),
                    Catalog.GetString("Reverse Payment"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            this.Cursor = Cursors.Default;

            //
            // Ask the user to confirm reversal of this payment
            //
            String PaymentMsg = Catalog.GetString("Do you want to reverse this payment?");

            PaymentMsg += ("\r\n" + String.Format("Payment made {0} to {1}\r\n\r\nRelated invoices:",
                               TDate.DateTimeToLongDateString2(TempDS.AApPayment[0].PaymentDate.Value), TempDS.PPartner[0].PartnerShortName));

            foreach (AApDocumentPaymentRow PaymentRow in TempDS.AApDocumentPayment.Rows)
            {
                Int32 DocIdx = TempDS.AApDocument.DefaultView.Find(PaymentRow.ApDocumentId);
                AApDocumentRow DocumentRow = TempDS.AApDocument[DocIdx];
                PaymentMsg += ("\r\n" + String.Format("     {2} ({3})  {0:n2} {1}",
                                   DocumentRow.TotalAmount, TempDS.AApSupplier[0].CurrencyCode, DocumentRow.DocumentCode, DocumentRow.Reference));
            }

            PaymentMsg += ("\r\n\r\n" + String.Format("Total payment {0:n2} {1}", TempDS.AApPayment[0].Amount, TempDS.AApSupplier[0].CurrencyCode));
            DialogResult YesNo = MessageBox.Show(PaymentMsg, Catalog.GetString("Reverse Payment"), MessageBoxButtons.YesNo);

            if (YesNo == DialogResult.No)
            {
                return;
            }

            TDlgGLEnterDateEffective dateEffectiveDialog = new TDlgGLEnterDateEffective(
                ALedgerNumber,
                Catalog.GetString("Select posting date"),
                Catalog.GetString("The date effective for the reversal") + ":");

            if (dateEffectiveDialog.ShowDialog() != DialogResult.OK)
            {
                MessageBox.Show(Catalog.GetString("Reversal was cancelled."), Catalog.GetString("Reverse Payment"),
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            DateTime PostingDate = dateEffectiveDialog.SelectedDate;
            TVerificationResultCollection Verifications;

            this.Cursor = Cursors.WaitCursor;

            if (TRemote.MFinance.AP.WebConnectors.ReversePayment(ALedgerNumber, APaymentNumber, PostingDate, out Verifications))
            {
                this.Cursor = Cursors.Default;
                // TODO: print reports on successfully posted batch
                MessageBox.Show(Catalog.GetString("The AP payment has been reversed."), Catalog.GetString("Reverse Payment"));
                TFormsMessage broadcastMessage = new TFormsMessage(TFormsMessageClassEnum.mcAPTransactionChanged);
                broadcastMessage.SetMessageDataAPTransaction(String.Empty);
                TFormsList.GFormsList.BroadcastFormMessage(broadcastMessage);
            }
            else
            {
                this.Cursor = Cursors.Default;
                string ErrorMessages = String.Empty;

                foreach (TVerificationResult verif in Verifications)
                {
                    ErrorMessages += "[" + verif.ResultContext + "] " +
                                     verif.ResultTextCaption + ": " +
                                     verif.ResultText + Environment.NewLine;
                }

                System.Windows.Forms.MessageBox.Show(ErrorMessages, Catalog.GetString("Reverse Payment Failed"));
            }
        }
        /// <summary>
        /// Refreshes the Family Members list on the Family tab
        /// </summary>
        public void RefreshFamilyMembersList(TFormsMessage AFormsMessage)
        {
            IFormsMessagePartnerInterface FormsMessagePartner;

            if (FUcoFamilyMembers != null)
            {
                FormsMessagePartner = (IFormsMessagePartnerInterface)AFormsMessage.MessageObject;

                // return if the partner that has just been deleted/edited is not a member of this partner's family
                if (((AFormsMessage.MessageClass == TFormsMessageClassEnum.mcPartnerDeleted)
                     || (AFormsMessage.MessageClass == TFormsMessageClassEnum.mcExistingPartnerSaved))
                    && (FMainDS.FamilyMembers.Rows.Find(new object[] { FormsMessagePartner.PartnerKey }) == null))
                {
                    return;
                }

                FUcoFamilyMembers.BroadcastRefresh = true;
                FUcoFamilyMembers.RefreshFamilyMembersList(null, null);
                FUcoFamilyMembers.BroadcastRefresh = false;
            }
        }
Esempio n. 6
0
        // once an extract has been created, this will refresh extract master screen and open maintainance screen for extract
        private static void NewExtractCreated(string AExtractName, int AExtractId, Form AParentForm)
        {
            // refresh extract master screen if it is open
            TFormsMessage BroadcastMessage = new TFormsMessage(TFormsMessageClassEnum.mcExtractCreated);

            BroadcastMessage.SetMessageDataName(AExtractName);
            TFormsList.GFormsList.BroadcastFormMessage(BroadcastMessage);

            // now open Screen for new extract so user can add partner records manually
            TFrmExtractMaintain frm = new TFrmExtractMaintain(AParentForm);
            frm.ExtractId = AExtractId;
            frm.ExtractName = AExtractName;
            frm.Show();
        }
        /// <summary>
        /// Update Unit recipient based on a broadcast message
        /// </summary>
        /// <param name="AFormsMessage"></param>
        public void ProcessUnitHierarchyBroadcastMessage(TFormsMessage AFormsMessage)
        {
            // for some reason it is possible that this method can be called even if the parent form has been closed
            if (((TFrmRecurringGiftBatch)ParentForm) == null)
            {
                return;
            }

            if (txtDetailRecipientKey.CurrentPartnerClass != TPartnerClass.UNIT)
            {
                return;
            }

            List <Tuple <string, Int64,
                         Int64>>UnitHierarchyChanges =
                ((TFormsMessage.FormsMessageUnitHierarchy)AFormsMessage.MessageObject).UnitHierarchyChanges;

            // loop backwards as the most recent (and accurate) change will be at the end
            for (int i = UnitHierarchyChanges.Count - 1; i >= 0; i--)
            {
                if (UnitHierarchyChanges[i].Item2 == Convert.ToInt64(txtDetailRecipientKey.Text))
                {
                    GetRecipientData(Convert.ToInt64(txtDetailRecipientKey.Text));
                    break;
                }
            }
        }
        /// <summary>
        /// Will be called by TFormsList to inform any Form that is registered in TFormsList
        /// about any 'Forms Messages' that are broadcasted.
        /// </summary>
        /// <remarks>The Partner Edit 'listens' to such 'Forms Message' broadcasts by
        /// implementing this virtual Method. This Method will be called each time a
        /// 'Forms Message' broadcast occurs.
        /// </remarks>
        /// <param name="AFormsMessage">An instance of a 'Forms Message'. This can be
        /// inspected for parameters in the Method Body and the Form can use those to choose
        /// to react on the Message, or not.</param>
        /// <returns>Returns True if the Form reacted on the specific Forms Message,
        /// otherwise false.</returns>
        public bool ProcessFormsMessage(TFormsMessage AFormsMessage)
        {
            bool MessageProcessed = false;

            if (AFormsMessage.MessageClass == TFormsMessageClassEnum.mcExtractCreated)
            {
                FPetraUtilsObject.GetForm().BringToFront();

                if (FDelegateRefreshExtractList())
                {
                    // this is required as extracts are created on a different thread
                    if (this.InvokeRequired)
                    {
                        this.BeginInvoke((MethodInvoker) delegate()
                            {
                                // show filter panel
                                MniFilterFind_Click(GetPetraUtilsObject().GetForm(), null);
                                // show the screen in case it has been hidden
                                FPetraUtilsObject.GetForm().Show();
                                // filter results to show the new extract
                                ((TextBox)FFilterAndFindObject.FilterPanelControls.FindControlByName("txtExtractName")).Text =
                                    ((TFormsMessage.FormsMessageName)AFormsMessage.MessageObject).Name;
                            });
                    }
                }

                MessageProcessed = true;
            }

            return MessageProcessed;
        }
        /// <summary>
        /// Update Unit recipient based on a broadcast message
        /// </summary>
        /// <param name="AFormsMessage"></param>
        public void ProcessUnitHierarchyBroadcastMessage(TFormsMessage AFormsMessage)
        {
            // for some reason it is possible that this method can be called even if the parent form has been closed
            if (((TFrmGiftBatch)ParentForm) == null)
            {
                return;
            }

            if (txtDetailRecipientKey.CurrentPartnerClass != TPartnerClass.UNIT)
            {
                return;
            }

            List <Tuple <string, Int64,
                         Int64>>UnitHierarchyChanges =
                ((TFormsMessage.FormsMessageUnitHierarchy)AFormsMessage.MessageObject).UnitHierarchyChanges;

            // loop backwards as the most recent (and accurate) change will be at the end
            for (int i = UnitHierarchyChanges.Count - 1; i >= 0; i--)
            {
                if (UnitHierarchyChanges[i].Item2 == Convert.ToInt64(txtDetailRecipientKey.Text))
                {
                    TUC_GiftTransactions_Recipient.GetRecipientData(FPreviouslySelectedDetailRow,
                        Convert.ToInt64(txtDetailRecipientKey.Text),
                        ref cmbKeyMinistries,
                        txtDetailRecipientKey,
                        ref txtDetailRecipientLedgerNumber,
                        false);

                    break;
                }
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void FileSave(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;

            if (SaveChanges())
            {
                // Broadcast message to update partner's Partner Edit screen if open
                TFormsMessage BroadcastMessage = new TFormsMessage(TFormsMessageClassEnum.mcUnitHierarchyChanged);
                BroadcastMessage.SetMessageDataUnitHierarchy(FChangedParents);
                TFormsList.GFormsList.BroadcastFormMessage(BroadcastMessage);

                FChangedParents = new List <Tuple <string, long, long>>();

                FPetraUtilsObject.HasChanges = false;
                FPetraUtilsObject.DisableSaveButton();
            }

            this.Cursor = Cursors.Default;
        }
Esempio n. 11
0
        /// <summary>
        /// Will be called by TFormsList to inform any Form that is registered in TFormsList
        /// about any 'Forms Messages' that are broadcasted.
        /// </summary>
        /// <remarks>The Partner Edit 'listens' to such 'Forms Message' broadcasts by
        /// implementing this virtual Method. This Method will be called each time a
        /// 'Forms Message' broadcast occurs.
        /// </remarks>
        /// <param name="AFormsMessage">An instance of a 'Forms Message'. This can be
        /// inspected for parameters in the Method Body and the Form can use those to choose
        /// to react on the Message, or not.</param>
        /// <returns>Returns True if the Form reacted on the specific Forms Message,
        /// otherwise false.</returns>
        public bool ProcessFormsMessage(TFormsMessage AFormsMessage)
        {
            bool MessageProcessed = false;

            if ((AFormsMessage.MessageClass == TFormsMessageClassEnum.mcNewPartnerSaved)
                || (AFormsMessage.MessageClass == TFormsMessageClassEnum.mcExistingPartnerSaved)
                || (AFormsMessage.MessageClass == TFormsMessageClassEnum.mcPartnerDeleted))
            {
                // Refreshes the Suppliers list on the Suppliers tab
                FIsSupplierDataChanged = true;

                if (tabSearchResult.SelectedTab == tpgSuppliers)
                {
                    ucoSuppliers.LoadSuppliers();
                }

                MessageProcessed = true;
            }
            else if (AFormsMessage.MessageClass == TFormsMessageClassEnum.mcAPTransactionChanged)
            {
                // Refresh the outstanding invoices
                FIsInvoiceDataChanged = true;

                if (tabSearchResult.SelectedTab == tpgOutstandingInvoices)
                {
                    ucoOutstandingInvoices.LoadInvoices();
                }

                MessageProcessed = true;
            }

            return MessageProcessed;
        }
        /// <summary>
        /// Update Gift Destination based on a broadcast message
        /// </summary>
        /// <param name="AFormsMessage"></param>
        public void ProcessGiftDetainationBroadcastMessage(TFormsMessage AFormsMessage)
        {
            // for some reason it is possible that this method can be called even if the parent form has been closed
            if (((TFrmGiftBatch)ParentForm) == null)
            {
                return;
            }

            // update dataset from controls
            GetDataFromControls();

            // loop through every gift detail currently in the dataset
            foreach (AGiftDetailRow DetailRow in FMainDS.AGiftDetail.Rows)
            {
                if (DetailRow.RecipientKey == ((TFormsMessage.FormsMessageGiftDestination)AFormsMessage.MessageObject).PartnerKey)
                {
                    // only make changes if gift is unposted, not a reversal and doesn't have a fixed gift destination
                    if ((!DetailRow.IsFixedGiftDestinationNull() && DetailRow.FixedGiftDestination)
                        || (((AGiftBatchRow)FMainDS.AGiftBatch.Rows.Find(
                                 new object[] { DetailRow.LedgerNumber, DetailRow.BatchNumber })).BatchStatus != MFinanceConstants.BATCH_UNPOSTED)
                        || (!DetailRow.IsModifiedDetailNull() && DetailRow.ModifiedDetail))
                    {
                        continue;
                    }

                    DetailRow.RecipientLedgerNumber = 0;
                    DateTime GiftDate = ((AGiftRow)FMainDS.AGift.Rows.Find(
                                             new object[] { DetailRow.LedgerNumber, DetailRow.BatchNumber,
                                                            DetailRow.GiftTransactionNumber })).DateEntered;

                    foreach (PPartnerGiftDestinationRow Row in ((TFormsMessage.FormsMessageGiftDestination)AFormsMessage.MessageObject).
                             GiftDestinationTable.Rows)
                    {
                        // check if record is active for the Gift Date
                        if ((Row.DateEffective <= GiftDate)
                            && ((Row.DateExpires >= GiftDate) || Row.IsDateExpiresNull())
                            && (Row.DateEffective != Row.DateExpires))
                        {
                            DetailRow.RecipientLedgerNumber = Row.FieldKey;
                        }
                    }

                    // update control if updated gift is currently being displayed
                    if (!string.IsNullOrEmpty(txtDetailRecipientKey.Text) && (Convert.ToInt64(txtDetailRecipientKey.Text) == DetailRow.RecipientKey)
                        && (dtpDateEntered.Date == GiftDate))
                    {
                        txtDetailRecipientLedgerNumber.Text = DetailRow.RecipientLedgerNumber.ToString();
                    }
                }
            }
        }
        /// <summary>
        /// Deletes the currently selected Partner.
        /// </summary>
        public bool DeletePartner()
        {
            TFormsMessage BroadcastMessage;

            if (TPartnerMain.DeletePartner(FPartnerKey, ((UserControl) this.ParentForm).ParentForm))
            {
                BroadcastMessage = new TFormsMessage(TFormsMessageClassEnum.mcPartnerDeleted,
                    null);

                BroadcastMessage.SetMessageDataPartner(
                    FPartnerKey,
                    SharedTypes.PartnerClassStringToEnum(DetermineCurrentPartnerClass()),
                    "",
                    DetermineCurrentPartnerStatus());

                TFormsList.GFormsList.BroadcastFormMessage(BroadcastMessage);

                return true;
            }

            return false;
        }
 /// <summary>
 /// Refreshes the Family Members list on the Family tab
 /// </summary>
 public void RefreshFamilyMembersList(TFormsMessage AFormsMessage)
 {
     ucoPartnerTabSet.RefreshFamilyMembersList(AFormsMessage);
 }
        /// <summary>
        /// Will be called by TFormsList to inform any Form that is registered in TFormsList
        /// about any 'Forms Messages' that are broadcasted.
        /// </summary>
        /// <remarks>This screen 'listens' to such 'Forms Message' broadcasts by
        /// implementing this virtual Method. This Method will be called each time a
        /// 'Forms Message' broadcast occurs.
        /// </remarks>
        /// <param name="AFormsMessage">An instance of a 'Forms Message'. This can be
        /// inspected for parameters in the Method Body and the Form can use those to choose
        /// to react on the Message, or not.</param>
        /// <returns>Returns True if the Form reacted on the specific Forms Message,
        /// otherwise false.</returns>
        public bool ProcessFormsMessage(TFormsMessage AFormsMessage)
        {
            bool MessageProcessed = false;

            if (AFormsMessage.MessageClass == TFormsMessageClassEnum.mcAccountsChanged)
            {
                string CurrentlySelectedAccountCode = FPreviouslySelectedDetailRow.AccountCode;
                Type DataTableType;

                // Load Data
                DataTable CacheDT = TDataCache.GetSpecificallyFilteredCacheableDataTableFromCache("AccountList", "Ledger", FFilter, out DataTableType);
                FMainDS.AAccount.Merge(CacheDT);

                GetData();

                // reapply filter
                FFilterAndFindObject.ApplyFilter();

                // reselect the last selected account code
                if (FPreviouslySelectedDetailRow != null)
                {
                    SelectAccountInGrid(CurrentlySelectedAccountCode);
                }

                UpdateRecordNumberDisplay();

                MessageProcessed = true;
            }

            return MessageProcessed;
        }
        /// <summary>
        /// Stores the manual code.
        /// </summary>
        /// <param name="ASubmitDS">a submit ds.</param>
        /// <param name="AVerificationResult">a verification result.</param>
        /// <returns></returns>
        private TSubmitChangesResult StoreManualCode(ref GLSetupTDS ASubmitDS, out TVerificationResultCollection AVerificationResult)
        {
            //
            // I need to remove any AnalysisAttribute records that are still set to "Unassigned"
            //
            if ((ASubmitDS.AAnalysisAttribute != null) && (ASubmitDS.AAnalysisAttribute.Rows.Count > 0))
            {
                for (int Idx = ASubmitDS.AAnalysisAttribute.Rows.Count - 1; Idx >= 0; Idx--)
                {
                    AAnalysisAttributeRow Row = ASubmitDS.AAnalysisAttribute[Idx];

                    if ((Row.RowState != DataRowState.Deleted) && (Row.AnalysisTypeCode.IndexOf("Unassigned") == 0))
                    {
                        Row.Delete();
                    }
                }
            }

            //
            // I'll take this opportunity to remove any similar records in my own TDS
            //
            for (int Idx = FMainDS.AAnalysisAttribute.Rows.Count - 1; Idx >= 0; Idx--)
            {
                AAnalysisAttributeRow Row = FMainDS.AAnalysisAttribute[Idx];

                if ((Row.RowState != DataRowState.Deleted) && (Row.AnalysisTypeCode.IndexOf("Unassigned") == 0))
                {
                    Row.Delete();
                }
            }

            ucoAccountsTree.MarkAllNodesCommitted();
            TSubmitChangesResult ServerResult =
                TRemote.MFinance.Setup.WebConnectors.SaveGLSetupTDS(FLedgerNumber, ref ASubmitDS, out AVerificationResult);
            TDataCache.TMFinance.RefreshCacheableFinanceTable(Shared.TCacheableFinanceTablesEnum.AccountList, FLedgerNumber);

            if (ServerResult == TSubmitChangesResult.scrOK)
            {
                if ((FZeroForeignCurrencyBalances != null) && (FZeroForeignCurrencyBalances.Count > 0))
                {
                    Int32 Year = (Int32)TDataCache.TMFinance.GetCacheableFinanceTable(
                        TCacheableFinanceTablesEnum.LedgerDetails, FLedgerNumber).Rows[0][ALedgerTable.GetCurrentFinancialYearDBName()];

                    // Makes all foreign currency balances zero for the given accounts in the current ledger year for all posting cost centres
                    TRemote.MFinance.Setup.WebConnectors.ZeroForeignCurrencyBalances(FLedgerNumber, Year, FZeroForeignCurrencyBalances.ToArray());
                    FZeroForeignCurrencyBalances.Clear();
                }

                // Broadcast message to update partner's Partner Edit screen if open
                TFormsMessage BroadcastMessage = new TFormsMessage(TFormsMessageClassEnum.mcAccountsChanged);
                BroadcastMessage.SetMessageDataAccounts();
                TFormsList.GFormsList.BroadcastFormMessage(BroadcastMessage);
            }

            return ServerResult;
        }
Esempio n. 17
0
        /// <summary>
        /// this is where all the calculations take place
        /// </summary>
        /// <returns>
        /// true if the report was successfully generated
        /// </returns>
        public Boolean GenerateResultRemoteClient()
        {
            Boolean ReturnValue;
            Thread ProgressCheckThread;

            ReturnValue = false;
            FReportingGenerator = TRemote.MReporting.UIConnectors.ReportGenerator();
            FKeepUpProgressCheck = true;

            try
            {
                this.Results = new TResultList();
                FReportingGenerator.Start(this.Parameters.ToDataTable());
                ProgressCheckThread = new Thread(new ThreadStart(AsyncProgressCheckThread));
                ProgressCheckThread.Start();
            }
            catch (Exception e)
            {
                TLogging.Log(e.Message);

                // Release the server object
                FReportingGenerator = null;

                return false;
            }

            // todo: allow canceling of the calculation of a report
            while (FKeepUpProgressCheck)
            {
                Thread.Sleep(500);
            }

            ReturnValue = FReportingGenerator.GetSuccess();

            // Do not release the server object, we still might want to send an email...
            // FReportingGenerator = null;

            if (ReturnValue)
            {
                if (FCalculatesExtract)
                {
                    TLogging.Log("Extract calculation finished. Look for extract '" +
                        Parameters.Get("param_extract_name").ToString() +
                        "' in Extract Master List.", TLoggingType.ToStatusBar);

                    TFormsMessage BroadcastMessage = new TFormsMessage(TFormsMessageClassEnum.mcExtractCreated);
                    BroadcastMessage.SetMessageDataName(Parameters.Get("param_extract_name").ToString());
                    TFormsList.GFormsList.BroadcastFormMessage(BroadcastMessage);
                }
                else
                {
                    TLogging.Log("Report calculation finished.", TLoggingType.ToStatusBar);
                }
            }

            return ReturnValue;
        }
        /// <summary>
        /// Will be called by TFormsList to inform any Form that is registered in TFormsList
        /// about any 'Forms Messages' that are broadcasted.
        /// </summary>
        /// <remarks>The Partner Edit 'listens' to such 'Forms Message' broadcasts by
        /// implementing this virtual Method. This Method will be called each time a
        /// 'Forms Message' broadcast occurs.
        /// </remarks>
        /// <param name="AFormsMessage">An instance of a 'Forms Message'. This can be
        /// inspected for parameters in the Method Body and the Form can use those to choose
        /// to react on the Message, or not.</param>
        /// <returns>Returns True if the Form reacted on the specific Forms Message,
        /// otherwise false.</returns>
        public bool ProcessFormsMessage(TFormsMessage AFormsMessage)
        {
            bool MessageProcessed = false;

            if (AFormsMessage.MessageClass == TFormsMessageClassEnum.mcAPTransactionChanged)
            {
                // The message is relevant if the supplier name is empty (=any supplier) or our specific supplier
                if ((((TFormsMessage.FormsMessageAP)AFormsMessage.MessageObject).SupplierName == this.lblSupplierName.Text)
                    || (((TFormsMessage.FormsMessageAP)AFormsMessage.MessageObject).SupplierName == String.Empty))
                {
                    // Reload the screen data
                    Reload();
                }

                MessageProcessed = true;
            }

            return MessageProcessed;
        }
        /// <summary>
        /// Will be called by TFormsList to inform any Form that is registered in TFormsList
        /// about any 'Forms Messages' that are broadcasted.
        /// </summary>
        /// <remarks>Theis screen 'listens' to such 'Forms Message' broadcasts by
        /// implementing this virtual Method. This Method will be called each time a
        /// 'Forms Message' broadcast occurs.
        /// </remarks>
        /// <param name="AFormsMessage">An instance of a 'Forms Message'. This can be
        /// inspected for parameters in the Method Body and the Form can use those to choose
        /// to react on the Message, or not.</param>
        /// <returns>Returns True if the Form reacted on the specific Forms Message,
        /// otherwise false.</returns>
        public bool ProcessFormsMessage(TFormsMessage AFormsMessage)
        {
            bool MessageProcessed = false;

            if ((AFormsMessage.MessageClass == TFormsMessageClassEnum.mcPersonnelCommitmentChanged)
                && (((IFormsMessagePartnerInterface)AFormsMessage.MessageObject).PartnerKey == FPartnerKey))
            {
                TSearchCriteria[] Search = new TSearchCriteria[1];
                Search[0] = new TSearchCriteria(PPartnerGiftDestinationTable.GetPartnerKeyDBName(), FPartnerKey);

                FMainDS = new TLocalMainTDS();
                Ict.Common.Data.TTypedDataTable TypedTable;
                TRemote.MCommon.DataReader.WebConnectors.GetData(PPartnerGiftDestinationTable.GetTableDBName(), Search, out TypedTable);
                FMainDS.PPartnerGiftDestination.Merge(TypedTable);

                SetupGrid();
                UpdateRecordNumberDisplay();
                SelectRowInGrid(1);

                MessageProcessed = true;
            }

            return MessageProcessed;
        }
 /// <summary>
 /// Will be called by TFormsList to inform any Form that is registered in TFormsList
 /// about any 'Forms Messages' that are broadcasted.
 /// </summary>
 /// <remarks>The Partner Edit 'listens' to such 'Forms Message' broadcasts by
 /// implementing this virtual Method. This Method will be called each time a
 /// 'Forms Message' broadcast occurs.
 /// </remarks>
 /// <param name="AFormsMessage">An instance of a 'Forms Message'. This can be
 /// inspected for parameters in the Method Body and the Form can use those to choose
 /// to react on the Message, or not.</param>
 /// <returns>Returns True if the Form reacted on the specific Forms Message,
 /// otherwise false.</returns>
 public bool ProcessFormsMessage(TFormsMessage AFormsMessage)
 {
     return ucoExtractMasterList.ProcessFormsMessage(AFormsMessage);
 }
        /// <summary>
        /// Update Gift Destination based on a broadcast message
        /// </summary>
        /// <param name="AFormsMessage"></param>
        public void ProcessGiftDetainationBroadcastMessage(TFormsMessage AFormsMessage)
        {
            // for some reason it is possible that this method can be called even if the parent form has been closed
            if (((TFrmRecurringGiftBatch)ParentForm) == null)
            {
                return;
            }

            // update dataset from controls
            GetDataFromControls();

            // loop through every gift detail currently in the dataset
            foreach (ARecurringGiftDetailRow DetailRow in FMainDS.ARecurringGiftDetail.Rows)
            {
                if (DetailRow.RecipientKey == ((TFormsMessage.FormsMessageGiftDestination)AFormsMessage.MessageObject).PartnerKey)
                {
                    DetailRow.RecipientLedgerNumber = 0;

                    foreach (PPartnerGiftDestinationRow Row in ((TFormsMessage.FormsMessageGiftDestination)AFormsMessage.MessageObject).
                             GiftDestinationTable.Rows)
                    {
                        // check if record is active for the Gift Date
                        if ((Row.DateEffective <= DateTime.Today)
                            && ((Row.DateExpires >= DateTime.Today) || Row.IsDateExpiresNull())
                            && (Row.DateEffective != Row.DateExpires))
                        {
                            DetailRow.RecipientLedgerNumber = Row.FieldKey;
                        }
                    }

                    // update control if updated gift is currently being displayed
                    if (!string.IsNullOrEmpty(txtDetailRecipientKey.Text) && (Convert.ToInt64(txtDetailRecipientKey.Text) == DetailRow.RecipientKey))
                    {
                        txtDetailRecipientLedgerNumber.Text = DetailRow.RecipientLedgerNumber.ToString();
                    }
                }
            }
        }
        private void FPetraUtilsObject_DataSaved(object Sender, TDataSavedEventArgs e)
        {
            if (e.Success)
            {
                // Reload details on successful save. This is so dtpDetailDateEffective can be made readonly
                if (!FPetraUtilsObject.HasChanges)
                {
                    ShowDetailsManual(FPreviouslySelectedDetailRow);
                }

                if (!this.Modal)
                {
                    // Broadcast message to update partner's Partner Edit screen if open
                    TFormsMessage BroadcastMessage;

                    BroadcastMessage = new TFormsMessage(TFormsMessageClassEnum.mcGiftDestinationChanged);

                    BroadcastMessage.SetMessageDataGiftDestination(
                        FPartnerKey,
                        FMainDS.PPartnerGiftDestination);

                    TFormsList.GFormsList.BroadcastFormMessage(BroadcastMessage);
                }
            }
        }
        /// <summary>
        /// Post document as a GL Batch
        /// See very similar function in TFrmAPSupplierTransactions
        /// </summary>
        private void PostDocument(object sender, EventArgs e)
        {
            if (FPetraUtilsObject.HasChanges)
            {
                MessageBox.Show(Catalog.GetString("Document should be saved before posting."), Catalog.GetString(
                        "Post Document"), MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }

            GetDataFromControls(FMainDS.AApDocument[0]);

            // TODO: make sure that there are uptodate exchange rates

            if (!ApDocumentCanPost(FMainDS, FMainDS.AApDocument[0]))
            {
                return;
            }

            List <Int32>TaggedDocuments = new List <Int32>();

            TaggedDocuments.Add(FMainDS.AApDocument[0].ApDocumentId);

            if (PostApDocumentList(FMainDS, FMainDS.AApDocument[0].LedgerNumber, TaggedDocuments, this))
            {
                // TODO: print reports on successfully posted batch
                MessageBox.Show(Catalog.GetString("The AP document has been posted successfully!"));

                //
                // Refresh by re-loading the document from the server
                Int32 DocumentId = FMainDS.AApDocument[0].ApDocumentId;
                FMainDS.Clear();
                FPreviouslySelectedDetailRow = null;
                LoadAApDocument(FDocumentLedgerNumber, DocumentId);

                //
                // Also refresh the opener?
                TFormsMessage broadcastMessage = new TFormsMessage(TFormsMessageClassEnum.mcAPTransactionChanged);
                broadcastMessage.SetMessageDataAPTransaction(lblSupplierName.Text);
                TFormsList.GFormsList.BroadcastFormMessage(broadcastMessage);
            }
        }
Esempio n. 24
0
        /// <summary>
        /// this is where all the calculations take place
        /// </summary>
        /// <returns>true if the report was successfully generated
        /// </returns>
        public Boolean GenerateResultRemoteClient()
        {
            Boolean ReturnValue;
            Thread ProgressCheckThread;

            ReturnValue = false;
            FReportingGenerator = TRemote.MReporting.UIConnectors.ReportGenerator();
            FKeepUpProgressCheck = true;

            // Register Object with the TEnsureKeepAlive Class so that it doesn't get GC'd
            TEnsureKeepAlive.Register(FReportingGenerator);
            try
            {
                this.Results = new TResultList();
                FReportingGenerator.Start(this.Parameters.ToDataTable());
                ProgressCheckThread = new Thread(new ThreadStart(AsyncProgressCheckThread));
                ProgressCheckThread.Start();
            }
            catch (Exception e)
            {
                TLogging.Log(e.Message);

                // UnRegister Object from the TEnsureKeepAlive Class so that the Object can get GC'd on the PetraServer
                TEnsureKeepAlive.UnRegister(FReportingGenerator);

                return false;
            }

            // todo: allow canceling of the calculation of a report
            while (FKeepUpProgressCheck)
            {
                Thread.Sleep(500);
            }

            ReturnValue = FReportingGenerator.GetSuccess();

            // UnRegister Object from the TEnsureKeepAlive Class so that the Object can get GC'd on the PetraServer
            TEnsureKeepAlive.UnRegister(FReportingGenerator);

            if (ReturnValue)
            {
                if (FCalculatesExtract)
                {
                    TLogging.Log("Extract calculation finished. Look for extract '" +
                        Parameters.Get("param_extract_name").ToString() +
                        "' in Extract Master List.", TLoggingType.ToStatusBar);

                    TFormsMessage BroadcastMessage = new TFormsMessage(TFormsMessageClassEnum.mcExtractCreated);

                    BroadcastMessage.SetMessageDataName(Parameters.Get("param_extract_name").ToString());

                    TFormsList.GFormsList.BroadcastFormMessage(BroadcastMessage);
                }
                else
                {
                    TLogging.Log("Report calculation finished.", TLoggingType.ToStatusBar);
                }
            }

            return ReturnValue;
        }
 /// <summary>
 /// When this document is saved in the database, I can check whether
 /// my calling form should be updated.
 /// </summary>
 /// <param name="Sender"></param>
 /// <param name="e"></param>
 private void OnDataSaved(object Sender, TDataSavedEventArgs e)
 {
     if (e.Success)
     {
         TFormsMessage broadcastMessage = new TFormsMessage(TFormsMessageClassEnum.mcAPTransactionChanged);
         broadcastMessage.SetMessageDataAPTransaction(txtSupplierName.Text);
         TFormsList.GFormsList.BroadcastFormMessage(broadcastMessage);
     }
 }
        /// <summary>
        /// Will be called by TFormsList to inform any Form that is registered in TFormsList
        /// about any 'Forms Messages' that are broadcasted.
        /// </summary>
        /// <remarks>The Partner Edit 'listens' to such 'Forms Message' broadcasts by
        /// implementing this virtual Method. This Method will be called each time a
        /// 'Forms Message' broadcast occurs.
        /// </remarks>
        /// <param name="AFormsMessage">An instance of a 'Forms Message'. This can be
        /// inspected for parameters in the Method Body and the Form can use those to choose
        /// to react on the Message, or not.</param>
        /// <returns>Returns True if the Form reacted on the specific Forms Message,
        /// otherwise false.</returns>
        public bool ProcessFormsMessage(TFormsMessage AFormsMessage)
        {
            bool MessageProcessed = false;

            // update gift destination
            if (AFormsMessage.MessageClass == TFormsMessageClassEnum.mcGiftDestinationChanged)
            {
                ucoRecurringTransactions.ProcessGiftDetainationBroadcastMessage(AFormsMessage);

                MessageProcessed = true;
            }
            else if (AFormsMessage.MessageClass == TFormsMessageClassEnum.mcUnitHierarchyChanged)
            {
                ucoRecurringTransactions.ProcessUnitHierarchyBroadcastMessage(AFormsMessage);

                MessageProcessed = true;
            }

            return MessageProcessed;
        }
        /// <summary>
        /// Approve Document for posting.
        /// See very similar function in TFrmAPSupplierTransactions
        /// </summary>
        ///
        private void ApproveDocument(object sender, EventArgs e)
        {
            if (FPetraUtilsObject.HasChanges)
            {
                MessageBox.Show(Catalog.GetString("Document should be saved before approving."), Catalog.GetString(
                        "Approve Document"), MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }

            List <Int32>DocsList = new List <int>();

            DocsList.Add(FMainDS.AApDocument[0].ApDocumentId);
            this.Cursor = Cursors.WaitCursor;
            TVerificationResultCollection verificationResult;
            string MsgTitle = Catalog.GetString("Document Approval");

            if (TRemote.MFinance.AP.WebConnectors.ApproveAPDocuments(FMainDS.AApDocument[0].LedgerNumber, DocsList, out verificationResult))
            {
                this.Cursor = Cursors.Default;
                MessageBox.Show(Catalog.GetString("Document has been approved."), MsgTitle);

                FMainDS.AApDocument[0].DocumentStatus = MFinanceConstants.AP_DOCUMENT_APPROVED; // The "changed" light isn't lit by this, because the change
                                                                                                // already took place on the server.
                EnableControls();

                //
                // Also refresh the opener
                TFormsMessage broadcastMessage = new TFormsMessage(TFormsMessageClassEnum.mcAPTransactionChanged);
                broadcastMessage.SetMessageDataAPTransaction(lblSupplierName.Text);
                TFormsList.GFormsList.BroadcastFormMessage(broadcastMessage);
            }
            else
            {
                this.Cursor = Cursors.Default;
                MessageBox.Show(verificationResult.BuildVerificationResultString(), MsgTitle);
            }
        }
        /// <summary>
        /// Standard method to process a OP Forms Message from another window
        /// </summary>
        /// <param name="AFormsMessage">The message</param>
        /// <returns>True if we handle the message</returns>
        public bool ProcessFormsMessage(TFormsMessage AFormsMessage)
        {
            bool MessageProcessed = false;

            // Is it for us??
            if (AFormsMessage.MessageClass == TFormsMessageClassEnum.mcGLOrGiftBatchSaved)
            {
                // We received this message because a GL or Gift Batch was saved that contained a Forex row!!
                // remember the current row
                int nCurrentRow = GetSelectedRowIndex();

                // re-load the data
                FMainDS.Clear();
                FMainDS.Merge(TRemote.MFinance.Common.WebConnectors.LoadDailyExchangeRateData(false));
                FMainDS.AcceptChanges();

                // select the same row as before
                SelectRowInGrid(nCurrentRow);

                MessageProcessed = true;
            }

            return MessageProcessed;
        }
        /// <summary>
        /// Will be called by TFormsList to inform any Form that is registered in TFormsList
        /// about any 'Forms Messages' that are broadcasted.
        /// </summary>
        /// <remarks>This screen 'listens' to such 'Forms Message' broadcasts by
        /// implementing this virtual Method. This Method will be called each time a
        /// 'Forms Message' broadcast occurs.
        /// </remarks>
        /// <param name="AFormsMessage">An instance of a 'Forms Message'. This can be
        /// inspected for parameters in the Method Body and the Form can use those to choose
        /// to react on the Message, or not.</param>
        /// <returns>Returns True if the Form reacted on the specific Forms Message,
        /// otherwise false.</returns>
        public bool ProcessFormsMessage(TFormsMessage AFormsMessage)
        {
            bool MessageProcessed = false;

            if ((((IFormsMessagePartnerInterface)AFormsMessage.MessageObject).PartnerClass == TPartnerClass.BANK)
                && ((AFormsMessage.MessageClass == TFormsMessageClassEnum.mcNewPartnerSaved)
                    || (AFormsMessage.MessageClass == TFormsMessageClassEnum.mcExistingPartnerSaved)))
            {
                FMainDS = null;
                FBankPartnerKey = ((IFormsMessagePartnerInterface)AFormsMessage.MessageObject).PartnerKey;
                LoadDataGrid(false);

                MessageProcessed = true;
            }

            return MessageProcessed;
        }
Esempio n. 30
0
 private void FPetraUtilsObject_DataSaved(object sender, TDataSavedEventArgs e)
 {
     if (e.Success && FLatestSaveIncludedForex)
     {
         // Notify the exchange rate screen, if it is there
         TFormsMessage broadcastMessage = new TFormsMessage(TFormsMessageClassEnum.mcGLOrGiftBatchSaved, this.ToString());
         TFormsList.GFormsList.BroadcastFormMessage(broadcastMessage);
     }
 }
Esempio n. 31
0
        private void MakePayment(object sender, EventArgs e)
        {
            FSelectedDocumentRow.Amount = Decimal.Parse(txtAmountToPay.Text);
            FSelectedPaymentRow.BankAccount = cmbBankAccount.GetSelectedString();
            AccountsPayableTDSAApPaymentTable AApPayment = FMainDS.AApPayment;

            //
            // I want to check whether the user is paying more than the due amount on any of these payments...
            //
            foreach (AccountsPayableTDSAApPaymentRow PaymentRow in AApPayment.Rows)
            {
                FMainDS.AApDocumentPayment.DefaultView.RowFilter = String.Format("{0}={1}",
                    AApDocumentPaymentTable.GetPaymentNumberDBName(), PaymentRow.PaymentNumber);

                foreach (DataRowView rv in FMainDS.AApDocumentPayment.DefaultView)
                {
                    AccountsPayableTDSAApDocumentPaymentRow DocPaymentRow = (AccountsPayableTDSAApDocumentPaymentRow)rv.Row;
                    Boolean overPayment = (DocPaymentRow.DocType == "INVOICE") ?
                                          (DocPaymentRow.Amount > DocPaymentRow.InvoiceTotal) : (DocPaymentRow.Amount < DocPaymentRow.InvoiceTotal);

                    if (overPayment)
                    {
                        String strMessage =
                            String.Format(Catalog.GetString(
                                    "Payment of {0} {1} to {2}: Payment cannot be more than the due amount."),
                                StringHelper.FormatUsingCurrencyCode(DocPaymentRow.Amount, PaymentRow.CurrencyCode),
                                PaymentRow.CurrencyCode, PaymentRow.SupplierName);

                        System.Windows.Forms.MessageBox.Show(strMessage, Catalog.GetString("OverPayment"));
                        return;
                    }
                }
            }

            TDlgGLEnterDateEffective dateEffectiveDialog = new TDlgGLEnterDateEffective(
                FMainDS.AApDocument[0].LedgerNumber,
                Catalog.GetString("Select payment date"),
                Catalog.GetString("The date effective for the payment") + ":");

            if (dateEffectiveDialog.ShowDialog() != DialogResult.OK)
            {
                MessageBox.Show(Catalog.GetString("The payment was cancelled."), Catalog.GetString(
                        "No Success"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            DateTime PaymentDate = dateEffectiveDialog.SelectedDate;
            TVerificationResultCollection Verifications;

            this.Cursor = Cursors.WaitCursor;

            if (!TRemote.MFinance.AP.WebConnectors.PostAPPayments(
                    ref FMainDS,
                    PaymentDate,
                    out Verifications))
            {
                this.Cursor = Cursors.Default;
                string ErrorMessages = String.Empty;

                foreach (TVerificationResult verif in Verifications)
                {
                    ErrorMessages += "[" + verif.ResultContext + "] " +
                                     verif.ResultTextCaption + ": " +
                                     verif.ResultText + Environment.NewLine;
                }

                System.Windows.Forms.MessageBox.Show(ErrorMessages, Catalog.GetString("Payment failed"));
            }
            else
            {
                this.Cursor = Cursors.Default;
                PrintPaymentReport(sender, e);
                PrintRemittanceAdvice();

                // TODO: show posting register of GL Batch?

                // After the payments screen, The status of this document may have changed.
                TFormsMessage broadcastMessage = new TFormsMessage(TFormsMessageClassEnum.mcAPTransactionChanged);
                broadcastMessage.SetMessageDataAPTransaction(String.Empty);
                TFormsList.GFormsList.BroadcastFormMessage(broadcastMessage);

                Close();
            }
        }