Exemple #1
0
        //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
        //Logic

        //Assign Selected UserDetail to classe Member
        private void AssignUserDetail()
        {
            try
            {
                if (_tablePadUser.SelectedButtonOid != null)
                {
                    _selectedUserDetail = (FrameworkUtils.GetXPGuidObject(typeof(sys_userdetail), _tablePadUser.SelectedButtonOid) as sys_userdetail);
                    if (_selectedUserDetail != null)
                    {
                        //Change NumberPadPinMode Mode
                        _numberPadPin.Mode = (_selectedUserDetail.PasswordReset) ? NumberPadPinMode.PasswordOld : NumberPadPinMode.Password;

                        if (_selectedUserDetail.PasswordReset)
                        {
                            //_log.Debug(string.Format("Name: [{0}], PasswordReset: [{1}]", _selectedUserDetail.Name, _selectedUserDetail.PasswordReset));
                            Utils.ShowMessageTouch(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "global_information"),
                                                   string.Format(resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "dialog_message_user_request_change_password"), _selectedUserDetail.Name, SettingsApp.DefaultValueUserDetailAccessPin)
                                                   );
                        }
                    }
                }

                //Grab Focus
                _numberPadPin.EntryPin.GrabFocus();
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message, ex);
            }
        }
Exemple #2
0
        private void LoadRefreshView()
        {
            _listStoreModelPermissionItem.Clear();

            //UserProfile _currentXPObject = (UserProfile)_dataSource.Lookup(new Guid("" + TreeView.Model.GetValue(_treeIter, _modelFirstCustomFieldIndex)));
            sys_userprofile _currentXPObject = (sys_userprofile)FrameworkUtils.GetXPGuidObject(GlobalFramework.SessionXpo, typeof(sys_userprofile), new Guid("" + TreeView.Model.GetValue(_treeIter, _modelFirstCustomFieldIndex)));

            for (int i = 0; i < _xpCollectionUserPermissionItem.Count; i++)
            {
                bool tmpCurrentValue = false;
                sys_userpermissionitem tmpUserPermissionItem = ((sys_userpermissionitem)_xpCollectionUserPermissionItem[i]);

                try
                {
                    for (int j = 0; j < _xpCollectionUserPermissionProfile.Count; j++)
                    {
                        sys_userpermissionprofile tmpUserPermissionProfile = ((sys_userpermissionprofile)_xpCollectionUserPermissionProfile[j]);
                        if (tmpUserPermissionProfile.UserProfile != null && tmpUserPermissionProfile.PermissionItem != null)
                        {
                            if ((tmpUserPermissionProfile.UserProfile.Oid == _currentXPObject.Oid) &&
                                (tmpUserPermissionProfile.PermissionItem.Oid == tmpUserPermissionItem.Oid))
                            {
                                tmpCurrentValue = tmpUserPermissionProfile.Granted;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    _log.Error(ex.Message, ex);
                }
                _listStoreModelPermissionItem.AppendValues("" + tmpUserPermissionItem.Oid, tmpUserPermissionItem.Designation, tmpCurrentValue);
            }
        }
Exemple #3
0
        //Extra Stuff to LogicPos BootStrap
        private static void InitExtended()
        {
            try
            {
                //TODO
                //http://stackoverflow.com/questions/9640240/accessing-a-resource-file-from-a-different-project-with-resourcemanager-c-sharp
                //ResourceManager rm = new ResourceManager("Namespace.LanguageLocalization", logicpos.financial.library.Classes);

                //Override Paths
                GlobalFramework.Path["assets"]  = @"c:\SVN\logicpos\trunk\src\logicpos\Assets\";
                GlobalFramework.Path["reports"] = @"c:\SVN\logicpos\trunk\src\logicpos\Resources\Reports\";
                //Get Terminal from DB
                GlobalFramework.LoggedUser = (sys_userdetail)FrameworkUtils.GetXPGuidObject(GlobalFramework.SessionXpo, typeof(sys_userdetail), new Guid(GlobalFramework.Settings["xpoOidUserDetailDefaultLoggedUser"]));
                //Get Permissions
                GlobalFramework.LoggedUserPermissions = FrameworkUtils.GetUserPermissions();
                //Override Terminal Printer (PDF)
                //GlobalFramework.LoggedTerminal.Printer = (sys_configurationprinters)GlobalFramework.SessionXpo.GetObjectByKey(typeof(sys_configurationprinters), SettingsApp.LoggedTerminalPrinter);
                GlobalApp.PrinterExportPDF = (sys_configurationprinters)GlobalFramework.SessionXpo.GetObjectByKey(typeof(sys_configurationprinters), SettingsApp.XpoOidPrinterExportPDF);
                GlobalApp.PrinterThermal   = (sys_configurationprinters)GlobalFramework.SessionXpo.GetObjectByKey(typeof(sys_configurationprinters), SettingsApp.XpoOidPrinterThermal);

                if (GlobalFramework.LoggedTerminal == null)
                {
                    _log.Debug("Invalid Printer. Working Without Printer");
                }
                //Override Licence
                GlobalFramework.LicenceCompany = "Logicpulse : Demonstração";
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message, ex);
            }
        }
Exemple #4
0
        public override XPGuidObject DataSourceRowGetNewRecord()
        {
            XPGuidObject newXPGuidObject = (XPGuidObject)Activator.CreateInstance(_xpoGuidObjectType);

            foreach (GenericTreeViewColumnProperty column in _columnProperties)
            {
                //if (_debug) _log.Debug(string.Format("column.Name: [{0}], column.Type: [{1}]", column.Name, column.Type));
                if (column.InitialValue != null)
                {
                    //If is a XPGuidObject
                    if (column.InitialValue.GetType().BaseType == typeof(XPGuidObject))
                    {
                        //Get Fresh Object else "object belongs to a different session"
                        var xInitialValue = FrameworkUtils.GetXPGuidObject(newXPGuidObject.Session, column.InitialValue.GetType(), (column.InitialValue as XPGuidObject).Oid);
                        newXPGuidObject.SetMemberValue(column.Name, xInitialValue);
                    }
                    //Default Values
                    else
                    {
                        newXPGuidObject.SetMemberValue(column.Name, column.InitialValue);
                    }
                }
            }

            return(newXPGuidObject);
        }
Exemple #5
0
        //Change and Persist TableStatus
        public void ChangeTableStatus(Guid pTableOid, TableStatus pTableStatus)
        {
            //Get Target Table
            POS_ConfigurationPlaceTable xTable = (POS_ConfigurationPlaceTable)FrameworkUtils.GetXPGuidObject(typeof(POS_ConfigurationPlaceTable), pTableOid);

            //_log.Debug(string.Format("1 pTableStatus: [{0}] [{1}]", xTable.Designation, pTableStatus));

            if (pTableStatus == TableStatus.Reserved)
            {
                _labelTotalOrStatus.Text             = Resx.global_reserved_table;
                _eventBoxTotalOrStatus.VisibleWindow = true;
                SetBackgroundColor(_colorPosTablePadTableTableStatusReservedButtonBackground, _eventBoxTotalOrStatus);
                xTable.TableStatus = TableStatus.Reserved;
                FrameworkUtils.Audit("TABLE_RESERVED", string.Format(Resx.audit_message_table_reserved, xTable.Designation));
            }
            else
            {
                _labelTotalOrStatus.Text             = string.Empty;
                _eventBoxTotalOrStatus.VisibleWindow = false;
                SetBackgroundColor(_buttonColor, _eventBoxTotalOrStatus);
                xTable.TableStatus = TableStatus.Free;
                FrameworkUtils.Audit("TABLE_UNRESERVED", string.Format(Resx.audit_message_table_unreserved, xTable.Designation));
            }
            //_log.Debug(string.Format("1 pTableStatus: [{0}] [{1}]", xTable.Designation, pTableStatus));
            //Update Status State
            _tableStatus = pTableStatus;
            //Persist in DB
            xTable.Save();
        }
Exemple #6
0
        private void UpdateState(string pOid, bool pNewValue)
        {
            //UserProfile _currentXPObject = (UserProfile)_dataSource.Lookup(new Guid("" + TreeView.Model.GetValue(_treeIter, _modelFirstCustomFieldIndex)));
            sys_userprofile _currentXPObject = (sys_userprofile)FrameworkUtils.GetXPGuidObject(GlobalFramework.SessionXpo, typeof(sys_userprofile), new Guid("" + TreeView.Model.GetValue(_treeIter, _modelFirstCustomFieldIndex)));

            sys_userpermissionprofile tmpUserPermissionProfileUpdate = null;// (UserPermissionProfile)_xpCollection2.Lookup(new Guid("" + pOid));

            bool needToInsert = true;

            for (int i = 0; i < _xpCollectionUserPermissionItem.Count; i++)
            {
                sys_userpermissionitem tmpUserPermissionItem = ((sys_userpermissionitem)_xpCollectionUserPermissionItem[i]);

                try
                {
                    if (tmpUserPermissionItem.Oid == new Guid("" + pOid))
                    {
                        for (int j = 0; j < _xpCollectionUserPermissionProfile.Count; j++)
                        {
                            sys_userpermissionprofile tmpUserPermissionProfile = ((sys_userpermissionprofile)_xpCollectionUserPermissionProfile[j]);

                            if ((tmpUserPermissionProfile.UserProfile != null) && (tmpUserPermissionProfile.PermissionItem != null))
                            {
                                if ((tmpUserPermissionProfile.UserProfile.Oid == _currentXPObject.Oid) &&
                                    (tmpUserPermissionProfile.PermissionItem.Oid == tmpUserPermissionItem.Oid))
                                {
                                    needToInsert = true;
                                    //((UserPermissionProfile)_xpCollection3[j]).Disabled = !pNewValue;
                                    //((UserPermissionProfile)_xpCollectionUserPermissionProfile[j]).Delete();
                                    //Mario Fix: Get Fresh Object else Gives Object Deleted Stress
                                    tmpUserPermissionProfile = (sys_userpermissionprofile)FrameworkUtils.GetXPGuidObject(GlobalFramework.SessionXpo, typeof(sys_userpermissionprofile), tmpUserPermissionProfile.Oid);
                                    tmpUserPermissionProfile.Delete();
                                    _xpCollectionUserPermissionProfile.Reload();
                                }
                            }
                        }

                        if (needToInsert)
                        {
                            tmpUserPermissionProfileUpdate = (sys_userpermissionprofile)Activator.CreateInstance(_xpObjectTypeUserPermissionProfile, GlobalFramework.SessionXpo);
                            tmpUserPermissionProfileUpdate.Reload();
                            tmpUserPermissionProfileUpdate.UserProfile = _currentXPObject;
                            //Mario Fix: Get Fresh Object else Gives Object Deleted Stress
                            tmpUserPermissionItem = (sys_userpermissionitem)FrameworkUtils.GetXPGuidObject(GlobalFramework.SessionXpo, typeof(sys_userpermissionitem), tmpUserPermissionItem.Oid);
                            tmpUserPermissionProfileUpdate.PermissionItem = tmpUserPermissionItem;
                            tmpUserPermissionProfileUpdate.Granted        = !pNewValue;
                            tmpUserPermissionProfileUpdate.Save();
                            _xpCollectionUserPermissionProfile.Reload();
                        }
                        else
                        {
                        }
                    }
                }
                catch (Exception ex)
                {
                    _log.Error(ex.Message, ex);
                }
            }
        }
Exemple #7
0
        public void UpdateMenuPrivileges()
        {
            string currentNodePrivilegesToken;

            //Required to Reload Object before Get New Permissions
            GlobalFramework.LoggedUser = (sys_userdetail)FrameworkUtils.GetXPGuidObject(GlobalFramework.SessionXpo, typeof(sys_userdetail), GlobalFramework.LoggedUser.Oid);
            //Update Session Privileges
            GlobalFramework.LoggedUserPermissions = FrameworkUtils.GetUserPermissions(GlobalFramework.LoggedUser);

            //Update Backoffice Menu
            if (_accordionDefinition != null && _accordionDefinition.Count > 0)
            {
                foreach (var parentLevel in _accordionDefinition)
                {
                    if (parentLevel.Value.Childs.Count > 0)
                    {
                        foreach (var childLevel in parentLevel.Value.Childs)
                        {
                            currentNodePrivilegesToken = string.Format(_nodePrivilegesTokenFormat, childLevel.Key.ToUpper());
                            //_log.Debug(string.Format("[{0}]=[{1}] [{2}]=[{3}]", childLevel.Value.NodeButton.Sensitive, childLevel.Value.NodeButton.Name, currentNodePrivilegesToken, FrameworkUtils.HasPermissionTo(currentNodePrivilegesToken)));
                            //If have (Content | Events | ExternalApp) & Privileges or the Button is Enabled, Else is Disabled
                            if (FrameworkUtils.HasPermissionTo(currentNodePrivilegesToken) && (childLevel.Value.Content != null || childLevel.Value.Clicked != null || childLevel.Value.ExternalAppFileName != null))
                            {
                                childLevel.Value.NodeButton.Sensitive = true;
                            }
                            else
                            {
                                childLevel.Value.NodeButton.Sensitive = false;
                            }
                        }
                    }
                }
            }
        }
Exemple #8
0
        /// <summary>
        /// If Record is Selected and Ok clicked
        /// </summary>
        /// <param name="pEntry"></param>
        /// <param name="dialog"></param>
        private void SelectRecord(Entry pEntry, PosSelectRecordDialog <XPCollection, XPGuidObject, T2> dialog)
        {
            PropertyInfo propertyInfo;

            //Store previousValue before update _value, to keep it
            _previousValue = _value;

            //Get Object from dialog else Mixing Sessions, Both belong to diferente Sessions
            _value       = (T1)FrameworkUtils.GetXPGuidObject(typeof(T1), dialog.GenericTreeView.DataSourceRow.Oid);
            propertyInfo = typeof(T1).GetProperty(_fieldDisplayValue);

            object value = null;

            if (propertyInfo != null)
            {
                // Get value from XPGuidObject Instance
                value = propertyInfo.GetValue(_value, null);
            }
            else
            {
                string invalidFieldMessage = string.Format("Invalid Field DisplayValue:[{0}] on XPGuidObject:[{1}]", _fieldDisplayValue, _value.GetType().Name);
                _log.Error(invalidFieldMessage);
                value = invalidFieldMessage;
            }

            pEntry.Text = (value != null) ? value.ToString() : resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "global_error");

            //Call Custom Event, Only if OK, if Cancel Dont Trigger Event
            OnClosePopup();
        }
        //Get DocumentFinanceYearSerieTerminal for Terminal
        public static fin_documentfinanceyearserieterminal GetDocumentFinanceYearSerieTerminal(Session pSession, Guid pDocumentType, Guid pLoggedTerminal)
        {
            DateTime currentDateTime = FrameworkUtils.CurrentDateTimeAtomic();
            fin_documentfinanceyearserieterminal documentFinanceYearSerieTerminal = null;
            fin_documentfinancetype documentFinanceType = (fin_documentfinancetype)FrameworkUtils.GetXPGuidObject(pSession, typeof(fin_documentfinancetype), pDocumentType);

            //If DocumentTypeInvoiceWayBill Replace/Override Helper Document Type InvoiceWayBill with InvoiceWay to get Invoice Serie,
            //this way we have Invoice Serie but DocumentMaster keeps DocumentFinanceType has DocumentFinanceTypeInvoiceWayBill
            //Usefull for Future Documents WayBill distinct code, ex have WayBill, ex Re-Print Documents in WayBillMode etc
            Guid documentFinanceTypeSerieGuid = (documentFinanceType.Oid == SettingsApp.XpoOidDocumentFinanceTypeInvoiceWayBill)
                ? SettingsApp.XpoOidDocumentFinanceTypeInvoice
                : documentFinanceType.Oid
            ;

            //Get Document Serie
            SortingCollection sortCollection = new SortingCollection();

            sortCollection.Add(new SortProperty("FiscalYear", DevExpress.Xpo.DB.SortingDirection.Ascending));
            CriteriaOperator criteria = CriteriaOperator.Parse(string.Format("(Disabled = 0 OR Disabled IS NULL) AND DocumentType == '{0}'", documentFinanceTypeSerieGuid.ToString()));
            ICollection      collectionDocumentFinanceSeries = pSession.GetObjects(pSession.GetClassInfo(typeof(fin_documentfinanceyearserieterminal)), criteria, sortCollection, int.MaxValue, false, true);

            foreach (fin_documentfinanceyearserieterminal item in collectionDocumentFinanceSeries)
            {
                if (currentDateTime.Year >= item.FiscalYear.FiscalYear)
                {
                    if (item.Terminal.Oid == pLoggedTerminal)
                    {
                        documentFinanceYearSerieTerminal = item;
                    }
                }
            }

            return(documentFinanceYearSerieTerminal);
        }
Exemple #10
0
        //Change and Persist TableStatus
        public void ChangeTableStatus(Guid pTableOid, TableStatus pTableStatus)
        {
            //Get Target Table
            pos_configurationplacetable xTable = (pos_configurationplacetable)FrameworkUtils.GetXPGuidObject(typeof(pos_configurationplacetable), pTableOid);

            //_log.Debug(string.Format("1 pTableStatus: [{0}] [{1}]", xTable.Designation, pTableStatus));

            if (pTableStatus == TableStatus.Reserved)
            {
                _labelTotalOrStatus.Text             = resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "global_reserved_table");
                _eventBoxTotalOrStatus.VisibleWindow = true;
                SetBackgroundColor(_colorPosTablePadTableTableStatusReservedButtonBackground, _eventBoxTotalOrStatus);
                xTable.TableStatus = TableStatus.Reserved;
                FrameworkUtils.Audit("TABLE_RESERVED", string.Format(resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "audit_message_table_reserved"), xTable.Designation));
            }
            else
            {
                _labelTotalOrStatus.Text             = string.Empty;
                _eventBoxTotalOrStatus.VisibleWindow = false;
                SetBackgroundColor(_buttonColor, _eventBoxTotalOrStatus);
                xTable.TableStatus = TableStatus.Free;
                FrameworkUtils.Audit("TABLE_UNRESERVED", string.Format(resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "audit_message_table_unreserved"), xTable.Designation));
            }
            //_log.Debug(string.Format("1 pTableStatus: [{0}] [{1}]", xTable.Designation, pTableStatus));
            //Update Status State
            _tableStatus = pTableStatus;
            //Persist in DB
            xTable.Save();
        }
