//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
        //Helper for Create DocumentFinanceSeries & DocumentFinanceYearSerieTerminal
        //Used to generate Series Preview, or to Process Series in Database

        public static FrameworkCallsResult CreateDocumentFinanceYearSeriesTerminal(fin_documentfinanceyears pDocumentFinanceYears, DataTable pTerminals, string pAcronym, bool pPreviewMode)
        {
            FrameworkCallsResult result = new FrameworkCallsResult();
            uint   ordAndCode = 10;
            uint   ordAndCodeInc = 10;
            int    terminalInc = 1;
            string acronymPrefix = String.Empty, acronym, designation, output = String.Empty, acronymAudit;
            Dictionary <string, string> acronymPrefixCreatedSeries = new Dictionary <string, string>();
            fin_documentfinanceseries   documentFinanceSeries = null;
            //Used to add DocumentFinanceYearSerieTerminal to list to delete outside of Loop
            List <fin_documentfinanceyearserieterminal> listDeleteSerieTerminal = new List <fin_documentfinanceyearserieterminal>();

            //Start UnitOfWork
            using (UnitOfWork uowSession = new UnitOfWork())
            {
                try
                {
                    //Get Object in UOW Session
                    fin_documentfinanceyears documentFinanceYears = (fin_documentfinanceyears)FrameworkUtils.GetXPGuidObject(uowSession, typeof(fin_documentfinanceyears), pDocumentFinanceYears.Oid);

                    //Initialize DocumentFinanceType Collection : Criteria/XPCollection/Model : Use Default Filter
                    CriteriaOperator criteria = CriteriaOperator.Parse("(Disabled = 0 OR Disabled IS NULL)");
                    //Configure SortProperty
                    SortProperty sortProperty = new SortProperty("Ord", DevExpress.Xpo.DB.SortingDirection.Ascending);
                    //Init Collection
                    XPCollection xpDocumentFinanceType = new XPCollection(uowSession, typeof(fin_documentfinancetype), criteria, sortProperty);

                    //Loop Terminals
                    foreach (DataRow terminal in pTerminals.Rows)
                    {
                        //Disable Series and Delete SerieTerminal for selected Terminal
                        if (!pPreviewMode)
                        {
                            //Initialize DocumentFinanceYearSerieTerminal Collection : Criteria/XPCollection/Model : Use Default Filter + Terminal
                            criteria = CriteriaOperator.Parse(string.Format("(Disabled = 0 OR Disabled IS NULL) AND (Terminal = '{0}')", terminal["Oid"]));
                            //Init Collection
                            XPCollection xpDocumentFinanceYearSerieTerminal = new XPCollection(uowSession, typeof(fin_documentfinanceyearserieterminal), criteria);

                            //Loop DocumentFinanceYearSerieTerminal and Parent DocumentFinanceYearSerie and Delete
                            foreach (fin_documentfinanceyearserieterminal documentFinanceYearSerieTerminal in xpDocumentFinanceYearSerieTerminal)
                            {
                                if (_debug)
                                {
                                    _log.Debug(string.Format("Disabled documentFinanceYearSerie: [{0}]", documentFinanceYearSerieTerminal.Serie.Designation));
                                }
                                documentFinanceYearSerieTerminal.Serie.Disabled = true;
                                //documentFinanceYearSerieTerminal.Disabled = true;
                                //Add to Post Loop Deletion
                                listDeleteSerieTerminal.Add(documentFinanceYearSerieTerminal);
                            }

                            //Now we can delete, Outside of Loop
                            foreach (fin_documentfinanceyearserieterminal deleteSerieTerminal in listDeleteSerieTerminal)
                            {
                                if (_debug)
                                {
                                    _log.Debug(string.Format("Deleted documentFinanceYearSerieTerminal: [{0}]", deleteSerieTerminal.Designation));
                                }
                                deleteSerieTerminal.Delete();
                            }
                        }

                        //Add to Output
                        if (pPreviewMode)
                        {
                            output += string.Format("{0}{1}", terminal["Designation"], Environment.NewLine);
                        }

                        //Get Current Terminal Object
                        pos_configurationplaceterminal configurationPlaceTerminal = (pos_configurationplaceterminal)uowSession.GetObjectByKey(typeof(pos_configurationplaceterminal), new Guid(terminal["Oid"].ToString()));

                        //Create DocumentFinanceSeries Acronym From Date
                        DateTime now = FrameworkUtils.CurrentDateTimeAtomic();

                        //AcronymPrefix ex FT[QN3T1U401]2016S001, works with Random and AcronymLastSerie modes
                        if (SettingsApp.DocumentFinanceSeriesGenerationFactoryUseRandomAcronymPrefix)
                        {
                            acronymPrefix = DateToAcronymPrefix(new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second));
                        }
                        //AcronymPrefix ex Fatura FT[0001]2016S001
                        else
                        {
                            //Get acronymPrefix in first DocumentFinanceType, not in every Document, this way we have uniform series
                            acronymPrefix = (xpDocumentFinanceType[0] as fin_documentfinancetype).AcronymLastSerie.ToString(SettingsApp.DocumentFinanceSeriesGenerationFactoryAcronymLastSerieFormat);
                        }

                        //Add to Created List
                        acronymPrefixCreatedSeries.Add(acronymPrefix, configurationPlaceTerminal.Designation);

                        foreach (fin_documentfinancetype documentFinanceType in xpDocumentFinanceType)
                        {
                            //Ignored DocumentTypes (DocumentFinanceTypeInvoiceWayBill, this DocumentType use DocumentFinanceTypeInvoice Serie)
                            if (documentFinanceType.Oid != SettingsApp.XpoOidDocumentFinanceTypeInvoiceWayBill)
                            {
                                //2018-05-08 : Old Format : [FT005012018S1] : Search GenDocumentNumber in ProcessFinanceDocument
                                //acronym = string.Format("{0}{1}{2}{3}", documentFinanceType.Acronym, acronymPrefix, terminalInc.ToString("00"), pAcronym);
                                //2018-05-08 : New Format
                                //acronym = string.Format("{0} {1}{2}{3}", documentFinanceType.Acronym, pAcronym, acronymPrefix, terminalInc);
                                acronym     = string.Format("{0} {1}{2}", documentFinanceType.Acronym, pAcronym, acronymPrefix);
                                designation = string.Format("{0} {1}", documentFinanceType.Designation, acronym);
                                if (!pPreviewMode)
                                {
                                    documentFinanceSeries = new fin_documentfinanceseries(uowSession)
                                    {
                                        Ord                      = ordAndCode,
                                        Code                     = ordAndCode,
                                        FiscalYear               = documentFinanceYears,
                                        DocumentType             = documentFinanceType,
                                        NextDocumentNumber       = 1,
                                        DocumentNumberRangeBegin = 1,
                                        DocumentNumberRangeEnd   = int.MaxValue,
                                        Acronym                  = acronym,
                                        Designation              = designation
                                    };
                                }
                                //Add to Output
                                if (pPreviewMode)
                                {
                                    output += string.Format("  {0} {1} - {2}{3}", documentFinanceType.Acronym, acronym, documentFinanceType.Designation, Environment.NewLine);
                                }
                                if (_debug)
                                {
                                    _log.Debug(string.Format("DocumentFinanceSeries: [{0}], Designation: [{1}], Acronym: [{2}]", ordAndCode, designation, acronym));
                                }

                                //Create DocumentFinanceYearSerieTerminal
                                designation = string.Format("{0} {1}", designation, configurationPlaceTerminal.Designation);
                                if (!pPreviewMode)
                                {
                                    fin_documentfinanceyearserieterminal documentFinanceYearSerieTerminal = new fin_documentfinanceyearserieterminal(uowSession)
                                    {
                                        Ord          = ordAndCode,
                                        Code         = ordAndCode,
                                        FiscalYear   = documentFinanceYears,
                                        DocumentType = documentFinanceSeries.DocumentType,
                                        Serie        = documentFinanceSeries,
                                        Terminal     = configurationPlaceTerminal,
                                        Printer      = configurationPlaceTerminal.Printer,
                                        Template     = documentFinanceSeries.DocumentType.Template,
                                        Designation  = string.Format("{0} {1}", documentFinanceSeries.Designation, configurationPlaceTerminal.Designation)
                                    };
                                }
                                if (_debug)
                                {
                                    _log.Debug(string.Format("DocumentFinanceYearSerieTerminal: [{0}], Terminal: [{1}], Serie: [{2}]", ordAndCode, terminal["Designation"], designation));
                                }

                                //Increment AcronymLastSerie and ordAndCodeInc
                                documentFinanceType.AcronymLastSerie++;
                                ordAndCode = ordAndCode + ordAndCodeInc;
                            }
                        }
                        //Add Blank Line to Split Series/Terminal
                        if (pPreviewMode && pTerminals.Rows.Count > terminalInc)
                        {
                            output += Environment.NewLine;
                        }
                        //Increment Terminal
                        terminalInc++;
                    }

                    //Finnaly Commit Changes
                    if (!pPreviewMode)
                    {
                        uowSession.CommitChanges();
                    }

                    result.Result = true;

                    if (pPreviewMode)
                    {
                        result.Output = output;
                    }
                    else
                    {
                        foreach (var item in acronymPrefixCreatedSeries)
                        {
                            //Audit FINANCE_SERIES_CREATED
                            acronymAudit = string.Format("{0}{1}{2}{3}", "xx", item.Key, 0.ToString("00"), pAcronym);
                            FrameworkUtils.Audit("FINANCE_SERIES_CREATED", string.Format(resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "audit_message_finance_series_created"), acronymAudit, item.Value, GlobalFramework.LoggedUser.Name));
                        }
                    }
                }
                catch (Exception ex)
                {
                    uowSession.RollbackTransaction();
                    result.Exception = ex;
                    _log.Error(ex.Message, ex);
                }
            }
            return(result);
        }
        //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
        //Shared UI Helper to Request Selected Terminals to send to ProcessFinanceDocumentSeries (Framework)

        public static bool UICreateDocumentFinanceYearSeriesTerminal(Window pSourceWindow, FIN_DocumentFinanceYears pDocumentFinanceYear)
        {
            bool result = false;

            try
            {
                //Refresh Terminal XPO Object
                XPCollection xpcConfigurationPlaceTerminal = new XPCollection(GlobalFramework.SessionXpo, typeof(POS_ConfigurationPlaceTerminal));
                xpcConfigurationPlaceTerminal.Reload();

                //Get Terminals
                DataTable dataTableSelectedTerminals = PosSelectRecordDialog <DataTable, DataRow, TreeViewTerminalSeries> .GetSelected(pSourceWindow);

                //Store Reference to BackOffice TreeViewDocumentFinanceYearSerieTerminal
                TreeViewDocumentFinanceSeries treeViewDocumentFinanceSeries =
                    ((pSourceWindow as BackOfficeMainWindow).Accordion.Nodes["TopMenuDocuments"].Childs.ContainsKey("DocumentFinanceSeries"))
                    ? ((pSourceWindow as BackOfficeMainWindow).Accordion.Nodes["TopMenuDocuments"].Childs["DocumentFinanceSeries"].Content as TreeViewDocumentFinanceSeries)
                    : null;

                //Store Reference to BackOffice TreeViewDocumentFinanceYearSerieTerminal
                TreeViewDocumentFinanceYearSerieTerminal treeViewDocumentFinanceYearSerieTerminal =
                    ((pSourceWindow as BackOfficeMainWindow).Accordion.Nodes["TopMenuDocuments"].Childs.ContainsKey("DocumentFinanceYearSerieTerminal"))
                    ? ((pSourceWindow as BackOfficeMainWindow).Accordion.Nodes["TopMenuDocuments"].Childs["DocumentFinanceYearSerieTerminal"].Content as TreeViewDocumentFinanceYearSerieTerminal)
                    : null;

                if (dataTableSelectedTerminals != null && dataTableSelectedTerminals.Rows.Count > 0)
                {
                    //Request Acronym
                    //string initialValue = string.Format("{0}{1}", pDocumentFinanceYear.Acronym, "01");
                    string initialValue = pDocumentFinanceYear.Acronym;
                    logicpos.Utils.ResponseText resultAcronym = TreeViewDocumentFinanceSeries.PosConfirmAcronymSeriesDialog(pSourceWindow, pDocumentFinanceYear, dataTableSelectedTerminals, initialValue);

                    // Protect to Skip Cancel
                    if (resultAcronym.ResponseType == ResponseType.Ok)
                    {
                        int    sqlCheckExistingSeriesResultInt = 0;
                        string sqlCheckExistingSeries          = "SELECT COUNT(*) AS Count FROM fin_documentfinanceseries WHERE (Disabled = 0 OR Disabled IS NULL);";
                        object sqlCheckExistingSeriesResult    = GlobalFramework.SessionXpo.ExecuteScalar(sqlCheckExistingSeries);
                        if (sqlCheckExistingSeriesResult != null)
                        {
                            sqlCheckExistingSeriesResultInt = Convert.ToInt16(sqlCheckExistingSeriesResult);
                        }

                        //Request User Confirmation if already has working Series
                        ResponseType responseType = ResponseType.No;
                        if (resultAcronym.ResponseType == ResponseType.Ok && sqlCheckExistingSeriesResultInt > 0)
                        {
                            responseType = Utils.ShowMessageTouch(
                                GlobalApp.WindowStartup,
                                DialogFlags.Modal,
                                MessageType.Question,
                                ButtonsType.YesNo,
                                Resx.window_title_series_create_series,
                                Resx.dialog_message_series_create_confirmation_text
                                );
                        }
                        else
                        {
                            //Auto Yes, if dont have series, assumes Yes
                            responseType = ResponseType.Yes;
                        }

                        if (responseType == ResponseType.Yes)
                        {
                            //Get Result
                            FrameworkCallsResult frameworkCallsResult = ProcessFinanceDocumentSeries.CreateDocumentFinanceYearSeriesTerminal(pDocumentFinanceYear, dataTableSelectedTerminals, resultAcronym.Text, false);
                            //Prepare Result
                            result = frameworkCallsResult.Result;
                            //Refresh Child Trees DocumentFinanceYearSerieTerminal
                            if (result)
                            {
                                //Refresh TreeViewDocumentFinanceSeries (If Visible/Enabled)
                                if (treeViewDocumentFinanceSeries != null)
                                {
                                    treeViewDocumentFinanceSeries.Refresh();
                                }
                                //Refresh TreeViewDocumentFinanceYearSerieTerminal (If Visible/Enabled)
                                if (treeViewDocumentFinanceYearSerieTerminal != null)
                                {
                                    treeViewDocumentFinanceYearSerieTerminal.Refresh();
                                }
                            }
                            //Show Error to User, Outside of Framework (Non UI)
                            else
                            {
                                Utils.ShowMessageTouch(
                                    pSourceWindow,
                                    DialogFlags.Modal,
                                    MessageType.Error,
                                    ButtonsType.Ok,
                                    Resx.global_error,
                                    string.Format("{0}{1}{1}{2}",
                                                  string.Format(Resx.dialog_message_series_create_error, resultAcronym.Text),
                                                  Environment.NewLine,
                                                  frameworkCallsResult.Exception.InnerException.Message
                                                  )
                                    );
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message, ex);
            }

            return(result);
        }