Exemple #11
0
 /// <summary>
 /// Get Current DataRow Object
 /// </summary>
 /// <returns></returns>
 public override void GetDataRow()
 {
     _dataSourceRow = FrameworkUtils.GetXPGuidObject(
         GlobalFramework.SessionXpo,
         _dataSource.ObjectType,
         new Guid(Convert.ToString(_treeView.Model.GetValue(_treeIter, _modelFirstCustomFieldIndex)))
         );
 }
Exemple #12
0
        public void Insert(Guid pArticleId, decimal pQuantity, TaxSellType pTaxSellType)
        {
            FIN_Article     article         = (FIN_Article)FrameworkUtils.GetXPGuidObject(typeof(FIN_Article), pArticleId);
            PriceProperties priceProperties = FrameworkUtils.GetArticlePrice(article, pTaxSellType);

            priceProperties.Quantity = pQuantity;
            Insert(article.Oid, article.Designation, priceProperties);
        }
Exemple #13
0
        //TK016251 - FrontOffice - Criar novo documento com auto-complete para artigos e clientes
        private void SelectRecordDropDown(Entry pEntry)
        {
            PropertyInfo propertyInfo;

            //Store previousValue before update _value, to keep it
            _previousValue = _value;

            Guid articleOid = Guid.Empty;

            if (dropdownTextCollection != null && _value != null)
            {
                foreach (dynamic item in dropdownTextCollection)
                {
                    if (_value.ClassInfo.ToString() == "logicpos.datalayer.DataLayer.Xpo.erp_customer")
                    {
                        if (item.Name == pEntry.Text)
                        {
                            articleOid = item.Oid;
                        }
                    }
                    else if (_articleCode)
                    {
                        if (item.Code == pEntry.Text)
                        {
                            articleOid = item.Oid;
                        }
                    }
                    else if (item.Designation == pEntry.Text)
                    {
                        articleOid = item.Oid;
                    }
                }
            }
            if (!articleOid.Equals(Guid.Empty))
            {
                //Get Object from dialog else Mixing Sessions, Both belong to diferente Sessions
                _value       = (T1)FrameworkUtils.GetXPGuidObject(typeof(T1), articleOid);
                propertyInfo = typeof(T1).GetProperty(_fieldDisplayValue);

                object value = null;
                if (propertyInfo != null)
                {
                    // Get value from XPGuidObject Instance
                    value = propertyInfo.GetValue(_value, null);
                }
                else
                {
                    string invalidFieldMessage = string.Format("Invalid Field DisplayValue:[{0}] on XPGuidObject:[{1}]", _fieldDisplayValue, _value.GetType().Name);
                    _log.Error(invalidFieldMessage);
                    value = invalidFieldMessage;
                }

                pEntry.Text = (value != null) ? value.ToString() : resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "global_error");
                OnClosePopup();
            }
        }
Exemple #14
0
        private DataTable GetDataTable(List <GenericTreeViewColumnProperty> pColumnProperties)
        {
            //Init Local Vars
            DataTable              resultDataTable = new DataTable();
            Type                   dataTableColumnType;
            FIN_Article            article;
            OrderMain              orderMain  = GlobalFramework.SessionApp.OrdersMain[GlobalFramework.SessionApp.CurrentOrderMainOid];
            ArticleBag             articleBag = ArticleBag.TicketOrderToArticleBag(orderMain);
            POS_ConfigurationPlace configurationPlace;

            //Add Columns with specific Types From Column Properties
            foreach (GenericTreeViewColumnProperty column in pColumnProperties)
            {
                dataTableColumnType = (column.Type != null) ? column.Type : typeof(String);
                resultDataTable.Columns.Add(column.Name, dataTableColumnType);
            }

            //Init DataRow
            System.Object[] dataRow = new System.Object[pColumnProperties.Count];

            //Start Loop
            foreach (var item in articleBag)
            {
                article = (FIN_Article)FrameworkUtils.GetXPGuidObject(typeof(FIN_Article), item.Key.ArticleOid);
                if (article.Type.HavePrice)
                {
                    configurationPlace = (POS_ConfigurationPlace)FrameworkUtils.GetXPGuidObject(typeof(POS_ConfigurationPlace), item.Value.PlaceOid);

                    for (int i = 0; i < item.Value.Quantity; i++)
                    {
                        //Column Fields
                        dataRow[0]  = item.Key.ArticleOid;
                        dataRow[1]  = item.Value.Code;
                        dataRow[2]  = item.Key.Designation;
                        dataRow[3]  = item.Value.PriceFinal;
                        dataRow[4]  = item.Key.Vat;
                        dataRow[5]  = item.Key.Discount;
                        dataRow[6]  = configurationPlace.Designation;
                        dataRow[7]  = item.Key.Price;
                        dataRow[8]  = 1;
                        dataRow[9]  = item.Value.UnitMeasure;
                        dataRow[10] = item.Value.PlaceOid;
                        dataRow[11] = item.Value.TableOid;
                        dataRow[12] = item.Value.PriceType;
                        dataRow[13] = item.Value.Token1;
                        dataRow[14] = item.Value.Token2;
                        dataRow[15] = string.Empty;

                        //Add Row
                        resultDataTable.Rows.Add(dataRow);
                    }
                }
            }
            return(resultDataTable);
        }
Exemple #15
0
        //Update TreeView TotalFinal, used when we change Customer Discount, this way we update Total Final for all Articles in TreeView
        public void UpdateTotalFinal()
        {
            bool debug = false;

            try
            {
                if (_treeViewArticles.DataSource.Rows.Count > 0)
                {
                    FIN_Article article;
                    //Get Discount from Select Customer
                    decimal discountGlobal = FrameworkUtils.StringToDecimal(_pagePad2.EntryBoxCustomerDiscount.EntryValidation.Text);
                    decimal exchangeRate   = _pagePad1.EntryBoxSelectConfigurationCurrency.Value.ExchangeRate;

                    //Update DataTable Rows
                    foreach (DataRow item in _treeViewArticles.DataSource.Rows)
                    {
                        article = (FIN_Article)FrameworkUtils.GetXPGuidObject(typeof(FIN_Article), new Guid(item.ItemArray[item.Table.Columns["Oid"].Ordinal].ToString()));

                        //Calc PriceProperties
                        PriceProperties priceProperties = PriceProperties.GetPriceProperties(
                            PricePropertiesSourceMode.FromPriceNet,
                            false,                                                                                                       //PriceWithVat
                            Convert.ToDecimal(item.ItemArray[item.Table.Columns["Price"].Ordinal]),                                      //Price
                            Convert.ToDecimal(item.ItemArray[item.Table.Columns["Quantity"].Ordinal]),                                   //Quantity
                            Convert.ToDecimal(item.ItemArray[item.Table.Columns["Discount"].Ordinal]),                                   //Discount
                            discountGlobal,
                            (item.ItemArray[item.Table.Columns["ConfigurationVatRate.Value"].Ordinal] as FIN_ConfigurationVatRate).Value //VatValue
                            );

                        //Finnally Update DataSourceRow Value with calculated PriceProperties
                        if (debug)
                        {
                            _log.Debug(string.Format("#1:TotalFinal DataSourceRow: [{0}], discountGlobal: [{1}]", FrameworkUtils.DecimalToString(Convert.ToDecimal(_treeViewArticles.DataSourceRow["TotalFinal"])), FrameworkUtils.DecimalToString(discountGlobal)));
                        }
                        //Update Display Values with ExchangeRate Multiplier
                        item["PriceDisplay"] = priceProperties.PriceNet * exchangeRate;
                        item["TotalNet"]     = (priceProperties.TotalNet * exchangeRate);
                        item["TotalFinal"]   = priceProperties.TotalFinal * exchangeRate;
                        item["PriceFinal"]   = priceProperties.PriceFinal * exchangeRate;
                        if (debug)
                        {
                            _log.Debug(string.Format("#2:TotalFinal DataSourceRow: [{0}], discountGlobal: [{1}]", FrameworkUtils.DecimalToString(Convert.ToDecimal(_treeViewArticles.DataSourceRow["TotalFinal"])), FrameworkUtils.DecimalToString(discountGlobal)));
                        }
                    }
                    //Call Refresh, Recreate TreeView from Model
                    _treeViewArticles.Refresh();
                }
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message, ex);
            }
        }
Exemple #16
0
        //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
        //Helper Methods

        private void ActivateButton(TouchButtonIconWithText pButton)
        {
            //If Changed Button, Clean old Values
            if (_selectedCashDrawerButton != pButton)
            {
                _entryBoxMovementAmountMoney.EntryValidation.Text = string.Empty;
                _entryBoxMovementDescription.EntryValidation.Text = string.Empty;
            }

            //Assign _selectedMovementType
            _selectedMovementType = (pos_worksessionmovementtype)FrameworkUtils.GetXPGuidObject(GlobalFramework.SessionXpo, typeof(pos_worksessionmovementtype), pButton.CurrentButtonOid);

            //Detect Cash open
            if (_selectedMovementType.Token == "CASHDRAWER_OPEN")
            {
                _entryBoxMovementAmountMoney.EntryValidation.Text      = FrameworkUtils.DecimalToString(_totalAmountInCashDrawer);
                _entryBoxMovementAmountMoney.EntryValidation.Sensitive = false;
                //Required to disable keyboard button
                _entryBoxMovementAmountMoney.ButtonKeyBoard.Sensitive = false;
                _entryBoxMovementAmountMoney.EntryValidation.Required = false;
                _entryBoxMovementAmountMoney.EntryValidation.Rule     = null;
            }
            else
            {
                _entryBoxMovementAmountMoney.EntryValidation.Required  = true;
                _entryBoxMovementAmountMoney.EntryValidation.Rule      = SettingsApp.RegexDecimalGreaterEqualThanZero;
                _entryBoxMovementAmountMoney.EntryValidation.Sensitive = true;
                //Required to enable keyboard button
                _entryBoxMovementAmountMoney.ButtonKeyBoard.Sensitive = true;
            }

            //Apply Requires Description for MONEY_IN and MONEY_OUT
            _entryBoxMovementDescription.EntryValidation.Required = (_selectedMovementType.Token == "CASHDRAWER_IN" || _selectedMovementType.Token == "CASHDRAWER_OUT");
            _entryBoxMovementDescription.EntryValidation.Validate();

            //Now we can UnToggle Old Selected Button
            if (_selectedCashDrawerButton != null)
            {
                //Toggle Button Off
                _selectedCashDrawerButton.ModifyBg(StateType.Normal, Utils.ColorToGdkColor(_colorBaseDialogDefaultButtonBackground));
            }

            //In the End Change reference to new Seleted Button
            _selectedCashDrawerButton = pButton;
            //Toggle Button On
            _selectedCashDrawerButton.ModifyBg(StateType.Normal, Utils.ColorToGdkColor(Utils.Lighten(_colorBaseDialogDefaultButtonBackground, 0.50f)));

            //Validate
            ValidateDialog();
        }
 public void DeleteLoggedUsers()
 {
     try
     {
         foreach (Guid item in GlobalFramework.SessionApp.LoggedUsers.Keys)
         {
             sys_userdetail user = (sys_userdetail)FrameworkUtils.GetXPGuidObject(typeof(sys_userdetail), item);
             FrameworkUtils.Audit("USER_LOGOUT", string.Format(resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "audit_message_used_forced_logout"), user.Name));
         }
         GlobalFramework.SessionApp.LoggedUsers.Clear();
     }
     catch (Exception ex)
     {
         _log.Error(ex.Message, ex);
     }
 }
Exemple #18
0
 public void DeleteLoggedUsers()
 {
     try
     {
         foreach (Guid item in GlobalFramework.SessionApp.LoggedUsers.Keys)
         {
             SYS_UserDetail user = (SYS_UserDetail)FrameworkUtils.GetXPGuidObject(typeof(SYS_UserDetail), item);
             FrameworkUtils.Audit("USER_LOGOUT", string.Format(Resx.audit_message_used_forced_logout, user.Name));
         }
         GlobalFramework.SessionApp.LoggedUsers.Clear();
     }
     catch (Exception ex)
     {
         _log.Error(ex.Message, ex);
     }
 }
Exemple #19
0
 //Constructor without Json.NET Load, With Defaults
 public OrderMainTable(Guid pOrderMainOid, Guid pTableOid)
 {
     _orderMainOid = pOrderMainOid;
     _oid          = pTableOid;
     try
     {
         POS_ConfigurationPlaceTable table = (POS_ConfigurationPlaceTable)FrameworkUtils.GetXPGuidObject(typeof(POS_ConfigurationPlaceTable), pTableOid);
         _name = table.Designation;
         //Enum is not Zero Indexed
         _priceType = (PriceType)table.Place.PriceType.EnumValue;
         _placeId   = table.Place.Oid;
     }
     catch (Exception ex)
     {
         _log.Error(ex.Message, ex);
     }
 }
Exemple #20
0
        /// <summary>
        /// <para>
        /// Method responsible for check all items from Current Order (from temp file).
        /// </para>
        /// For Parking Ticket purposes, it is not allowed to have 2 units of same article,
        /// therefore, after adding a new article in Current Order and finishing this order,
        /// all items from the same will be persisted in data base, merging temp order and database order.
        /// <para>
        /// It is necessary to check for duplicates, removing it from database order.
        /// </para>
        /// </summary>
        /// <remarks>Please see TK013134 for further details</remarks>
        /// <param name="session"></param>
        public void CheckForDuplicatedArticleInArticleBag(Session session)
        {
            _log.Debug("OrderMain.CheckForDuplicatedArticleInArticleBag(Session session)");

            Session _sessionXpo = session;
            fin_documentordermain xOrderMain = (fin_documentordermain)FrameworkUtils.GetXPGuidObject(_sessionXpo, typeof(fin_documentordermain), _persistentOid);

            //Get current Working Order from SessionApp
            OrderMain   currentOrderMain   = GlobalFramework.SessionApp.OrdersMain[GlobalFramework.SessionApp.CurrentOrderMainOid];
            OrderTicket currentOrderTicket = currentOrderMain.OrderTickets[currentOrderMain.CurrentTicketId];

            OrderDetailLine[] orderDetailsLines = currentOrderTicket.OrderDetails.Lines.ToArray();

            if (xOrderMain != null)
            {
                /* iterates over current Order ticket list */
                foreach (OrderDetailLine line in orderDetailsLines)
                {
                    string currentDesignation = line.Designation;

                    /* iterates over main Order list */
                    foreach (var xOrderMainTicket in xOrderMain.OrderTicket)
                    {
                        xOrderMainTicket.OrderDetail.Load();

                        /* iterates over main Order ticket list */
                        foreach (var xOrderMainTicketOrderDetail in xOrderMainTicket.OrderDetail)
                        {
                            {
                                fin_documentorderdetail aa = xOrderMainTicket.OrderDetail[0];

                                /* When order already has the parking ticket, remove and break */
                                if (xOrderMainTicketOrderDetail.Designation.Equals(currentDesignation))
                                {
                                    currentOrderTicket.OrderDetails.Lines.Remove(line);
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
Exemple #21
0
        private void UpdateTouchButtonSplitPaymentLabels(TouchButtonSplitPayment touchButtonSplitPayment)
        {
            bool debug = false;

            try
            {
                string labelPaymentDetails = string.Empty;
                ProcessFinanceDocumentParameter processFinanceDocumentParameter = touchButtonSplitPayment.ProcessFinanceDocumentParameter;

                if (processFinanceDocumentParameter != null)
                {
                    if (debug)
                    {
                        _log.Debug(Environment.NewLine);
                    }
                    foreach (var item in touchButtonSplitPayment.ArticleBag)
                    {
                        if (debug)
                        {
                            _log.Debug(string.Format("\t[{0}],[{1}],[{2}]", item.Key.Designation, item.Value.Quantity, item.Value.TotalFinal));
                        }
                    }

                    erp_customer customer = (erp_customer)FrameworkUtils.GetXPGuidObject(typeof(erp_customer), processFinanceDocumentParameter.Customer);
                    fin_configurationpaymentmethod paymentMethod = (fin_configurationpaymentmethod)FrameworkUtils.GetXPGuidObject(typeof(fin_configurationpaymentmethod), processFinanceDocumentParameter.PaymentMethod);
                    cfg_configurationcurrency      currency      = (cfg_configurationcurrency)FrameworkUtils.GetXPGuidObject(typeof(cfg_configurationcurrency), processFinanceDocumentParameter.Currency);
                    // Compose labelPaymentDetails
                    string totalFinal    = FrameworkUtils.DecimalToStringCurrency(processFinanceDocumentParameter.ArticleBag.TotalFinal, currency.Acronym);
                    string totalDelivery = FrameworkUtils.DecimalToStringCurrency(processFinanceDocumentParameter.TotalDelivery, currency.Acronym);
                    string totalChange   = FrameworkUtils.DecimalToStringCurrency(processFinanceDocumentParameter.TotalChange, currency.Acronym);
                    string moneyExtra    = (paymentMethod.Token.Equals("MONEY")) ? $" : ({totalDelivery}/{totalChange})" : string.Empty;
                    // Override default labelPaymentDetails
                    labelPaymentDetails = $"{customer.Name} : {paymentMethod.Designation} : {totalFinal}{moneyExtra}";
                }
                // Assign to button Reference
                touchButtonSplitPayment.LabelPaymentDetails.Text = labelPaymentDetails;
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message, ex);
            }
        }
Exemple #22
0
        void _tablePadUsers_Clicked(object sender, EventArgs e)
        {
            TouchButtonBase button = (TouchButtonBase)sender;

            //Assign CurrentId to TablePad.CurrentId, to Know last Clicked Button Id
            _tablePadUsers.SelectedButtonOid = button.CurrentButtonOid;
            //To be Used in Dialog Result
            _selectedUserDetail = (SYS_UserDetail)FrameworkUtils.GetXPGuidObject(typeof(SYS_UserDetail), button.CurrentButtonOid);

            if (_selectedUserDetail.PasswordReset)
            {
                //_log.Debug(string.Format("Name: [{0}], PasswordReset: [{1}]", _selectedUserDetail.Name, _selectedUserDetail.PasswordReset));
                Utils.ShowMessageTouch(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, Resx.global_information,
                                       string.Format(Resx.dialog_message_user_request_change_password, _selectedUserDetail.Name, SettingsApp.DefaultValueUserDetailAccessPin)
                                       );
            }

            //Send Response to Replace the Old Ok Button
            Respond(ResponseType.Ok);
        }
Exemple #23
0
        //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

        // Generic Method to Generate XPOEntryBoxSelectRecordValidation
        private XPOEntryBoxSelectRecordValidation <T1, T2> SelectionBoxFactory <T1, T2>(string labelText, string fieldDisplayValue = "Designation", string extraFilter = "")
            where T1 : XPGuidObject, new()
            where T2 : GenericTreeViewXPO, new()
        {
            XPOEntryBoxSelectRecordValidation <T1, T2> resultObject;

            // Helper to debug extraFilter
            //if (!string.IsNullOrEmpty(extraFilter))
            //{
            //    _log.Debug("BREAK");
            //}
            T1 defaultValue = (T1)FrameworkUtils.GetXPGuidObject(GlobalFramework.SessionXpo, typeof(T1), SettingsApp.XpoOidUndefinedRecord);
            CriteriaOperator criteriaOperator = CriteriaOperator.Parse(string.Format("((Disabled IS NULL OR Disabled  <> 1) OR (Oid = '{0}')){1}", SettingsApp.XpoOidUndefinedRecord, extraFilter));

            resultObject      = new XPOEntryBoxSelectRecordValidation <T1, T2>(this, labelText, fieldDisplayValue, "Oid", (defaultValue as T1), criteriaOperator, SettingsApp.RegexGuid, true);
            resultObject.Name = typeof(T1).Name;
            resultObject.EntryValidation.IsEditable = true;
            resultObject.ClosePopup += _entryBoxSelectShared_ClosePopup;

            return(resultObject);
        }
Exemple #24
0
        private bool PersistFinanceDocuments()
        {
            bool debug        = false;
            int  padLeftChars = 10;

            try
            {
                int i = 0;
                foreach (TouchButtonSplitPayment item in _splitPaymentButtons)
                {
                    i++;
                    // If have
                    if (item.ProcessFinanceDocumentParameter != null)
                    {
                        if (debug)
                        {
                            _log.Debug(string.Format("TotalFinal: [#{0}]:[{1}]", i,
                                                     FrameworkUtils.DecimalToStringCurrency(item.ProcessFinanceDocumentParameter.ArticleBag.TotalFinal).PadLeft(padLeftChars, ' ')
                                                     ));
                        }

                        // PersistFinanceDocument
                        item.DocumentFinanceMaster = FrameworkCalls.PersistFinanceDocument(this, item.ProcessFinanceDocumentParameter);
                        //Update Display
                        if (item.DocumentFinanceMaster != null)
                        {
                            fin_configurationpaymentmethod paymentMethod = (fin_configurationpaymentmethod)FrameworkUtils.GetXPGuidObject(typeof(fin_configurationpaymentmethod), item.ProcessFinanceDocumentParameter.PaymentMethod);
                            if (GlobalApp.UsbDisplay != null)
                            {
                                GlobalApp.UsbDisplay.ShowPayment(paymentMethod.Designation, item.ProcessFinanceDocumentParameter.TotalDelivery, item.ProcessFinanceDocumentParameter.TotalChange);
                            }
                        }
                    }
                }

                //If has Working Order
                if (
                    GlobalFramework.SessionApp.OrdersMain != null &&
                    GlobalFramework.SessionApp.CurrentOrderMainOid != null &&
                    GlobalFramework.SessionApp.OrdersMain.ContainsKey(GlobalFramework.SessionApp.CurrentOrderMainOid)
                    )
                {
                    // Get Current working orderMain
                    OrderMain currentOrderMain = GlobalFramework.SessionApp.OrdersMain[GlobalFramework.SessionApp.CurrentOrderMainOid];
                    if (debug)
                    {
                        _log.Debug(string.Format("Working on currentOrderMain.PersistentOid: [{0}]", currentOrderMain.PersistentOid));
                    }
                    //Get OrderDetail
                    OrderDetail currentOrderDetails = currentOrderMain.OrderTickets[currentOrderMain.CurrentTicketId].OrderDetails;

                    // Get configurationPlace to get Tax
                    pos_configurationplace configurationPlace = (pos_configurationplace)GlobalFramework.SessionXpo.GetObjectByKey(typeof(pos_configurationplace), currentOrderMain.Table.PlaceId);
                }

                return(true);
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message, ex);
                return(false);
            }
        }
Exemple #25
0
        private void CalculateTotalPerSplit(ArticleBag articleBag, int numberOfSplits)
        {
            bool debug = false;

            // Calculate final Total Pay per Split
            _totalPerSplit = articleBag.TotalFinal / numberOfSplits;

            try
            {
                // Always Init ArticleBags
                foreach (TouchButtonSplitPayment item in _splitPaymentButtons)
                {
                    item.ArticleBag = new ArticleBag();
                }

                // Init Object to Use priceTax on above Loop
                //Get Place Objects to extract TaxSellType Normal|TakeWay, Place, Tables etc
                OrderMain currentOrderMain = GlobalFramework.SessionApp.OrdersMain[GlobalFramework.SessionApp.CurrentOrderMainOid];
                pos_configurationplace configurationPlace = (pos_configurationplace)GlobalFramework.SessionXpo.GetObjectByKey(typeof(pos_configurationplace), currentOrderMain.Table.PlaceId);

                // Loop articleBag, and Add the quantity for Each Split (Total Article Quantity / numberOfSplits)
                foreach (var article in articleBag)
                {
                    // Default quantity to add to all Splitters, last one gets the extra Remains ex 0,0000000000001
                    decimal articleQuantity = (article.Value.Quantity / numberOfSplits);
                    // Store Remain Quantity
                    decimal articleQuantityRemain = article.Value.Quantity;
                    // Check if Total is equal to Origin
                    decimal articleQuantityCheck       = 0.0m;
                    decimal articleQuantityCheckModulo = 0.0m;
                    // Reset t
                    int t = 0;
                    foreach (TouchButtonSplitPayment touchButtonSplitPayment in _splitPaymentButtons)
                    {
                        t++;
                        // Discount articleQuantityRemain
                        articleQuantityRemain = articleQuantityRemain - articleQuantity;
                        if (t.Equals(_splitPaymentButtons.Count))
                        {
                            // Override Default split Quantity, adding extra Remain
                            articleQuantity += articleQuantityRemain;
                        }

                        // Add to articleQuantityCheck
                        articleQuantityCheck += articleQuantity;
                        // Modulo
                        articleQuantityCheckModulo = article.Value.Quantity % articleQuantityCheck;

                        if (debug)
                        {
                            _log.Debug(string.Format("#{0} Designation: [{1}], PriceFinal: [{2}], Quantity: [{3}]:[{4}]:[{5}]:[{6}]:[{7}]",
                                                     t, article.Key.Designation, article.Value.PriceFinal, article.Value.Quantity, articleQuantity, articleQuantityRemain, articleQuantityCheck, articleQuantityCheckModulo)
                                       );
                        }

                        // ArticleBagKey
                        ArticleBagKey articleBagKey = new ArticleBagKey(
                            article.Key.ArticleOid,
                            article.Key.Designation,
                            article.Key.Price,
                            article.Key.Discount,
                            article.Key.Vat
                            );
                        //Detect and Assign VatExemptionReason to ArticleBak Key
                        if (article.Key.VatExemptionReasonOid != null && article.Key.VatExemptionReasonOid != Guid.Empty)
                        {
                            articleBagKey.VatExemptionReasonOid = article.Key.VatExemptionReasonOid;
                        }
                        // ArticleBagProperties
                        ArticleBagProperties articleBagProps = articleBagProps = new ArticleBagProperties(
                            configurationPlace.Oid,
                            currentOrderMain.Table.Oid,
                            (PriceType)configurationPlace.PriceType.EnumValue,
                            article.Value.Code,
                            articleQuantity,
                            article.Value.UnitMeasure
                            );

                        // Add to ArticleBag
                        touchButtonSplitPayment.ArticleBag.Add(articleBagKey, articleBagProps);
                    }
                }

                // After have all splitPaymentButtons ArticleBags (End of arraySplit.Count Loop)
                foreach (TouchButtonSplitPayment item in _splitPaymentButtons)
                {
                    // Require to Update ProcessFinanceDocumentParameter, like when we Close Payment Window, BEFORE UpdateTouchButtonSplitPaymentLabels
                    // This is to Update UI when we Add/Remove Splits, else Already filled Payments dont Update
                    // Only change ArticleBag
                    if (item.ProcessFinanceDocumentParameter != null)
                    {
                        fin_configurationpaymentmethod paymentMethod = (fin_configurationpaymentmethod)FrameworkUtils.GetXPGuidObject(typeof(fin_configurationpaymentmethod), item.ProcessFinanceDocumentParameter.PaymentMethod);
                        decimal totalDelivery = (paymentMethod.Token.Equals("MONEY"))
                            ? item.ProcessFinanceDocumentParameter.TotalDelivery
                            : item.ArticleBag.TotalFinal;

                        item.ProcessFinanceDocumentParameter = new ProcessFinanceDocumentParameter(
                            item.ProcessFinanceDocumentParameter.DocumentType, item.ArticleBag
                            )
                        {
                            PaymentMethod    = item.ProcessFinanceDocumentParameter.PaymentMethod,
                            PaymentCondition = item.ProcessFinanceDocumentParameter.PaymentCondition,
                            Customer         = item.ProcessFinanceDocumentParameter.Customer,
                            TotalDelivery    = totalDelivery,
                            // Require to Recalculate TotalChange
                            TotalChange = totalDelivery - item.ArticleBag.TotalFinal
                        };
                    }

                    // Always Update all Buttons, with and without ProcessFinanceDocumentParameter
                    UpdateTouchButtonSplitPaymentLabels(item);

                    // Update Window Title
                    //if (WindowTitle != null) WindowTitle = string.Format(resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "window_title_dialog_split_payment, numberOfSplits, FrameworkUtils.DecimalToStringCurrency(totalFinal));
                    if (WindowTitle != null)
                    {
                        WindowTitle = string.Format(resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "window_title_dialog_split_payment"), numberOfSplits, FrameworkUtils.DecimalToStringCurrency(_totalPerSplit));
                    }
                }
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message, ex);
            }
        }
Exemple #26
0
        /// <summary>
        /// Get Total of All Persistent Tickets (Without PartialPayments), Used to Update StatusBar, And Update OrderMain main Object
        /// </summary>
        public void UpdateTotals()
        {
            try
            {
                /* METHOD #2 : From Article Bag
                 * //OrderMain orderMain = GlobalFramework.SessionApp.OrdersMain[GlobalFramework.SessionApp.CurrentOrderMainOid];
                 */
                ArticleBag articleBag = ArticleBag.TicketOrderToArticleBag(this);
                articleBag.UpdateTotals();
                //sqlTotalTickets
                string sqlTotalTickets = string.Format(@"
                    SELECT 
                        COUNT(*) AS TotalTickets    
                    FROM 
                        fin_documentorderticket
                    WHERE 
                        OrderMain = '{0}'
                ;"
                                                       , this.PersistentOid
                                                       );
                var totalTickets = GlobalFramework.SessionXpo.ExecuteScalar(sqlTotalTickets);

                //Assign Totals
                _globalTotalTickets  = (totalTickets != null) ? Convert.ToInt32(totalTickets) : 0;
                _globalTotalGross    = articleBag.TotalFinal;
                _globalTotalDiscount = articleBag.TotalDiscount;
                _globalTotalTax      = articleBag.TotalTax;
                _globalTotalFinal    = articleBag.TotalFinal;
                _globalTotalQuantity = articleBag.TotalQuantity;
                //Persist Final TotalOpen
                pos_configurationplacetable currentTable = (pos_configurationplacetable)FrameworkUtils.GetXPGuidObject(typeof(pos_configurationplacetable), _table.Oid);

                if (currentTable != null)
                {
                    //Required Reload, after ProcessFinanceDocument uowSession, else we get cached object, and apply changes to old object, ex we get a OpenedTable vs a ClosedTable by uowSession
                    currentTable.Reload();
                    currentTable.TotalOpen = _globalTotalFinal;
                    currentTable.Save();
                }
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message, ex);
            }

            /* METHOD 3 : When we Change table it dont Update GlobalDiscounts
             * //Get Total Order (Payed/Invoiced and NonPayed)
             * string sqlTotalViewOrders = string.Format(@"
             * SELECT
             *  SUM(ddTotalGross) AS TotalGross,
             *  SUM(ddTotalDiscount) AS TotalDiscount,
             *  SUM(ddTotalTax) AS TotalTax,
             *  SUM(ddTotalFinal) AS TotalFinal,
             *  SUM(ddQuantity) AS TotalQuantity
             * FROM
             *  view_orders
             * WHERE
             *  dmOid = '{0}'
             * ORDER BY
             *  dtTicketId,ddOrd;
             * ;"
             * , this.PersistentOid
             * );
             *
             * string sqlTotalViewDocumentFinance = string.Format(@"
             * SELECT
             *    SUM(fdTotalGross) AS TotalGross,
             *  SUM(fdTotalDiscount) AS TotalDiscount,
             *  SUM(fdTotalTax) AS TotalTax,
             *  SUM(fdTotalFinal) AS TotalFinal,
             *  SUM(fdQuantity) AS TotalQuantity
             * FROM
             *    view_documentfinance
             * WHERE
             *    fmSourceOrderMain = '{0}'
             * ;"
             * , this.PersistentOid
             * );
             *
             * string sqlTotalTickets = string.Format(@"
             * SELECT
             *  COUNT(*) AS TotalTickets
             * FROM
             *  fin_documentorderticket
             * WHERE
             *  OrderMain = '{0}'
             * ;"
             * , this.PersistentOid
             * );
             *
             * try
             * {
             * XPSelectData sdTotalViewOrders = FrameworkUtils.GetSelectedDataFromQuery(sqlTotalViewOrders);
             * XPSelectData sdTotalViewDocumentFinance = FrameworkUtils.GetSelectedDataFromQuery(sqlTotalViewDocumentFinance);
             *
             * if (sdTotalViewOrders.Data.Length > 0 && sdTotalViewDocumentFinance.Data.Length > 0)
             * {
             *  //TotalGross
             *  _globalTotalGross =
             *    Convert.ToDecimal(sdTotalViewOrders.Data[0].Values[sdTotalViewOrders.GetFieldIndex("TotalGross")]) -
             *    Convert.ToDecimal(sdTotalViewDocumentFinance.Data[0].Values[sdTotalViewOrders.GetFieldIndex("TotalGross")]);
             *  //TotalDiscount
             *  _globalTotalDiscount =
             *    Convert.ToDecimal(sdTotalViewOrders.Data[0].Values[sdTotalViewOrders.GetFieldIndex("TotalDiscount")]) -
             *    Convert.ToDecimal(sdTotalViewDocumentFinance.Data[0].Values[sdTotalViewOrders.GetFieldIndex("TotalDiscount")]);
             *  //TotalTax
             *  _globalTotalTax =
             *    Convert.ToDecimal(sdTotalViewOrders.Data[0].Values[sdTotalViewOrders.GetFieldIndex("TotalTax")]) -
             *    Convert.ToDecimal(sdTotalViewDocumentFinance.Data[0].Values[sdTotalViewOrders.GetFieldIndex("TotalTax")]);
             *  //TotalFinal
             *  _globalTotalFinal =
             *    Convert.ToDecimal(sdTotalViewOrders.Data[0].Values[sdTotalViewOrders.GetFieldIndex("TotalFinal")]) -
             *    Convert.ToDecimal(sdTotalViewDocumentFinance.Data[0].Values[sdTotalViewOrders.GetFieldIndex("TotalFinal")]);
             *  //TotalQuantity
             *  _globalTotalQuantity =
             *    Convert.ToDecimal(sdTotalViewOrders.Data[0].Values[sdTotalViewOrders.GetFieldIndex("TotalQuantity")]) -
             *    Convert.ToDecimal(sdTotalViewDocumentFinance.Data[0].Values[sdTotalViewOrders.GetFieldIndex("TotalQuantity")]);
             * }
             *
             * //sqlTotalTickets
             * var totalTickets = GlobalFramework.SessionXpo.ExecuteScalar(sqlTotalTickets);
             * _globalTotalTickets = (totalTickets != null) ? Convert.ToInt32(totalTickets) : 0;
             *
             * //Persist Final TotalOpen
             * ConfigurationPlaceTable currentTable = (ConfigurationPlaceTable)FrameworkUtils.GetXPGuidObjectFromSession(typeof(ConfigurationPlaceTable), _table.Oid);
             * currentTable.TotalOpen = _globalTotalFinal;
             * currentTable.Save();
             * }
             * catch (Exception ex)
             * {
             * _log.Error(ex.Message, ex);
             * }
             */

            /* OLD DEPRECATED METHOD #1 : Bugged In Orders with PartialPayments
             * bool debug = false;
             *
             * //Settings
             *
             * //Always Reset Totals, With Persistent and Non Persistent Orders
             * _globalNumOfTickets = 0;
             * _globalTotalGross = 0;
             * _globalTotalDiscount = 0;
             * _globalTotalTax = 0;
             * _globalTotalFinal = 0;
             *
             * //Get Current _persistentOid and _orderStatus from Database
             * _persistentOid = GetOpenTableFieldValueGuid(_table.Oid, "Oid");
             * _orderStatus = (OrderStatus)GetOpenTableFieldValue(_table.Oid, "OrderStatus");
             *
             * if (_persistentOid != Guid.Empty)
             * {
             * CriteriaOperator binaryOperator = new BinaryOperator("OrderMain", _persistentOid, BinaryOperatorType.Equal);
             * XPCollection _xpcDocumentOrderTicket = new XPCollection(GlobalFramework.SessionXpo, typeof(DocumentOrderTicket), binaryOperator);
             *
             * //Required to ByPass Cache
             * _xpcDocumentOrderTicket.Reload();
             *
             * //Process DocumentOrderTickets Totals
             * if (_xpcDocumentOrderTicket.Count > 0)
             * {
             *  foreach (DocumentOrderTicket ticket in _xpcDocumentOrderTicket)
             *  {
             *    //Required to ByPass Cache
             *    ticket.OrderDetail.Reload();
             *
             *    //Increase Ticket
             *    _globalNumOfTickets++;
             *
             *    foreach (DocumentOrderDetail line in ticket.OrderDetail)
             *    {
             *      _globalTotalGross += line.TotalGross;
             *      _globalTotalDiscount += line.TotalDiscount;
             *      _globalTotalTax += line.TotalTax;
             *      _globalTotalFinal += line.TotalFinal;
             *      if (debug) _log.Debug(string.Format("{0}\t{1}\t{2}\t{3}\t{4}\t{5}", line.Article.Oid, line.Designation, line.Price, line.Quantity, line.Discount, line.Vat));
             *    }
             *    _globalLastUser = ticket.UpdatedBy;
             *    _globalLastTerminal = ticket.UpdatedWhere;
             *  }
             * }
             *
             * //Process PartialPayed Items and Discount its Totals
             * CriteriaOperator binaryOperatorDocumentFinanceMaster = new BinaryOperator("SourceOrderMain", _persistentOid, BinaryOperatorType.Equal);
             * XPCollection _xpcDocumentFinanceMaster = new XPCollection(GlobalFramework.SessionXpo, typeof(DocumentFinanceMaster), binaryOperatorDocumentFinanceMaster);
             * if (_xpcDocumentFinanceMaster.Count > 0)
             * {
             *  foreach (DocumentFinanceMaster master in _xpcDocumentFinanceMaster)
             *  {
             *    //SEARCH#001 - Change here and in Other Search, to SYNC RESULTS
             *    //Only Discount items from ArticleBag if is NOT a TableConsult, in TableConsult keep Full ArticleBag From OrderMain
             *    if (master.DocumentType.Oid != new Guid(xpoOidDocumentFinanceTypeConferenceDocument))
             *    {
             *      foreach (DocumentFinanceDetail line in master.DocumentDetail)
             *      {
             *        _globalTotalGross -= line.TotalGross;
             *        _globalTotalDiscount -= line.TotalDiscount;
             *        _globalTotalTax -= line.TotalTax;
             *        _globalTotalFinal -= line.TotalFinal;
             *      }
             *    }
             *  }
             * }
             *
             * //Persist Final TotalOpen
             * ConfigurationPlaceTable currentTable = (ConfigurationPlaceTable)FrameworkUtils.GetXPGuidObjectFromSession(typeof(ConfigurationPlaceTable), _table.Oid);
             * currentTable.TotalOpen = _globalTotalFinal;
             * currentTable.Save();
             *
             * //Debug
             * //_log.Debug(string.Format("GetGlobalOrderSummary(): _table.Id:[{0}], _table.Name:[{1}]", _table.Id, _table.Name));
             * //_log.Debug(string.Format("GetGlobalOrderSummary(): _globalTotalGross [{0}]", _globalTotalGross));
             * //_log.Debug(string.Format("GetGlobalOrderSummary(): _globalTotalTax [{0}]", _globalTotalTax));
             * //_log.Debug(string.Format("GetGlobalOrderSummary(): _globalTotalDiscount [{0}]", _globalTotalDiscount));
             * //_log.Debug(string.Format("GetGlobalOrderSummary(): _globalTotalFinal [{0}]", _globalTotalFinal));
             * //_log.Debug(string.Format("GetGlobalOrderSummary(): _globalNumOfTickets [{0}]", _globalNumOfTickets));
             * //if (_globalLastUser != null) _log.Debug(string.Format("GetGlobalOrderSummary(): _globalLastUser.Name [{0}]", _globalLastUser.Name));
             * //if (_globalLastTerminal != null) _log.Debug(string.Format("GetGlobalOrderSummary(): _globalLastTerminal.Designation [{0}]", _globalLastTerminal.Designation));
             * }
             */
        }
Exemple #27
0
        public fin_documentorderticket FinishOrder(Session pSession, bool pPrintTicket, bool pTicketDrecrease)
        {
            //Local Vars
            DateTime currentDateTime = DateTime.Now;
            fin_documentordermain xOrderMain;
            Session _sessionXpo = pSession;
            bool    isInUOW     = (_sessionXpo.GetType() == typeof(UnitOfWork));
            //Result
            fin_documentorderticket xOrderTicket = null;

            //Get current Working Order from SessionApp
            OrderMain   currentOrderMain   = GlobalFramework.SessionApp.OrdersMain[GlobalFramework.SessionApp.CurrentOrderMainOid];
            OrderTicket currentOrderTicket = currentOrderMain.OrderTickets[currentOrderMain.CurrentTicketId];

            //Get Place Object to extract TaxSellType Normal|TakeWay
            pos_configurationplace configurationPlace = (pos_configurationplace)GlobalFramework.SessionXpo.GetObjectByKey(typeof(pos_configurationplace), currentOrderMain.Table.PlaceId);
            //Use VatDirectSelling if in Retail or in TakeWay mode
            TaxSellType taxSellType = (configurationPlace.MovementType.VatDirectSelling || SettingsApp.AppMode == AppOperationMode.Retail) ? TaxSellType.TakeAway : TaxSellType.Normal;

            //Open Table on First Finish OrderTicket
            pos_configurationplacetable xTable = (pos_configurationplacetable)FrameworkUtils.GetXPGuidObject(_sessionXpo, typeof(pos_configurationplacetable), _table.Oid);

            xTable.Reload();
            if (xTable.TableStatus != TableStatus.Open)
            {
                xTable.TableStatus = TableStatus.Open;
                FrameworkUtils.Audit("TABLE_OPEN", string.Format(resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "audit_message_table_open"), xTable.Designation));
                xTable.DateTableOpen = FrameworkUtils.CurrentDateTimeAtomic();
                if (!isInUOW)
                {
                    xTable.Save();
                }
            }

            //Get Current _persistentOid and _from Database
            _persistentOid = GetOpenTableFieldValueGuid(_table.Oid, "Oid");
            _orderStatus   = (OrderStatus)GetOpenTableFieldValue(_table.Oid, "OrderStatus");
            _updatedAt     = FrameworkUtils.CurrentDateTimeAtomic();
            Guid orderTicketOid = Guid.Empty;

            //Insert
            if (_persistentOid == Guid.Empty)
            {
                //OrderMain
                xOrderMain = new fin_documentordermain(_sessionXpo)
                {
                    //Always assign New date to Persistent Date
                    DateStart   = currentDateTime,//currentOrderMain.DateStart,
                    OrderStatus = OrderStatus.Open,
                    PlaceTable  = xTable,
                    UpdatedAt   = FrameworkUtils.CurrentDateTimeAtomic()
                };
                if (!isInUOW)
                {
                    xOrderMain.Save();
                }
                //After Save, Get Oid
                _persistentOid = xOrderMain.Oid;
                //Change to Open Status
                _orderStatus = OrderStatus.Open;
            }
            //Update
            else
            {
                xOrderMain = (fin_documentordermain)FrameworkUtils.GetXPGuidObject(_sessionXpo, typeof(fin_documentordermain), _persistentOid);
                if (xOrderMain.PlaceTable != xTable)
                {
                    xOrderMain.PlaceTable = xTable;
                }
                //Force Changes in Record, else UpdatedAt dont Update
                xOrderMain.UpdatedAt = FrameworkUtils.CurrentDateTimeAtomic();
                //TODO: Check if User was Automatically Updated
                //if (xOrderMain.UpdatedBy != GlobalFramework.LoggedUser) xOrderMain.UpdatedBy = GlobalFramework.LoggedUser;
                if (!isInUOW)
                {
                    xOrderMain.Save();
                }
            }

            //Create OrderTicket
            //if (pTicketDrecrease)
            //{
            //var sql = string.Format(@"SELECT * FROM fin_documentorderticket WHERE TicketId = '{0}' AND OrderMain = '{1}';", currentOrderMain.CurrentTicketId, currentOrderMain.PersistentOid);
            //_log.Debug(string.Format("sql: [{0}]", sql));
            string sql = string.Format(@"SELECT Oid FROM fin_documentorderticket WHERE OrderMain = '{0}' AND TicketId = '{1}';", currentOrderMain.PersistentOid, currentOrderMain.CurrentTicketId);

            //_log.Debug(string.Format("sql: [{0}]", sql));
            orderTicketOid = FrameworkUtils.GetGuidFromQuery(sql);
            xOrderTicket   = (fin_documentorderticket)GlobalFramework.SessionXpo.GetObjectByKey(typeof(fin_documentorderticket), orderTicketOid);

            //xOrderTicket = (fin_documentorderticket)FrameworkUtils.GetXPGuidObject(_sessionXpo, typeof(fin_documentorderticket), currentOrderMain._persistentOid);
            if (xOrderTicket != null)
            {
                xOrderTicket.TicketId   = currentOrderMain.CurrentTicketId;
                xOrderTicket.DateStart  = currentOrderTicket.DateStart;
                xOrderTicket.PriceType  = currentOrderTicket.PriceType;
                xOrderTicket.Discount   = xTable.Discount;
                xOrderTicket.OrderMain  = xOrderMain;
                xOrderTicket.PlaceTable = xTable;
                xOrderTicket.UpdatedAt  = FrameworkUtils.CurrentDateTimeAtomic();
                if (!isInUOW)
                {
                    xOrderTicket.Save();
                }
            }

            //}
            else
            {
                xOrderTicket = new fin_documentorderticket(_sessionXpo)
                {
                    TicketId   = currentOrderMain.CurrentTicketId,
                    DateStart  = currentOrderTicket.DateStart,
                    PriceType  = currentOrderTicket.PriceType,
                    Discount   = xTable.Discount,
                    OrderMain  = xOrderMain,
                    PlaceTable = xTable
                };
                if (!isInUOW)
                {
                    xOrderTicket.Save();
                }
            }


            //Create OrderDetail
            fin_documentorderdetail xOrderDetailLine;
            fin_article             xArticle;
            uint    itemOrd  = 0;
            decimal priceTax = 0;

            foreach (OrderDetailLine line in currentOrderTicket.OrderDetails.Lines)
            {
                //Use Order in print tickets etc
                itemOrd++;
                xArticle = (fin_article)FrameworkUtils.GetXPGuidObject(_sessionXpo, typeof(fin_article), line.ArticleOid);
                //Get PriceTax from TaxSellType
                priceTax = (taxSellType == TaxSellType.Normal) ? xArticle.VatOnTable.Value : xArticle.VatDirectSelling.Value;
                //Edit/cancel orders lindote 10/07/2020
                //Get order ticket Oid from DB
                string sql3 = string.Format(@"SELECT Oid FROM fin_documentorderticket WHERE OrderMain = '{0}' AND TicketId = '{1}';", currentOrderMain.PersistentOid, currentOrderMain.CurrentTicketId);
                orderTicketOid = FrameworkUtils.GetGuidFromQuery(sql3);

                //Get order detail Oid from DB
                string sql4 = string.Format(@"SELECT Oid FROM fin_documentorderdetail WHERE OrderTicket = '{0}' AND Article = '{1}' AND Price = '{2}'  AND TotalDiscount = '{3}'  AND Vat = '{4}';",
                                            orderTicketOid, line.ArticleOid, line.Properties.PriceNet.ToString().Replace(",", "."),
                                            line.Properties.TotalDiscount.ToString().Replace(",", "."),
                                            line.Properties.Vat.ToString().Replace(",", "."));
                Guid orderDetailOid = FrameworkUtils.GetGuidFromQuery(sql4);

                string pToken2 = "";
                if (pTicketDrecrease)
                {
                    pToken2 = "decreased";
                }

                if (orderDetailOid == Guid.Empty)
                {
                    xOrderDetailLine = new fin_documentorderdetail(_sessionXpo)
                    {
                        //Values
                        Ord           = itemOrd,
                        Code          = xArticle.Code,
                        Designation   = line.Designation,
                        Quantity      = line.Properties.Quantity,
                        UnitMeasure   = xArticle.UnitMeasure.Acronym,
                        Price         = line.Properties.PriceNet,
                        Discount      = (xArticle.Discount > 0) ? xArticle.Discount : 0.0m,
                        TotalGross    = line.Properties.TotalGross,
                        TotalDiscount = line.Properties.TotalDiscount,
                        TotalTax      = line.Properties.TotalTax,
                        TotalFinal    = line.Properties.TotalFinal,
                        Token2        = pToken2,
                        //Use PriceTax Normal|TakeAway
                        Vat = priceTax,
                        //XPGuidObjects
                        Article     = xArticle,
                        OrderTicket = xOrderTicket
                    };

                    //Detect VatExemptionReason
                    if (line.Properties.VatExemptionReason != Guid.Empty)
                    {
                        xOrderDetailLine.VatExemptionReason = line.Properties.VatExemptionReason;
                    }
                    if (!isInUOW)
                    {
                        xOrderDetailLine.Save();
                    }
                }
                else
                {
                    xOrderDetailLine = (fin_documentorderdetail)FrameworkUtils.GetXPGuidObject(_sessionXpo, typeof(fin_documentorderdetail), orderDetailOid);

                    if (xOrderDetailLine.Token2 != "decreased" && !pTicketDrecrease)
                    {
                        xOrderDetailLine.Ord           = itemOrd;
                        xOrderDetailLine.Code          = xArticle.Code;
                        xOrderDetailLine.Designation   = line.Designation;
                        xOrderDetailLine.Quantity     += line.Properties.Quantity;
                        xOrderDetailLine.UnitMeasure   = xArticle.UnitMeasure.Acronym;
                        xOrderDetailLine.Price         = line.Properties.PriceNet;
                        xOrderDetailLine.Discount      = (xArticle.Discount > 0) ? xArticle.Discount : 0.0m;
                        xOrderDetailLine.TotalGross    = line.Properties.TotalGross;
                        xOrderDetailLine.TotalDiscount = line.Properties.TotalDiscount;
                        xOrderDetailLine.TotalTax      = line.Properties.TotalTax;
                        xOrderDetailLine.TotalFinal    = line.Properties.TotalFinal;
                        xOrderDetailLine.Token2        = pToken2;
                        //Use PriceTax Normal|TakeAway
                        xOrderDetailLine.Vat = priceTax;
                        //XPGuidObjects
                        xOrderDetailLine.Article     = xArticle;
                        xOrderDetailLine.OrderTicket = xOrderTicket;

                        if (!isInUOW)
                        {
                            xOrderDetailLine.Save();
                        }
                    }
                    else
                    if (xOrderDetailLine.Token2 == "decreased" && pTicketDrecrease)
                    {
                        xOrderDetailLine.Ord           = itemOrd;
                        xOrderDetailLine.Code          = xArticle.Code;
                        xOrderDetailLine.Designation   = line.Designation;
                        xOrderDetailLine.Quantity     += line.Properties.Quantity;
                        xOrderDetailLine.UnitMeasure   = xArticle.UnitMeasure.Acronym;
                        xOrderDetailLine.Price         = line.Properties.PriceNet;
                        xOrderDetailLine.Discount      = (xArticle.Discount > 0) ? xArticle.Discount : 0.0m;
                        xOrderDetailLine.TotalGross    = line.Properties.TotalGross;
                        xOrderDetailLine.TotalDiscount = line.Properties.TotalDiscount;
                        xOrderDetailLine.TotalTax      = line.Properties.TotalTax;
                        xOrderDetailLine.TotalFinal    = line.Properties.TotalFinal;
                        xOrderDetailLine.Token2        = pToken2;
                        //Use PriceTax Normal|TakeAway
                        xOrderDetailLine.Vat = priceTax;
                        //XPGuidObjects
                        xOrderDetailLine.Article     = xArticle;
                        xOrderDetailLine.OrderTicket = xOrderTicket;

                        if (!isInUOW)
                        {
                            xOrderDetailLine.Save();
                        }
                    }
                    else
                    if (xOrderDetailLine.Token2 == "decreased" && !pTicketDrecrease)
                    {
                        xOrderDetailLine.Ord           = itemOrd;
                        xOrderDetailLine.Code          = xArticle.Code;
                        xOrderDetailLine.Designation   = line.Designation;
                        xOrderDetailLine.Quantity      = xOrderDetailLine.Quantity;
                        xOrderDetailLine.UnitMeasure   = xArticle.UnitMeasure.Acronym;
                        xOrderDetailLine.Price         = line.Properties.PriceNet;
                        xOrderDetailLine.Discount      = (xArticle.Discount > 0) ? xArticle.Discount : 0.0m;
                        xOrderDetailLine.TotalGross    = line.Properties.TotalGross;
                        xOrderDetailLine.TotalDiscount = line.Properties.TotalDiscount;
                        xOrderDetailLine.TotalTax      = line.Properties.TotalTax;
                        xOrderDetailLine.TotalFinal    = line.Properties.TotalFinal;
                        xOrderDetailLine.Token2        = pToken2;
                        //Use PriceTax Normal|TakeAway
                        xOrderDetailLine.Vat = priceTax;
                        //XPGuidObjects
                        xOrderDetailLine.Article     = xArticle;
                        xOrderDetailLine.OrderTicket = xOrderTicket;

                        if (!isInUOW)
                        {
                            xOrderDetailLine.Save();
                        }
                    }
                }


                //}
            }
            ;

            //Clean Details and Open a New Blank Ticket in Session
            //Increment Terminal SessionApp CurrentTicketId
            //Only increase in new ticket, else stays the same
            if (!pTicketDrecrease)
            {
                _currentTicketId += 1;
                currentOrderMain.OrderTickets = new Dictionary <int, OrderTicket>();
                currentOrderMain.OrderTickets.Add(currentOrderMain.CurrentTicketId, new OrderTicket(this, _table.PriceType));
            }


            //Finish Writing Session
            GlobalFramework.SessionApp.Write();

            return(xOrderTicket);

            //Debug
            //_log.Debug(string.Format("FinishOrder(): xOrderMain.Oid [{0}]", xOrderMain.Oid));
            //_log.Debug(string.Format("FinishOrder(): _table.OrderMainId [{0}], _currentTicketId [{1}], _table.Name [{2}]", _table.OrderMainId, _currentTicketId, _table.Name));
        }
        //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
        //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);
        }
        //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
        //Check if has Active Document Finance Series, can have a filter parameter to check for Individual Series ex with DocumentType and FiscalYear

        /* NOT Used
         * public static bool HasActiveDocumentFinanceSeries()
         * {
         *  return HasActiveDocumentFinanceSeries(String.Empty);
         * }
         *
         * public static bool HasActiveDocumentFinanceSeries(string pFilter)
         * {
         *  bool result = false;
         *  if (pFilter != String.Empty) pFilter = string.Format(" AND {0}", pFilter);
         *  string sql = string.Format(@"SELECT Count(*) as Count FROM fin_documentfinanceseries WHERE (Disabled = 0 OR Disabled IS NULL){0};", pFilter);
         *  var sqlResult = GlobalFramework.SessionXpo.ExecuteScalar(sql);
         *  if (sqlResult != null && Convert.ToInt16(sqlResult) > 0) result = true;
         *  return result;
         * }
         */

        //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
        //Helper for Disable All Year Related Series and Series Terminal

        public static bool DisableActiveYearSeriesAndTerminalSeries(fin_documentfinanceyears pDocumentFinanceYears)
        {
            bool result = false;
            //Used to add DocumentFinanceYearSerieTerminal list to disable outside of Loop
            List <fin_documentfinanceseries> listDisableSeries = new List <fin_documentfinanceseries>();
            //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);

                    //Protection, used when user Restore DB without DocumentFinanceYears Created
                    if (documentFinanceYears != null)
                    {
                        foreach (fin_documentfinanceseries documentFinanceSeries in documentFinanceYears.Series)
                        {
                            if (!documentFinanceSeries.Disabled)
                            {
                                listDisableSeries.Add(documentFinanceSeries);
                            }
                            foreach (fin_documentfinanceyearserieterminal documentFinanceYearSerieTerminal in documentFinanceSeries.YearSerieTerminal)
                            {
                                listDeleteSerieTerminal.Add(documentFinanceYearSerieTerminal);
                            }
                        }

                        //Now we can disable, Outside of Loop
                        foreach (fin_documentfinanceseries disableSerie in listDisableSeries)
                        {
                            if (_debug)
                            {
                                _log.Debug(string.Format("  {0} : Disabled:[{1}]", disableSerie.Designation, disableSerie.Disabled));
                            }
                            disableSerie.Disabled = true;
                        }
                        //Now we can delete, Outside of Loop
                        foreach (fin_documentfinanceyearserieterminal deleteSerieTerminal in listDeleteSerieTerminal)
                        {
                            if (_debug)
                            {
                                _log.Debug(string.Format("    {0} : Deleted:[{1}]", deleteSerieTerminal.Designation, deleteSerieTerminal.Disabled));
                            }
                            deleteSerieTerminal.Delete();
                        }

                        //Finnaly Commit Changes
                        uowSession.CommitChanges();
                    }

                    result = true;
                }
                catch (Exception ex)
                {
                    uowSession.RollbackTransaction();
                    _log.Error(ex.Message, ex);
                }
            }

            return(result);
        }
        public bool PrintWorkSessionMovement(sys_configurationprinters pPrinter, pos_worksessionperiod pWorkSessionPeriod, SplitCurrentAccountMode pSplitCurrentAccountMode)
        {
            bool result = false;

            if (pPrinter != null)
            {
                sys_configurationprinters          printer  = pPrinter;
                sys_configurationprinterstemplates template = (sys_configurationprinterstemplates)FrameworkUtils.GetXPGuidObject(typeof(sys_configurationprinterstemplates), SettingsApp.XpoOidConfigurationPrintersTemplateWorkSessionMovement);
                string splitCurrentAccountFilter            = string.Empty;
                string fileTicket = template.FileTemplate;

                switch (pSplitCurrentAccountMode)
                {
                case SplitCurrentAccountMode.All:
                    break;

                case SplitCurrentAccountMode.NonCurrentAcount:
                    //Diferent from DocumentType CC
                    splitCurrentAccountFilter = string.Format("AND DocumentType <> '{0}'", SettingsApp.XpoOidDocumentFinanceTypeCurrentAccountInput);
                    break;

                case SplitCurrentAccountMode.CurrentAcount:
                    //Only DocumentType CC
                    splitCurrentAccountFilter = string.Format("AND DocumentType = '{0}'", SettingsApp.XpoOidDocumentFinanceTypeCurrentAccountInput);
                    break;
                }

                try
                {
                    //Shared Where for details and totals Queries
                    string sqlWhere = string.Empty;

                    if (pWorkSessionPeriod.PeriodType == WorkSessionPeriodType.Day)
                    {
                        sqlWhere = string.Format("PeriodParent = '{0}'{1}", pWorkSessionPeriod.Oid, splitCurrentAccountFilter);
                    }
                    else
                    {
                        sqlWhere = string.Format("Period = '{0}'{1}", pWorkSessionPeriod.Oid, splitCurrentAccountFilter);
                    }

                    //Shared for Both Modes
                    if (sqlWhere != string.Empty)
                    {
                        sqlWhere = string.Format(" AND {0}", sqlWhere);
                    }

                    //Format to Display Vars
                    string dateCloseDisplay = (pWorkSessionPeriod.SessionStatus == WorkSessionPeriodStatus.Open) ? resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "global_in_progress") : pWorkSessionPeriod.DateEnd.ToString(SettingsApp.DateTimeFormat);

                    //Get Session Period Details
                    Hashtable resultHashTable = ProcessWorkSessionPeriod.GetSessionPeriodSummaryDetails(pWorkSessionPeriod);

                    //Print Header Summary
                    DataRow   dataRow   = null;
                    DataTable dataTable = new DataTable();
                    dataTable.Columns.Add(new DataColumn("Label", typeof(string)));
                    dataTable.Columns.Add(new DataColumn("Value", typeof(string)));
                    //Open DateTime
                    dataRow    = dataTable.NewRow();
                    dataRow[0] = string.Format("{0}:", resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "global_worksession_open_datetime"));
                    dataRow[1] = pWorkSessionPeriod.DateStart.ToString(SettingsApp.DateTimeFormat);
                    dataTable.Rows.Add(dataRow);
                    //Close DataTime
                    dataRow    = dataTable.NewRow();
                    dataRow[0] = string.Format("{0}:", resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "global_worksession_close_datetime"));
                    dataRow[1] = dateCloseDisplay;
                    dataTable.Rows.Add(dataRow);
                    //Open Total CashDrawer
                    dataRow    = dataTable.NewRow();
                    dataRow[0] = string.Format("{0}:", resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "global_worksession_open_total_cashdrawer"));
                    dataRow[1] = FrameworkUtils.DecimalToStringCurrency((decimal)resultHashTable["totalMoneyInCashDrawerOnOpen"]);
                    dataTable.Rows.Add(dataRow);
                    //Close Total CashDrawer
                    dataRow    = dataTable.NewRow();
                    dataRow[0] = string.Format("{0}:", resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "global_worksession_close_total_cashdrawer"));
                    dataRow[1] = FrameworkUtils.DecimalToStringCurrency((decimal)resultHashTable["totalMoneyInCashDrawer"]);
                    dataTable.Rows.Add(dataRow);
                    //Total Money In
                    dataRow    = dataTable.NewRow();
                    dataRow[0] = string.Format("{0}:", resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "global_worksession_total_money_in"));
                    dataRow[1] = FrameworkUtils.DecimalToStringCurrency((decimal)resultHashTable["totalMoneyIn"]);
                    dataTable.Rows.Add(dataRow);
                    //Total Money Out
                    dataRow    = dataTable.NewRow();
                    dataRow[0] = string.Format("{0}:", resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "global_worksession_total_money_out"));
                    dataRow[1] = FrameworkUtils.DecimalToStringCurrency((decimal)resultHashTable["totalMoneyOut"]);
                    dataTable.Rows.Add(dataRow);
                    //Configure Ticket Column Properties
                    List <TicketColumn> columns = new List <TicketColumn>();
                    columns.Add(new TicketColumn("Label", "", Convert.ToInt16(_maxCharsPerLineNormal / 2) - 2, TicketColumnsAlign.Right));
                    columns.Add(new TicketColumn("Value", "", Convert.ToInt16(_maxCharsPerLineNormal / 2) - 2, TicketColumnsAlign.Left));
                    TicketTable ticketTable = new TicketTable(dataTable, columns, _thermalPrinterGeneric.MaxCharsPerLineNormalBold);
                    //Print Ticket Table
                    ticketTable.Print(_thermalPrinterGeneric);
                    //Line Feed
                    _thermalPrinterGeneric.LineFeed();

                    //Get Final Rendered DataTable Groups
                    Dictionary <DataTableGroupPropertiesType, DataTableGroupProperties> dictGroupProperties = GenDataTableWorkSessionMovementResume(pWorkSessionPeriod.PeriodType, pSplitCurrentAccountMode, sqlWhere);

                    //Prepare Local vars for Group Loop
                    XPSelectData xPSelectData = null;
                    string       designation  = string.Empty;
                    decimal      quantity     = 0.0m;
                    decimal      total        = 0.0m;
                    string       unitMeasure  = string.Empty;
                    //Store Final Totals
                    decimal summaryTotalQuantity = 0.0m;
                    decimal summaryTotal         = 0.0m;
                    //Used to Custom Print Table Ticket Rows
                    List <string> tableCustomPrint = new List <string>();

                    //Start to process Group
                    int groupPosition = -1;
                    //Assign Position to Print Payment Group Split Title
                    int groupPositionTitlePayments = (pWorkSessionPeriod.PeriodType == WorkSessionPeriodType.Day) ? 9 : 8;
                    //If CurrentAccount Mode decrease 1, it dont have PaymentMethods
                    if (pSplitCurrentAccountMode == SplitCurrentAccountMode.CurrentAcount)
                    {
                        groupPositionTitlePayments--;
                    }


                    foreach (KeyValuePair <DataTableGroupPropertiesType, DataTableGroupProperties> item in dictGroupProperties)
                    //foreach (DataTableGroupProperties item in dictGroupProperties.Values)
                    {
                        if (item.Value.Enabled)
                        {
                            //Increment Group Position
                            groupPosition++;

                            //Print Group Titles (FinanceDocuments|Payments)
                            if (groupPosition == 0)
                            {
                                _thermalPrinterGeneric.WriteLine(resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "global_worksession_resume_finance_documents"), WriteLineTextMode.Big);
                                _thermalPrinterGeneric.LineFeed();
                            }
                            else if (groupPosition == groupPositionTitlePayments)
                            {
                                //When finish FinanceDocuemnts groups, print Last Row, the Summary Totals Row
                                _thermalPrinterGeneric.WriteLine(tableCustomPrint[tableCustomPrint.Count - 1], WriteLineTextMode.DoubleHeight);
                                _thermalPrinterGeneric.LineFeed();

                                _thermalPrinterGeneric.WriteLine(resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "global_worksession_resume_paymens_documents"), WriteLineTextMode.Big);
                                _thermalPrinterGeneric.LineFeed();
                            }

                            //Reset Totals
                            summaryTotalQuantity = 0.0m;
                            summaryTotal         = 0.0m;

                            //Get Group Data from group Query
                            xPSelectData = FrameworkUtils.GetSelectedDataFromQuery(item.Value.Sql);

                            //Generate Columns
                            columns = new List <TicketColumn>();
                            columns.Add(new TicketColumn("GroupTitle", item.Value.Title, 0, TicketColumnsAlign.Left));
                            columns.Add(new TicketColumn("Quantity", resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "global_quantity_acronym"), 8, TicketColumnsAlign.Right, typeof(decimal), "{0:0.00}"));
                            //columns.Add(new TicketColumn("UnitMeasure", string.Empty, 3));
                            columns.Add(new TicketColumn("Total", resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "global_totalfinal_acronym"), 10, TicketColumnsAlign.Right, typeof(decimal), "{0:0.00}"));

                            //Init DataTable
                            dataTable = new DataTable();
                            dataTable.Columns.Add(new DataColumn("GroupDesignation", typeof(string)));
                            dataTable.Columns.Add(new DataColumn("Quantity", typeof(decimal)));
                            //dataTable.Columns.Add(new DataColumn("UnitMeasure", typeof(string)));
                            dataTable.Columns.Add(new DataColumn("Total", typeof(decimal)));

                            //If Has data
                            if (xPSelectData.Data.Length > 0)
                            {
                                foreach (SelectStatementResultRow row in xPSelectData.Data)
                                {
                                    designation = Convert.ToString(row.Values[xPSelectData.GetFieldIndex("Designation")]);
                                    quantity    = Convert.ToDecimal(row.Values[xPSelectData.GetFieldIndex("Quantity")]);
                                    unitMeasure = Convert.ToString(row.Values[xPSelectData.GetFieldIndex("UnitMeasure")]);
                                    total       = Convert.ToDecimal(row.Values[xPSelectData.GetFieldIndex("Total")]);
                                    // Override Encrypted values
                                    if (GlobalFramework.PluginSoftwareVendor != null && item.Key.Equals(DataTableGroupPropertiesType.DocumentsUser) || item.Key.Equals(DataTableGroupPropertiesType.PaymentsUser))
                                    {
                                        designation = GlobalFramework.PluginSoftwareVendor.Decrypt(designation);
                                    }
                                    //Sum Summary Totals
                                    summaryTotalQuantity += quantity;
                                    summaryTotal         += total;
                                    //_log.Debug(string.Format("Designation: [{0}], quantity: [{1}], unitMeasure: [{2}], total: [{3}]", designation, quantity, unitMeasure, total));
                                    //Create Row
                                    dataRow    = dataTable.NewRow();
                                    dataRow[0] = designation;
                                    dataRow[1] = quantity;
                                    //dataRow[2] = unitMeasure;
                                    dataRow[2] = total;
                                    dataTable.Rows.Add(dataRow);
                                }
                            }
                            else
                            {
                                //Create Row
                                dataRow    = dataTable.NewRow();
                                dataRow[0] = resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "global_cashdrawer_without_movements");
                                dataRow[1] = 0.0m;
                                //dataRow[2] = string.Empty;//UnitMeasure
                                dataRow[2] = 0.0m;
                                dataTable.Rows.Add(dataRow);
                            }

                            //Add Final Summary Row
                            dataRow    = dataTable.NewRow();
                            dataRow[0] = resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "global_total");
                            dataRow[1] = summaryTotalQuantity;
                            //dataRow[2] = string.Empty;
                            dataRow[2] = summaryTotal;
                            dataTable.Rows.Add(dataRow);

                            //Prepare TicketTable
                            ticketTable = new TicketTable(dataTable, columns, _thermalPrinterGeneric.MaxCharsPerLineNormal);

                            //Custom Print Loop, to Print all Table Rows, and Detect Rows to Print in DoubleHeight (Title and Total)
                            tableCustomPrint = ticketTable.GetTable();
                            WriteLineTextMode rowTextMode;

                            //Dynamic Print All except Last One (Totals), Double Height in Titles
                            for (int i = 0; i < tableCustomPrint.Count - 1; i++)
                            {
                                //Prepare TextMode Based on Row
                                rowTextMode = (i == 0) ? WriteLineTextMode.DoubleHeight : WriteLineTextMode.Normal;
                                //Print Row
                                _thermalPrinterGeneric.WriteLine(tableCustomPrint[i], rowTextMode);
                            }

                            //Line Feed
                            _thermalPrinterGeneric.LineFeed();
                        }
                    }

                    //When finish all groups, print Last Row, the Summary Totals Row, Ommited in Custom Print Loop
                    _thermalPrinterGeneric.WriteLine(tableCustomPrint[tableCustomPrint.Count - 1], WriteLineTextMode.DoubleHeight);

                    result = true;
                }
                catch (Exception ex)
                {
                    _log.Error(ex.Message, ex);
                    throw new Exception(ex.Message);
                }
            }

            return(result);
        }