//Start Application or Change User private void ProcessLogin(SYS_UserDetail pUserDetail) { GlobalFramework.LoggedUser = pUserDetail; GlobalFramework.LoggedUserPermissions = FrameworkUtils.GetUserPermissions(); FrameworkUtils.Audit("USER_LOGIN", string.Format(Resx.audit_message_user_login, pUserDetail.Name)); //SessionApp Add LoggedUser if (!GlobalFramework.SessionApp.LoggedUsers.ContainsKey(GlobalFramework.LoggedUser.Oid)) { GlobalFramework.SessionApp.LoggedUsers.Add(pUserDetail.Oid, FrameworkUtils.CurrentDateTimeAtomic()); } else { GlobalFramework.SessionApp.LoggedUsers[GlobalFramework.LoggedUser.Oid] = FrameworkUtils.CurrentDateTimeAtomic(); } GlobalFramework.SessionApp.Write(); //Returns to default mode _mode = NumberPadPinMode.Password; UpdateStatusLabels(); //Process Notifications After Login/Create First Time PosWindow //Disabled SystemNotification and ShowNotifications. Moved to Startup Window //FrameworkUtils.SystemNotification(); //Utils.ShowNotifications(_sourceWindow, pUserDetail.Oid); Utils.ShowFrontOffice(_sourceWindow); }
//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(); }
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //Static public static void QuitWithoutConfirmation(bool pAudit = true) { log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); try { //Audit if (pAudit) { FrameworkUtils.Audit("APP_CLOSE"); } //Before use DeleteSession() //GlobalFramework.SessionApp.CleanSession(); //GlobalFramework.SessionApp.Write(); GlobalFramework.SessionApp.DeleteSession(); //Disconnect SessionXpo GlobalFramework.SessionXpo.Disconnect(); } catch (Exception ex) { log.Error(ex.Message, ex); } Application.Quit(); }
public void LogOutUser(bool pGotoStartupWindow, sys_userdetail pUserDetail) { if ( GlobalFramework.SessionApp.LoggedUsers.ContainsKey(pUserDetail.Oid)) { GlobalFramework.SessionApp.LoggedUsers.Remove(pUserDetail.Oid); GlobalFramework.SessionApp.Write(); FrameworkUtils.Audit("USER_LOGOUT", string.Format(resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "audit_message_user_logout"), pUserDetail.Name)); //Only Reset LoggedUser if equal to pUser if (GlobalFramework.LoggedUser.Equals(pUserDetail)) { GlobalFramework.LoggedUser = null; GlobalFramework.LoggedUserPermissions = null; } } //Update Table, In case user change Users in BackOffice GlobalApp.WindowStartup.TablePadUser.UpdateSql(); //Required to Assign Details to Update Select User AssignUserDetail(); //Show Startup Windows, or Not (Silent Mode) if (pGotoStartupWindow) { GlobalApp.WindowStartup.ShowAll(); } }
//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(); }
//ChangeTable - Change Order From Table to Table void _buttonKeyChangeTable_Clicked(object sender, EventArgs e) { PosTablesDialog dialog = new PosTablesDialog(this.SourceWindow, DialogFlags.DestroyWithParent, TableFilterMode.OnlyFreeTables); ResponseType response = (ResponseType)dialog.Run(); if (response == ResponseType.Ok || response == ResponseType.Cancel || response == ResponseType.DeleteEvent) { if (response == ResponseType.Ok) { OrderMain currentOrderMain = GlobalFramework.SessionApp.OrdersMain[GlobalFramework.SessionApp.CurrentOrderMainOid]; POS_ConfigurationPlaceTable xOldTable = (POS_ConfigurationPlaceTable)FrameworkUtils.GetXPGuidObject(typeof(POS_ConfigurationPlaceTable), currentOrderMain.Table.Oid); POS_ConfigurationPlaceTable xNewTable = (POS_ConfigurationPlaceTable)FrameworkUtils.GetXPGuidObject(typeof(POS_ConfigurationPlaceTable), dialog.CurrentTableOid); //Require to Prevent A first chance exception of type 'DevExpress.Xpo.DB.Exceptions.LockingException' occurred in DevExpress.Xpo.v13.2.dll when it is Changed in Diferent Session ex UnitOfWork //TODO: Confirm working with Reload Commented //xOldTable.Reload(); //xNewTable.Reload(); if (xNewTable.TableStatus != TableStatus.Free) { Utils.ShowMessageTouch( GlobalApp.WindowPos, DialogFlags.Modal, MessageType.Warning, ButtonsType.Ok, Resx.global_error, Resx.dialog_message_table_is_not_free ); } else { //Put Old table Status to Free xOldTable.TableStatus = TableStatus.Free; xOldTable.Save(); FrameworkUtils.Audit("TABLE_OPEN", string.Format(Resx.audit_message_table_open, xOldTable.Designation)); //Put New table Status to Open xNewTable.TableStatus = TableStatus.Open; xNewTable.Save(); FrameworkUtils.Audit("TABLE_CLOSE", string.Format(Resx.audit_message_table_close, xNewTable.Designation)); //Change DocumentOrderMain table, If OpenOrder Exists in That table Guid documentOrderMainOid = currentOrderMain.GetOpenTableFieldValueGuid(xOldTable.Oid, "Oid"); FIN_DocumentOrderMain xDocumentOrderMain = (FIN_DocumentOrderMain)FrameworkUtils.GetXPGuidObject(typeof(FIN_DocumentOrderMain), documentOrderMainOid); if (xDocumentOrderMain != null) { xDocumentOrderMain.PlaceTable = xNewTable; xDocumentOrderMain.UpdatedAt = FrameworkUtils.CurrentDateTimeAtomic(); xDocumentOrderMain.Save(); } //Assign Session Data currentOrderMain.Table.Oid = xNewTable.Oid; currentOrderMain.Table.Name = xNewTable.Designation; currentOrderMain.Table.PriceType = (PriceType)xNewTable.Place.PriceType.EnumValue; currentOrderMain.OrderTickets[currentOrderMain.CurrentTicketId].PriceType = (PriceType)xNewTable.Place.PriceType.EnumValue; currentOrderMain.Table.PlaceId = xNewTable.Place.Oid; GlobalFramework.SessionApp.Write(); //Finally Update Status Bar, Table Name, Totals Etc UpdateOrderStatusBar(); } } dialog.Destroy(); } ; }
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); } }
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); } }
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: public static bool OpenDoor(sys_configurationprinters pPrinter) { bool result = false; bool hasPermission = FrameworkUtils.HasPermissionTo("HARDWARE_DRAWER_OPEN"); if (pPrinter != null && hasPermission) { try { switch (pPrinter.PrinterType.Token) { //Impressora SINOCAN em ambiente Windows case "THERMAL_PRINTER_WINDOWS": //Impressora SINOCAN em ambiente Linux case "THERMAL_PRINTER_LINUX": //Impressora SINOCAN em ambiente WindowsLinux/Socket case "THERMAL_PRINTER_SOCKET": //Impressora SINOCAN em ambiente WindowsLinux/USB case "THERMAL_PRINTER_USB": PrintObject printObjectSINOCAN = new PrintObject(0); // Deprecated //int m = Convert.ToInt32(GlobalFramework.Settings["DoorValueM"]); //int t1 = Convert.ToInt32(GlobalFramework.Settings["DoorValueT1"]); //int t2 = Convert.ToInt32(GlobalFramework.Settings["DoorValueT2"]); // Open Drawer //TK016249 - Impressoras - Diferenciação entre Tipos int m = GlobalFramework.LoggedTerminal.ThermalPrinter.ThermalOpenDrawerValueM; int t1 = GlobalFramework.LoggedTerminal.ThermalPrinter.ThermalOpenDrawerValueT1; int t2 = GlobalFramework.LoggedTerminal.ThermalPrinter.ThermalOpenDrawerValueT2; printObjectSINOCAN.OpenDoor(pPrinter.PrinterType.Token, pPrinter.NetworkName, m, t1, t2); //Audit FrameworkUtils.Audit("CASHDRAWER_OPEN", resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "audit_message_cashdrawer_open")); break; } result = true; } catch (Exception ex) { _log.Warn(ex.Message, ex); } } return(result); }
public bool ValidatePassword(sys_userdetail pUserDetail) { bool result = false; string password = _entryPin.Text; string sql = string.Format(@" SELECT AccessPin FROM sys_userdetail WHERE (Disabled <> 1 OR Disabled IS NULL) AND Oid = '{0}' ;", pUserDetail.Oid ); try { var resultObject = GlobalFramework.SessionXpo.ExecuteScalar(sql); if (resultObject != null && resultObject.GetType() == typeof(String) && CryptographyUtils.SaltedString.ValidateSaltedString(resultObject.ToString(), password)) { _entryPin.ModifyText(StateType.Normal, Utils.ColorToGdkColor(Color.Black)); _entryPin.Visibility = false; _entryPinShowStatus = false; result = true; } else { FrameworkUtils.Audit("USER_LOGIN_ERROR", string.Format(resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "audit_message_user_login_error"), pUserDetail.Name)); _entryPin.ModifyText(StateType.Normal, Utils.ColorToGdkColor(Color.Red)); _entryPin.Text = resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "status_message_pin_error"); _entryPin.Visibility = true; _entryPinShowStatus = true; result = false; } return(result); } catch (Exception ex) { _log.Error(ex.Message, ex); return(result); } }
/* ERR201810#15 - Database backup issues */ //public static bool Backup() //{ // return Backup(null); //} public static bool Backup(Window pSourceWindow) { bool backupResult = true; string fileName = string.Empty; string fullFileNamePacked = string.Empty; string fileHash = string.Empty; Thread thread; try { //FrameworkUtils.ShowWaitingCursor(); Init(); /* IN009164 - Begin */ string xpoConnectionString = string.Format(GlobalFramework.Settings["xpoConnectionString"], GlobalFramework.DatabaseName.ToLower()); XpoDefault.DataLayer = XpoDefault.GetDataLayer(xpoConnectionString, AutoCreateOption.None); Session SessionXpoForBackupPurposes = new Session(XpoDefault.DataLayer) { LockingOption = LockingOption.None }; _log.Debug(string.Format("bool Backup(Window pSourceWindow) :: Init XpoDefault.DataLayer [ {0} ]", SessionXpoForBackupPurposes.ToString())); /* IN009164 - End */ //Initialize object before start Actions, to allocate database (automatic backups) and assign CreatedAt, this way next Terminal Skip Backup when trigger backup event sys_systembackup systemBackup = new sys_systembackup(SessionXpoForBackupPurposes) { FileName = Path.GetRandomFileName(), FileNamePacked = Path.GetRandomFileName(), DataBaseType = GlobalFramework.DatabaseType, Version = FrameworkUtils.GetNextTableFieldID("sys_systembackup", "Version", false), Terminal = (pos_configurationplaceterminal)SessionXpoForBackupPurposes.GetObjectByKey(typeof(pos_configurationplaceterminal), GlobalFramework.LoggedTerminal.Oid) }; systemBackup.Save(); switch (GlobalFramework.DatabaseType) { case DatabaseType.MonoLite: case DatabaseType.SQLite: fileName = GetBackupFileName(_fileExtension, systemBackup.Version, ""); //Non Thread //resultBackup = BackupSQLite(fileName); //Thread thread = new Thread(() => backupResult = BackupSQLite(fileName)); Utils.ThreadStart(pSourceWindow, thread); break; case DatabaseType.MSSqlServer: fileName = GetBackupFileName(_fileExtension, systemBackup.Version, ""); //Non Thread //resultBackup = BackupMSSqlServer(fileName); //Thread thread = new Thread(() => backupResult = BackupMSSqlServer(Path.GetFileName(fileName), SessionXpoForBackupPurposes)); Utils.ThreadStart(pSourceWindow, thread); break; case DatabaseType.MySql: fileName = GetBackupFileName(_fileExtension, systemBackup.Version, ""); //Non Thread //resultBackup = BackupMySql(_backupConnectionString, fileName); //Thread thread = new Thread(() => backupResult = BackupMySql(_backupConnectionString, fileName)); Utils.ThreadStart(pSourceWindow, thread); break; default: break; } /* IN007007 */ _log.Debug(string.Format("Backup DatabaseType: [ {0} ] to FileName: [ {1} ], resultBackup:[ {2} ]", GlobalFramework.DatabaseType, fileName, backupResult)); if (_debug) { _log.Debug(string.Format("Backup DatabaseType: [ {0} ] to FileName: [ {1} ], resultBackup:[ {2} ]", GlobalFramework.DatabaseType, fileName, backupResult)); } if (backupResult) { //Update SystemBackup after Backup systemBackup.FileName = Path.GetFileName(fileName); systemBackup.FilePath = Path.GetDirectoryName(fileName); //Extra Protection for System Automatic Backups, with unlogged users sys_userdetail userDetail = (GlobalFramework.LoggedUser != null) ? (sys_userdetail)SessionXpoForBackupPurposes.GetObjectByKey(typeof(sys_userdetail), GlobalFramework.LoggedUser.Oid) : null; if (userDetail != null) { systemBackup.User = userDetail; } //Non MSSqlServer Work: Cant Get Remote File Sizes, Hash etc from LPDev Backups if (GlobalFramework.DatabaseType != DatabaseType.MSSqlServer) { //systemBackup.FileSize = new FileInfo(fileName).Length; systemBackup.FileNamePacked = Path.ChangeExtension(systemBackup.FileName, SettingsApp.BackupExtension); //Compress File : Required OSSlash fullFileNamePacked = FrameworkUtils.OSSlash(string.Format(@"{0}\{1}", systemBackup.FilePath, systemBackup.FileNamePacked)); // Old Method before PluginSoftwareVendor Implementation //backupResult = Utils.ZipPack(new string[] { fileName }, fullFileNamePacked); backupResult = GlobalFramework.PluginSoftwareVendor.BackupDatabase(SettingsApp.SecretKey, new string[] { fileName }, fullFileNamePacked); // Add FileHash if (backupResult) { systemBackup.FileHash = FrameworkUtils.MD5HashFile(fullFileNamePacked); } } //MSSqlServer else { //Must Assign FileName to FileNamePacked else next backup violate iFileNamePacked_SystemBackup Index systemBackup.FileNamePacked = systemBackup.FileName; } if (backupResult) { //Commit Object systemBackup.Save(); //Remove Temporary Backup /* ERR201810#15 - Database backup issues */ //try { if (File.Exists(fileName)) { File.Delete(fileName); } } //catch (Exception ex) { _log.Error(ex.Message, ex); } //Post Backup FrameworkUtils.Audit("DATABASE_BACKUP", string.Format(resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "audit_message_database_backup"), (fullFileNamePacked != string.Empty) ? fullFileNamePacked : systemBackup.FileNamePacked )); //Moved to Thread Outside > Only Show if not in Silence Mode if (pSourceWindow != null) { Utils.ShowMessageTouch(pSourceWindow, DialogFlags.Modal, _sizeDialog, MessageType.Info, ButtonsType.Close, resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "global_information"), string.Format(resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "dialog_message_database_backup_successfully"), systemBackup.FileNamePacked)); } } else { //On Error Delete Object form Database, this way we dont have a invalid Backup systemBackup.Delete(); /* * IN007007 * * This implementation covers only "non-DatabaseType.MSSqlServer" database, when calling the method to secure-compact database file: * > GlobalFramework.PluginSoftwareVendor.BackupDatabase...Utils.ZipPack * * Please note that variable "backupResult" never changes its value when "DatabaseType.MSSqlServer", therefore is not being covered by this. */ // Show only when "Silent Mode" is on if (pSourceWindow != null) { Utils.ShowMessageTouch(pSourceWindow, DialogFlags.Modal, _sizeDialog, MessageType.Warning, ButtonsType.Close, resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "global_information"), string.Format(resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "dialog_message_database_backup_error_when_secure_compacting"), systemBackup.FileNamePacked)); } _log.Debug($"DataBaseBackup.Backup(Window pSourceWindow): {string.Format(resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "dialog_message_database_backup_error_when_secure_compacting"), systemBackup.FileNamePacked)}"); } } else { //Moved to Thread Outside > Only Show if not in Silence Mode if (pSourceWindow != null) { Utils.ShowMessageTouch(pSourceWindow, DialogFlags.Modal, _sizeDialog, MessageType.Error, ButtonsType.Close, resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "global_error"), string.Format(resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "dialog_message_database_backup_error"), Path.GetFileName(fileName))); } } /* IN009164 */ SessionXpoForBackupPurposes.Disconnect(); } catch (Exception ex) { _log.Error("bool Backup(Window pSourceWindow) :: Error during backup process: " + ex.Message, ex); // _log.Error("bool Backup(Window pSourceWindow) :: Error during backup process on Session [ " + SessionXpoForBackupPurposes.ToString() + " ]: " + ex.Message, ex); // SessionXpoForBackupPurposes.Disconnect(); } return(backupResult); }
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: private void Init() { try { //Used to Force create DatabaseScema and Fixtures with XPO (Non Script Mode): Requirements for Work: Empty or Non Exist Database //Notes: OnError "An exception of type 'DevExpress.Xpo.DB.Exceptions.SchemaCorrectionNeededException'", UnCheck [X] Break when this exception is user-unhandled and continue, watch log and wait until sucefull message appear bool xpoCreateDatabaseAndSchema = SettingsApp.XPOCreateDatabaseAndSchema; bool xpoCreateDatabaseObjectsWithFixtures = xpoCreateDatabaseAndSchema; //Prepare AutoCreateOption AutoCreateOption xpoAutoCreateOption = (xpoCreateDatabaseAndSchema) ? AutoCreateOption.DatabaseAndSchema : AutoCreateOption.None; //Init Settings Main Config Settings //GlobalFramework.Settings = ConfigurationManager.AppSettings; //Override Licence data with Encrypted File Data if (File.Exists(SettingsApp.LicenceFileName)) { Utils.AssignLicence(SettingsApp.LicenceFileName, true); } //Other Global App Settings GlobalApp.MultiUserEnvironment = Convert.ToBoolean(GlobalFramework.Settings["appMultiUserEnvironment"]); GlobalApp.UseVirtualKeyBoard = Convert.ToBoolean(GlobalFramework.Settings["useVirtualKeyBoard"]); //Init App Notifications GlobalApp.Notifications = new System.Collections.Generic.Dictionary <string, bool>(); GlobalApp.Notifications["SHOW_PRINTER_UNDEFINED"] = true; //System GlobalApp.FilePickerStartPath = System.IO.Directory.GetCurrentDirectory(); //Get DataBase Details GlobalFramework.DatabaseType = (DatabaseType)Enum.Parse(typeof(DatabaseType), GlobalFramework.Settings["databaseType"]); //Override default Database name with parameter from config string configDatabaseName = GlobalFramework.Settings["databaseName"]; GlobalFramework.DatabaseName = (string.IsNullOrEmpty(configDatabaseName)) ? SettingsApp.DatabaseName : configDatabaseName; //Xpo Connection String string xpoConnectionString = string.Format(GlobalFramework.Settings["xpoConnectionString"], GlobalFramework.DatabaseName.ToLower()); Utils.AssignConnectionStringToSettings(xpoConnectionString); //Removed Protected Files //ProtectedFiles, Before Create Database from Scripts, usefull if Scripts are modified by User if (SettingsApp.ProtectedFilesUse) { GlobalApp.ProtectedFiles = InitProtectedFiles(); } //Check if Database Exists if Not Create it from Scripts bool databaseCreated = false; if (!xpoCreateDatabaseAndSchema) { //Get result to check if DB is created (true) try { // Launch Scripts databaseCreated = DataLayer.CreateDatabaseSchema(xpoConnectionString, GlobalFramework.DatabaseType, GlobalFramework.DatabaseName); } catch (Exception ex) { //Extra protection to prevent goes to login without a valid connection _log.Error(ex.Message, ex); Utils.ShowMessageTouch(GlobalApp.WindowStartup, DialogFlags.Modal, new Size(900, 700), MessageType.Error, ButtonsType.Ok, Resx.global_error, ex.Message); Environment.Exit(0); } } //Init XPO Connector DataLayer try { _log.Debug(string.Format("Init XpoDefault.DataLayer: [{0}]", xpoConnectionString)); XpoDefault.DataLayer = XpoDefault.GetDataLayer(xpoConnectionString, xpoAutoCreateOption); GlobalFramework.SessionXpo = new Session(XpoDefault.DataLayer) { LockingOption = LockingOption.None }; } catch (Exception ex) { _log.Error(ex.Message, ex); Utils.ShowMessageTouch(GlobalApp.WindowStartup, DialogFlags.Modal, new Size(900, 700), MessageType.Error, ButtonsType.Ok, Resx.global_error, ex.Message); throw; } //Check Valid Database Scheme if (!xpoCreateDatabaseAndSchema && !FrameworkUtils.IsRunningOnMono()) { bool isSchemaValid = DataLayer.IsSchemaValid(xpoConnectionString); _log.Debug(string.Format("Check if Database Scheme: isSchemaValid : [{0}]", isSchemaValid)); if (!isSchemaValid) { string endMessage = "Invalid database Schema! Fix database Schema and Try Again!"; Utils.ShowMessageTouch(GlobalApp.WindowStartup, DialogFlags.Modal, new Size(500, 300), MessageType.Error, ButtonsType.Ok, Resx.global_error, string.Format(endMessage, Environment.NewLine)); Environment.Exit(0); } } // Assign PluginSoftwareVendor Reference to DataLayer SettingsApp to use In Date Protection, we Required to assign it Statically to Prevent Circular References // Required to be here, before it is used in above lines, ex Utils.GetTerminal() if (GlobalFramework.PluginSoftwareVendor != null) { logicpos.datalayer.App.SettingsApp.PluginSoftwareVendor = GlobalFramework.PluginSoftwareVendor; } //If not in Xpo create database Scheme Mode, Get Terminal from Db if (!xpoCreateDatabaseAndSchema) { GlobalFramework.LoggedTerminal = Utils.GetTerminal(); } //After Assigned LoggedUser if (xpoCreateDatabaseObjectsWithFixtures) { InitFixtures.InitUserAndTerminal(GlobalFramework.SessionXpo); InitFixtures.InitOther(GlobalFramework.SessionXpo); InitFixtures.InitDocumentFinance(GlobalFramework.SessionXpo); InitFixtures.InitWorkSession(GlobalFramework.SessionXpo); } //End Xpo Create Scheme and Fixtures, Terminate App and Request assign False to Developer Vars if (xpoCreateDatabaseAndSchema) { string endMessage = "Xpo Create Schema and Fixtures Done!{0}Please assign false to 'xpoCreateDatabaseAndSchema' and 'xpoCreateDatabaseObjectsWithFixtures' and run App again"; Utils.ShowMessageTouch(GlobalApp.WindowStartup, DialogFlags.Modal, new Size(500, 300), MessageType.Info, ButtonsType.Ok, Resx.global_information, string.Format(endMessage, Environment.NewLine)); Environment.Exit(0); } //Init PreferenceParameters GlobalFramework.PreferenceParameters = FrameworkUtils.GetPreferencesParameters(); //Init Preferences Path MainApp.InitPathsPrefs(); bool validDirectoryBackup = FrameworkUtils.CreateDirectory(FrameworkUtils.OSSlash(Convert.ToString(GlobalFramework.Path["backups"]))); //Show Dialog if Cant Create Backups Directory (Extra Protection for Shared Network Folders) if (!validDirectoryBackup) { ResponseType response = Utils.ShowMessageTouch(GlobalApp.WindowStartup, DialogFlags.Modal, MessageType.Question, ButtonsType.YesNo, Resx.global_error, string.Format(Resx.dialog_message_error_create_directory_backups, Convert.ToString(GlobalFramework.Path["backups"]))); //Enable Quit After BootStrap, Preventing Application.Run() if (response == ResponseType.No) { _quitAfterBootStrap = true; } } //CultureInfo/Localization string culture = GlobalFramework.PreferenceParameters["CULTURE"]; if (!string.IsNullOrEmpty(culture)) { Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(culture); } GlobalFramework.CurrentCulture = CultureInfo.CurrentUICulture; //Always use en-US NumberFormat because of mySql Requirements GlobalFramework.CurrentCultureNumberFormat = CultureInfo.GetCultureInfo(SettingsApp.CultureNumberFormat); //Init AppSession string appSessionFile = Utils.GetSessionFileName(); if (databaseCreated && File.Exists(appSessionFile)) { File.Delete(appSessionFile); } GlobalFramework.SessionApp = GlobalFrameworkSession.InitSession(appSessionFile); //Try to Get open Session Day/Terminal for this Terminal GlobalFramework.WorkSessionPeriodDay = ProcessWorkSessionPeriod.GetSessionPeriod(WorkSessionPeriodType.Day); GlobalFramework.WorkSessionPeriodTerminal = ProcessWorkSessionPeriod.GetSessionPeriod(WorkSessionPeriodType.Terminal); //Use Detected ScreenSize string appScreenSize = string.IsNullOrEmpty(GlobalFramework.Settings["appScreenSize"]) ? GlobalFramework.PreferenceParameters["APP_SCREEN_SIZE"] : GlobalFramework.Settings["appScreenSize"]; if (appScreenSize.Replace(" ", string.Empty).Equals("0,0") || string.IsNullOrEmpty(appScreenSize)) { // Force Unknown Screen Size //GlobalApp.ScreenSize = new Size(2000, 1800); GlobalApp.ScreenSize = Utils.GetThemeScreenSize(); } //Use config ScreenSize else { Size configAppScreenSize = Utils.StringToSize(appScreenSize); GlobalApp.ScreenSize = Utils.GetThemeScreenSize(configAppScreenSize); } // Init ExpressionEvaluator GlobalApp.ExpressionEvaluator.EvaluateFunction += ExpressionEvaluatorExtended.ExpressionEvaluator_EvaluateFunction; // Init Variables ExpressionEvaluatorExtended.InitVariablesStartupWindow(); ExpressionEvaluatorExtended.InitVariablesPosMainWindow(); // Define Max Dialog Window Size GlobalApp.MaxWindowSize = new Size(GlobalApp.ScreenSize.Width - 40, GlobalApp.ScreenSize.Height - 40); // Add Variables to ExpressionEvaluator.Variables Singleton GlobalApp.ExpressionEvaluator.Variables.Add("globalScreenSize", GlobalApp.ScreenSize); //Parse and store Theme in Singleton try { GlobalApp.Theme = XmlToObjectParser.ParseFromFile(SettingsApp.FileTheme); // Use with dynamic Theme properties like: // GlobalApp.Theme.Theme.Frontoffice.Window[0].Globals.Name = PosBaseWindow // GlobalApp.Theme.Theme.Frontoffice.Window[1].Objects.TablePadUser.Position = 50,50 // or use predicate with from object id ex //var predicate = (Predicate<dynamic>)((dynamic x) => x.ID == "StartupWindow"); //var themeWindow = GlobalApp.Theme.Theme.Frontoffice.Window.Find(predicate); //_log.Debug(string.Format("Message: [{0}]", themeWindow.Globals.Title)); } catch (Exception ex) { Utils.ShowMessageTouchErrorRenderTheme(GlobalApp.WindowStartup, ex.Message); } //Init FastReports Custom Functions and Custom Vars CustomFunctions.Register(SettingsApp.AppName); //Hardware : Init Display if (GlobalFramework.LoggedTerminal.PoleDisplay != null) { GlobalApp.UsbDisplay = (UsbDisplayDevice)UsbDisplayDevice.InitDisplay(); GlobalApp.UsbDisplay.WriteCentered(string.Format("{0} {1}", SettingsApp.AppName, FrameworkUtils.ProductVersion), 1); GlobalApp.UsbDisplay.WriteCentered(SettingsApp.AppUrl, 2); GlobalApp.UsbDisplay.EnableStandBy(); } //Hardware : Init BarCodeReader if (GlobalFramework.LoggedTerminal.BarcodeReader != null) { GlobalApp.BarCodeReader = new InputReader(); } //Hardware : Init WeighingBalance if (GlobalFramework.LoggedTerminal.WeighingMachine != null) { GlobalApp.WeighingBalance = new WeighingBalance(GlobalFramework.LoggedTerminal.WeighingMachine); //_log.Debug(string.Format("IsPortOpen: [{0}]", GlobalApp.WeighingBalance.IsPortOpen())); } //Start Database Backup Timer if not create XPO Schema and SoftwareVendor is Active if (GlobalFramework.PluginSoftwareVendor != null && validDirectoryBackup && !xpoCreateDatabaseAndSchema) { _backupDatabaseTimeSpan = TimeSpan.Parse(GlobalFramework.PreferenceParameters["DATABASE_BACKUP_TIMESPAN"]); _databaseBackupTimeSpanRangeStart = TimeSpan.Parse(GlobalFramework.PreferenceParameters["DATABASE_BACKUP_TIME_SPAN_RANGE_START"]); _databaseBackupTimeSpanRangeEnd = TimeSpan.Parse(GlobalFramework.PreferenceParameters["DATABASE_BACKUP_TIME_SPAN_RANGE_END"]); StartBackupTimer(); } //Send To Log _log.Debug(string.Format("ProductVersion: [{0}], ImageRuntimeVersion: [{1}], IsLicensed: [{2}]", FrameworkUtils.ProductVersion, FrameworkUtils.ProductAssembly.ImageRuntimeVersion, LicenceManagement.IsLicensed)); //Audit FrameworkUtils.Audit("APP_START", string.Format("{0} {1} clr {2}", SettingsApp.AppName, FrameworkUtils.ProductVersion, FrameworkUtils.ProductAssembly.ImageRuntimeVersion)); if (databaseCreated) { FrameworkUtils.Audit("DATABASE_CREATE"); } // Plugin Errors Messages if (GlobalFramework.PluginSoftwareVendor == null || !GlobalFramework.PluginSoftwareVendor.IsValidSecretKey(SettingsApp.SecretKey)) { Utils.ShowMessageTouch(GlobalApp.WindowStartup, DialogFlags.Modal, new Size(650, 380), MessageType.Error, ButtonsType.Ok, Resx.global_error, Resx.dialog_message_error_plugin_softwarevendor_not_registered); _log.Debug(String.Format("Wrong key detected [{0}]. Use a valid LogicposFinantialLibrary with same key as SoftwareVendorPlugin", SettingsApp.SecretKey)); } //Create SystemNotification FrameworkUtils.SystemNotification(); //Clean Documents Folder on New Database, else we have Document files that dont correspond to Database if (databaseCreated && Directory.Exists(GlobalFramework.Path["documents"].ToString())) { string documentsFolder = GlobalFramework.Path["documents"].ToString(); System.IO.DirectoryInfo di = new DirectoryInfo(documentsFolder); if (di.GetFiles().Length > 0) { _log.Debug(string.Format("New database created. Start Delete [{0}] document(s) from [{1}] folder!", di.GetFiles().Length, documentsFolder)); foreach (FileInfo file in di.GetFiles()) { try { file.Delete(); } catch (Exception) { _log.Error(string.Format("Error! Cant delete Document file : [{0}]", file.Name)); } } } } } catch (Exception ex) { _log.Error(ex.Message, ex); } }
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //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); }
private static bool SystemPrintInsert(FIN_DocumentFinanceMaster pDocumentFinanceMaster, FIN_DocumentFinancePayment pDocumentFinancePayment, string pPrinterDesignation, int pPrintCopies, List <int> pCopyNames, bool pSecondPrint, string pPrintMotive, SYS_UserDetail pUserDetail, POS_ConfigurationPlaceTerminal pConfigurationPlaceTerminal) { bool result = false; try { //Start UnitOfWork using (UnitOfWork uowSession = new UnitOfWork()) { string designation = String.Empty; //Get Objects into Current UOW Session SYS_UserDetail userDetail = (SYS_UserDetail)FrameworkUtils.GetXPGuidObject(uowSession, typeof(SYS_UserDetail), pUserDetail.Oid); POS_ConfigurationPlaceTerminal configurationPlaceTerminal = (POS_ConfigurationPlaceTerminal)FrameworkUtils.GetXPGuidObject(uowSession, typeof(POS_ConfigurationPlaceTerminal), pConfigurationPlaceTerminal.Oid); //Convert CopyNames List to Comma Delimited String string copyNamesCommaDelimited = CustomReport.CopyNamesCommaDelimited(pCopyNames); //SystemPrint SYS_SystemPrint systemPrint = new SYS_SystemPrint(uowSession) { Date = FrameworkUtils.CurrentDateTimeAtomic(), Designation = designation, PrintCopies = pPrintCopies, CopyNames = copyNamesCommaDelimited, SecondPrint = pSecondPrint, UserDetail = userDetail, Terminal = configurationPlaceTerminal }; if (pPrintMotive != String.Empty) { systemPrint.PrintMotive = pPrintMotive; } //Mode: DocumentFinanceMaster if (pDocumentFinanceMaster != null) { FIN_DocumentFinanceMaster documentFinanceMaster = (FIN_DocumentFinanceMaster)FrameworkUtils.GetXPGuidObject(uowSession, typeof(FIN_DocumentFinanceMaster), pDocumentFinanceMaster.Oid); systemPrint.DocumentMaster = documentFinanceMaster; designation = string.Format("{0} {1} : {2}", Resx.global_printed, documentFinanceMaster.DocumentType.Designation, documentFinanceMaster.DocumentNumber); //Update DocumentFinanceMaster if (!documentFinanceMaster.Printed) { documentFinanceMaster.Printed = true; } } //Mode: DocumentFinancePayment if (pDocumentFinancePayment != null) { FIN_DocumentFinancePayment documentFinancePayment = (FIN_DocumentFinancePayment)FrameworkUtils.GetXPGuidObject(uowSession, typeof(FIN_DocumentFinancePayment), pDocumentFinancePayment.Oid); systemPrint.DocumentPayment = documentFinancePayment; designation = string.Format("{0} {1} : {2}", Resx.global_printed, documentFinancePayment.DocumentType.Designation, documentFinancePayment.PaymentRefNo); } systemPrint.Designation = designation; try { //Commit UOW Changes : Before get current OrderMain uowSession.CommitChanges(); //Audit FrameworkUtils.Audit("SYSTEM_PRINT_FINANCE_DOCUMENT", designation); result = true; } catch (Exception ex) { _log.Error(ex.Message, ex); uowSession.RollbackTransaction(); } } } catch (Exception ex) { _log.Error(ex.Message, ex); } return(result); }
public static bool Restore(Window pSourceWindow, DataBaseRestoreFrom pRestoreFrom) { try { //FrameworkUtils.ShowWaitingCursor(); Init(); bool restoreResult = false; string sql = string.Empty; string fileName = string.Empty; string fileNamePacked = string.Empty; //default pathBackups from Settings, can be Overrided in ChooseFromFilePickerDialog Mode string pathBackups = _pathBackups; DataBaseBackupFileInfo fileInfo = null; Guid systemBackupGuid = Guid.Empty; //Required to assign current FileName and FileNamePacked after restore, else name will be the TempName ex acegvpls.soj & n2sjiamk.32o sys_systembackup systemBackup = null; string currentFileName = string.Empty, currentFileNamePacked = string.Empty, currentFilePath = string.Empty, currentFileHash = string.Empty; sys_userdetail currentUserDetail = null; switch (pRestoreFrom) { case DataBaseRestoreFrom.SystemBackup: fileInfo = GetSelectRecordFileName(pSourceWindow); //Equal to Filename not FileNamePacked fileNamePacked = fileInfo.FileNamePacked; if (_debug) { _log.Debug(string.Format("RestoreBackup: FileNamePacked:[{0}], FileHashDB:[{1}], FileHashFile:[{2}] FileHashValid:[{3}]", fileInfo.FileNamePacked, fileInfo.FileHashDB, fileInfo.FileHashFile, fileInfo.FileHashValid)); } if (fileInfo.Response != ResponseType.Cancel && !fileInfo.FileHashValid) { //#EQUAL#1 string message = string.Format(resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "dialog_message_database_restore_error_invalid_backup_file"), fileNamePacked); Utils.ShowMessageTouch(pSourceWindow, DialogFlags.Modal, new Size(600, 300), MessageType.Error, ButtonsType.Ok, resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "global_error"), message); return(false); } break; case DataBaseRestoreFrom.ChooseFromFilePickerDialog: FileFilter fileFilterBackups = Utils.GetFileFilterBackups(); PosFilePickerDialog dialog = new PosFilePickerDialog(pSourceWindow, DialogFlags.DestroyWithParent, fileFilterBackups, FileChooserAction.Open); ResponseType response = (ResponseType)dialog.Run(); if (response == ResponseType.Ok) { fileNamePacked = dialog.FilePicker.Filename; //Override Default pathBackups pathBackups = string.Format("{0}/", Path.GetDirectoryName(fileNamePacked)); dialog.Destroy(); } else { /* IN009164 */ dialog.Destroy(); return(false); } break; default: break; } if (GlobalFramework.DatabaseType != DatabaseType.MSSqlServer) { fileName = Path.ChangeExtension(fileNamePacked, _fileExtension); } else { //Require to assign filename and packed filename from fileInfo fileName = fileInfo.FileName; fileNamePacked = fileInfo.FileName; } if (fileName != string.Empty) { if (_debug) { _log.Debug(string.Format("Restore Filename:[{0}] to pathBackups[{1}]", fileNamePacked, pathBackups)); } if (GlobalFramework.DatabaseType != DatabaseType.MSSqlServer) { // Old Method before PluginSoftwareVendor Implementation //restoreResult = Utils.ZipUnPack(fileNamePacked, pathBackups, true); restoreResult = GlobalFramework.PluginSoftwareVendor.RestoreBackup(SettingsApp.SecretKey, fileNamePacked, pathBackups, true); if (_debug) { _log.Debug(string.Format("RestoreBackup: unpackResult:[{0}]", restoreResult)); } } if (restoreResult || GlobalFramework.DatabaseType == DatabaseType.MSSqlServer) { //Get properties from SystemBackup Object before Restore, to Assign Properties after Restore (FilePath,FileHash,User,Terminal) sql = string.Format("SELECT Oid FROM sys_systembackup WHERE fileNamePacked = '{0}';", Path.GetFileName(fileNamePacked)); systemBackupGuid = FrameworkUtils.GetGuidFromQuery(sql); if (systemBackupGuid != Guid.Empty) { systemBackup = (sys_systembackup)FrameworkUtils.GetXPGuidObject(GlobalFramework.SessionXpo, typeof(sys_systembackup), systemBackupGuid); currentFileName = systemBackup.FileName; currentFileNamePacked = systemBackup.FileNamePacked; currentFilePath = systemBackup.FilePath; currentFileHash = systemBackup.FileHash; currentUserDetail = systemBackup.User; } //Send fileNamePacked only to show its name in success dialog if (Restore(pSourceWindow, fileName, fileNamePacked, systemBackup)) { //Audit DATABASE_RESTORE FrameworkUtils.Audit("DATABASE_RESTORE", string.Format(resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "audit_message_database_restore"), fileNamePacked)); //Required to DropIdentity before get currentDocumentFinanceYear Object, else it exists in old non restored Session GlobalFramework.SessionXpo.DropIdentityMap(); //Get Current Active FinanceYear fin_documentfinanceyears currentDocumentFinanceYear = ProcessFinanceDocumentSeries.GetCurrentDocumentFinanceYear(); //Disable all Active FinanceYear Series and SeriesTerminal if Exists if (currentDocumentFinanceYear != null) { ProcessFinanceDocumentSeries.DisableActiveYearSeriesAndTerminalSeries(currentDocumentFinanceYear); } //Restore SystemBackup properties else it keeps temp names after Restore acegvpls.soj & n2sjiamk.32o, empty hash etc if (systemBackupGuid != Guid.Empty) { //ReFresh UserDetail from Repository currentUserDetail = (currentUserDetail != null) ? (sys_userdetail)FrameworkUtils.GetXPGuidObject(GlobalFramework.SessionXpo, typeof(sys_userdetail), currentUserDetail.Oid) : null; //Get Current Restored systemBackup Object systemBackup = (sys_systembackup)FrameworkUtils.GetXPGuidObject(GlobalFramework.SessionXpo, typeof(sys_systembackup), systemBackupGuid); systemBackup.FileName = currentFileName; systemBackup.FileNamePacked = currentFileNamePacked; systemBackup.FilePath = currentFilePath; systemBackup.FileHash = currentFileHash; systemBackup.User = currentUserDetail; systemBackup.Save(); } //If Cant get Record, because works on ChooseFromFilePickerDialog, we must recreate Record from file, only in the case of record with miss fileNamePacked else { sql = "DELETE FROM sys_systembackup WHERE FilePath IS NULL AND FileHash IS NULL AND User IS NULL;"; GlobalFramework.SessionXpo.ExecuteNonQuery(sql); } //Audit FrameworkUtils.Audit("APP_CLOSE"); //Call QuitWithoutConfirmation without Audit LogicPos.QuitWithoutConfirmation(false); return(true); } else { return(false); } } else { //#EQUAL#1 string message = string.Format(resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "dialog_message_database_restore_error_invalid_backup_file"), fileNamePacked); Utils.ShowMessageTouch(pSourceWindow, DialogFlags.Modal, new Size(600, 300), MessageType.Error, ButtonsType.Ok, resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "global_error"), message); return(false); } } else { return(false); } } catch (Exception ex) { _log.Error(ex.Message, ex); return(false); } finally { //FrameworkUtils.HideWaitingCursor(); } }
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //Logic public bool ProcessPassword(Window pSourceWindow, sys_userdetail pUserDetail) { bool result = false; try { switch (_mode) { case NumberPadPinMode.Password: //Valid User if (ValidatePassword(pUserDetail)) { //Start Application ProcessLogin(pUserDetail); //Finish Job usefull to PosPinDialog send Respond(ResponseType.Ok) when Done result = true; } break; case NumberPadPinMode.PasswordOld: //Valid User if (ValidatePassword(pUserDetail)) { _mode = NumberPadPinMode.PasswordNew; UpdateStatusLabels(); } break; case NumberPadPinMode.PasswordNew: //Check If New Password is Equal to Old Password using ValidatePassword if (CryptographyUtils.SaltedString.ValidateSaltedString(pUserDetail.AccessPin, _entryPin.Text)) { //Show Error Message ResponseType responseType = Utils.ShowMessageTouch(pSourceWindow, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "window_title_dialog_change_password"), resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "pos_pinpad_message_password_equal_error")); ClearEntryPinStatusMessage(true); } else { _passwordNew = _entryPin.Text; _mode = NumberPadPinMode.PasswordNewConfirm; UpdateStatusLabels(); } break; case NumberPadPinMode.PasswordNewConfirm: if (_passwordNew == _entryPin.Text) { //Commit Changes pUserDetail.AccessPin = CryptographyUtils.SaltedString.GenerateSaltedString(_passwordNew); pUserDetail.PasswordReset = false; pUserDetail.PasswordResetDate = FrameworkUtils.CurrentDateTimeAtomic(); pUserDetail.Save(); FrameworkUtils.Audit("USER_CHANGE_PASSWORD", string.Format(resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "audit_message_user_change_password"), pUserDetail.Name)); ResponseType responseType = Utils.ShowMessageTouch(pSourceWindow, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "window_title_dialog_change_password"), resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "pos_pinpad_message_password_changed")); //Start Application ProcessLogin(pUserDetail); //Finish Job usefull to PosPinDialog send Respond(ResponseType.Ok) when Done result = true; } else { //Show Error Message ResponseType responseType = Utils.ShowMessageTouch(pSourceWindow, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "window_title_dialog_change_password"), resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "pos_pinpad_message_password_confirmation_error")); ClearEntryPinStatusMessage(true); //Return to _mode = NumberPadPinMode.PasswordNew; UpdateStatusLabels(); //Reset passwordNew _passwordNew = string.Empty; } break; case NumberPadPinMode.PasswordReset: //Valid User if (ValidatePassword(pUserDetail)) { _mode = NumberPadPinMode.PasswordNew; UpdateStatusLabels(); } //Return to default request password mode else { _mode = NumberPadPinMode.Password; } break; default: break; } //Always focus Entry _entryPin.GrabFocus(); } catch (Exception ex) { _log.Error(ex.Message, ex); } return(result); }
//Delete void _buttonKeyDelete_Clicked(object sender, EventArgs e) { if (_listMode == TicketListMode.OrderMain) { ResponseType responseType = Utils.ShowMessageTouch(_sourceWindow, DialogFlags.Modal, new System.Drawing.Size(400, 280), MessageType.Question, ButtonsType.YesNo, string.Format(resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "global_warning"), GlobalFramework.ServerVersion), resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "dialog_message__pos_order_cancel")); if (responseType == ResponseType.Yes) { try { _listStoreModel.Clear(); _listStoreModelSelectedIndex = -1; _listStoreModelTotalItems = 0; //Get Reference to current OrderMain OrderMain orderMain = GlobalFramework.SessionApp.OrdersMain[GlobalFramework.SessionApp.CurrentOrderMainOid]; fin_documentordermain documentOrderMain = null; //Get current OrderMain Article Bag, After Process Payment/PartialPayment to check if current OrderMain has Items, or is Empty ArticleBag pParameters = ArticleBag.TicketOrderToArticleBag(orderMain); //Start UnitOfWork using (UnitOfWork uowSession = new UnitOfWork()) { if (pParameters.Count > 0) { // Warning required to check if (documentOrderMain != null), when we work with SplitPayments and work only one product, // the 2,3,4....orders are null, this is because first FinanceDocument Closes Order //Close OrderMain //if (documentOrderMain != null) documentOrderMain.OrderStatus = OrderStatus.Close; //Required to Update and Sync Terminals //if (documentOrderMain != null) documentOrderMain.UpdatedAt = documentDateTime; //Change Table Status to Free pos_configurationplacetable placeTable; placeTable = (pos_configurationplacetable)FrameworkUtils.GetXPGuidObject(GlobalFramework.SessionXpo, typeof(pos_configurationplacetable), orderMain.Table.Oid); documentOrderMain = (fin_documentordermain)uowSession.GetObjectByKey(typeof(fin_documentordermain), orderMain.PersistentOid); placeTable.TableStatus = TableStatus.Free; FrameworkUtils.Audit("TABLE_OPEN", string.Format(resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "audit_message_table_open"), placeTable.Designation)); placeTable.DateTableClosed = DateTime.Now; placeTable.TotalOpen = 0; placeTable.Save(); //Required to Reload Objects after has been changed in Another Session(uowSession) if (documentOrderMain != null) { documentOrderMain = (fin_documentordermain)FrameworkUtils.GetXPGuidObject(GlobalFramework.SessionXpo, typeof(fin_documentordermain), orderMain.PersistentOid); documentOrderMain.OrderStatus = OrderStatus.Close; documentOrderMain.Save(); } if (documentOrderMain != null) { documentOrderMain.Reload(); } //aceTable = (pos_configurationplacetable)FrameworkUtils.GetXPGuidObject(GlobalFramework.SessionXpo, typeof(pos_configurationplacetable), orderMain.Table.Oid); //placeTable.Reload(); ArticleBag.TicketOrderToArticleBag(orderMain).Clear(); //Clean Session if Commited without problems orderMain.OrderStatus = OrderStatus.Close; orderMain.CleanSessionOrder(); GlobalFramework.SessionApp.OrdersMain[GlobalFramework.SessionApp.CurrentOrderMainOid] = orderMain; GlobalFramework.SessionApp.DeleteEmptyTickets(); //obalFramework.SessionApp.OrdersMain[GlobalFramework.SessionApp.CurrentOrderMainOid].CleanSessionOrder(); uowSession.CommitChanges(); } } //PartialPayment Detected //else //{ // //Required to Update and Sync Terminals // if (documentOrderMain != null) documentOrderMain.UpdatedAt = documentDateTime; //} //Remove from SessionApp //_currentOrderDetails.Delete(_listStoreModelSelectedIndex); //Remove from TreviewModel //_listStoreModel.Remove(ref _treeIter); //Get Reference to current OrderMain CurrentOrderDetails = orderMain.OrderTickets[orderMain.CurrentTicketId].OrderDetails; //Always Change to OrderMain ListMode before Update Model _listMode = TicketListMode.Ticket; orderMain.CleanSessionOrder(); Gdk.Color colorListMode = (_listMode == TicketListMode.Ticket) ? colorListMode = Utils.ColorToGdkColor(_colorPosTicketListModeTicketBackground) : colorListMode = Utils.ColorToGdkColor(_colorPosTicketListModeOrderMainBackground); _treeView.ModifyBase(StateType.Normal, colorListMode); //UpdateModel(); UpdateOrderStatusBar(); UpdateTicketListOrderButtons(); //IMPORTANT & REQUIRED: Assign Current Order Details from New CurrentTicketId, ELSE we cant add items to OrderMain CurrentOrderDetails = orderMain.OrderTickets[orderMain.CurrentTicketId].OrderDetails; } catch (Exception ex) { _log.Error(ex.Message, ex); } } } else { DeleteItem_Event(TicketListDeleteMode.Delete); } }
public static bool Backup(Window pSourceWindow) { bool backupResult = true; string fileName = string.Empty; string fullFileNamePacked = string.Empty; string fileHash = string.Empty; Thread thread; try { //FrameworkUtils.ShowWaitingCursor(); Init(); //Initialize object before start Actions, to allocate database (automatic backups) and assign CreatedAt, this way next Terminal Skip Backup when trigger backup event SYS_SystemBackup systemBackup = new SYS_SystemBackup(GlobalFramework.SessionXpo) { FileName = Path.GetRandomFileName(), FileNamePacked = Path.GetRandomFileName(), DataBaseType = GlobalFramework.DatabaseType, Version = FrameworkUtils.GetNextTableFieldID("SYS_SystemBackup", "Version", false), Terminal = (POS_ConfigurationPlaceTerminal)GlobalFramework.SessionXpo.GetObjectByKey(typeof(POS_ConfigurationPlaceTerminal), GlobalFramework.LoggedTerminal.Oid) }; systemBackup.Save(); switch (GlobalFramework.DatabaseType) { case DatabaseType.MonoLite: case DatabaseType.SQLite: fileName = GetBackupFileName(_fileExtension, systemBackup.Version); //Non Thread //resultBackup = BackupSQLite(fileName); //Thread thread = new Thread(() => backupResult = BackupSQLite(fileName)); Utils.ThreadStart(pSourceWindow, thread); break; case DatabaseType.MSSqlServer: fileName = GetBackupFileName(_fileExtension, systemBackup.Version); //Non Thread //resultBackup = BackupMSSqlServer(fileName); //Thread thread = new Thread(() => backupResult = BackupMSSqlServer(fileName)); Utils.ThreadStart(pSourceWindow, thread); break; case DatabaseType.MySql: fileName = GetBackupFileName(_fileExtension, systemBackup.Version); //Non Thread //resultBackup = BackupMySql(_backupConnectionString, fileName); //Thread thread = new Thread(() => backupResult = BackupMySql(_backupConnectionString, fileName)); Utils.ThreadStart(pSourceWindow, thread); break; default: break; } if (_debug) { _log.Debug(string.Format("Backup DatabaseType: [{0}] to FileName: [{1}], resultBackup:[{2}]", GlobalFramework.DatabaseType, fileName, backupResult)); } if (backupResult) { //Update SystemBackup after Backup systemBackup.FileName = Path.GetFileName(fileName); systemBackup.FilePath = Path.GetDirectoryName(fileName); //Extra Protection for System Automatic Backups, with unlogged users SYS_UserDetail userDetail = (GlobalFramework.LoggedUser != null) ? (SYS_UserDetail)GlobalFramework.SessionXpo.GetObjectByKey(typeof(SYS_UserDetail), GlobalFramework.LoggedUser.Oid) : null; if (userDetail != null) { systemBackup.User = userDetail; } //Non MSSqlServer Work: Cant Get Remote File Sizes, Hash etc from LPDev Backups if (GlobalFramework.DatabaseType != DatabaseType.MSSqlServer) { //systemBackup.FileSize = new FileInfo(fileName).Length; systemBackup.FileNamePacked = Path.ChangeExtension(systemBackup.FileName, SettingsApp.BackupExtension); //Compress File : Required OSSlash fullFileNamePacked = FrameworkUtils.OSSlash(string.Format(@"{0}\{1}", systemBackup.FilePath, systemBackup.FileNamePacked)); // Old Method before PluginSoftwareVendor Implementation //backupResult = Utils.ZipPack(new string[] { fileName }, fullFileNamePacked); backupResult = GlobalFramework.PluginSoftwareVendor.BackupDatabase(SettingsApp.SecretKey, new string[] { fileName }, fullFileNamePacked); // Add FileHash if (backupResult) { systemBackup.FileHash = FrameworkUtils.MD5HashFile(fullFileNamePacked); } } //MSSqlServer else { //Must Assign FileName to FileNamePacked else next backup violate iFileNamePacked_SystemBackup Index systemBackup.FileNamePacked = systemBackup.FileName; } if (backupResult) { //Commit Object systemBackup.Save(); //Remove Temporary Backup try { if (File.Exists(fileName)) { File.Delete(fileName); } } catch (Exception ex) { _log.Error(ex.Message, ex); } //Post Backup FrameworkUtils.Audit("DATABASE_BACKUP", string.Format(Resx.audit_message_database_backup, (fullFileNamePacked != string.Empty) ? fullFileNamePacked : systemBackup.FileNamePacked )); //Moved to Thread Outside > Only Show if not in Silence Mode if (pSourceWindow != null) { Utils.ShowMessageTouch(pSourceWindow, DialogFlags.Modal, _sizeDialog, MessageType.Info, ButtonsType.Close, Resx.global_information, string.Format(Resx.dialog_message_database_backup_successfully, fullFileNamePacked)); } } else { //On Error Delete Object form Database, this way we dont have a invalid Backup systemBackup.Delete(); } } else { //Moved to Thread Outside > Only Show if not in Silence Mode if (pSourceWindow != null) { Utils.ShowMessageTouch(pSourceWindow, DialogFlags.Modal, _sizeDialog, MessageType.Error, ButtonsType.Close, Resx.global_error, string.Format(Resx.dialog_message_database_backup_error, fullFileNamePacked)); } } } catch (Exception ex) { _log.Error(ex.Message, ex); } finally { //FrameworkUtils.HideWaitingCursor(); } return(backupResult); }
public static bool Add(Session pSession, ProcessArticleStockMode pMode, FIN_DocumentFinanceDetail pDocumentDetail, ERP_Customer pCustomer, int pOrd, DateTime pDocumentDate, string pDocumentNumber, FIN_Article pArticle, decimal pQuantity, string pNotes) { //Log4Net log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); bool result = false; decimal quantity = 0.0m; try { switch (pMode) { case ProcessArticleStockMode.Out: quantity = -(pQuantity); break; case ProcessArticleStockMode.In: quantity = pQuantity; break; } //Get Objects in same Session ERP_Customer customer = (ERP_Customer)pSession.GetObjectByKey(typeof(ERP_Customer), pCustomer.Oid); FIN_Article article = (FIN_Article)pSession.GetObjectByKey(typeof(FIN_Article), pArticle.Oid); POS_ConfigurationPlaceTerminal terminal = (POS_ConfigurationPlaceTerminal)pSession.GetObjectByKey(typeof(POS_ConfigurationPlaceTerminal), GlobalFramework.LoggedTerminal.Oid); SYS_UserDetail userDetail = (SYS_UserDetail)pSession.GetObjectByKey(typeof(SYS_UserDetail), GlobalFramework.LoggedUser.Oid); FIN_ArticleStock articleStock = new FIN_ArticleStock(pSession) { Customer = customer, Date = pDocumentDate, Article = article, Quantity = quantity, Notes = pNotes, CreatedWhere = terminal, CreatedBy = userDetail }; if (pDocumentNumber != string.Empty) { articleStock.DocumentNumber = pDocumentNumber; } if (pDocumentDetail != null) { articleStock.DocumentNumber = pDocumentDetail.DocumentMaster.DocumentNumber; articleStock.DocumentMaster = pDocumentDetail.DocumentMaster; articleStock.DocumentDetail = pDocumentDetail; } //Only saves if not Working on a Unit Of Work Transaction if (pSession.GetType() != typeof(UnitOfWork)) { articleStock.Save(); } //Audit switch (pMode) { case ProcessArticleStockMode.Out: FrameworkUtils.Audit("STOCK_MOVEMENT_OUT", string.Format(Resx.audit_message_stock_movement_out, article.Designation, FrameworkUtils.DecimalToString(quantity, SettingsApp.DecimalFormatStockQuantity))); break; case ProcessArticleStockMode.In: FrameworkUtils.Audit("STOCK_MOVEMENT_IN", string.Format(Resx.audit_message_stock_movement_in, article.Designation, FrameworkUtils.DecimalToString(quantity, SettingsApp.DecimalFormatStockQuantity))); break; } result = true; } catch (Exception ex) { log.Error(ex.Message, ex); } return(result); }
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //Used to Remove Articles from DocumentOrder ex when we Delete Article From TicketList.OrderMain Details public decimal DeleteFromDocumentOrder(ArticleBagKey pKey, decimal pRemoveQuantity) { bool isDone = false; decimal resultRemainQuantity = 0; string where = string.Empty; //Store Reference to Future delete Object (After foreach Loop) fin_documentordermain deleteOrderMain = null; fin_documentorderticket deleteOrderTicket = null; fin_documentorderdetail deleteOrderDetail = null; string articleDesignation = string.Empty; //Start UnitOfWork using (UnitOfWork uowSession = new UnitOfWork()) { OrderMain orderMain = GlobalFramework.SessionApp.OrdersMain[GlobalFramework.SessionApp.CurrentOrderMainOid]; fin_documentordermain xDocumentOrderMain = (fin_documentordermain)FrameworkUtils.GetXPGuidObject(uowSession, typeof(fin_documentordermain), orderMain.PersistentOid); if (xDocumentOrderMain != null && xDocumentOrderMain.OrderTicket != null) { foreach (fin_documentorderticket ticket in xDocumentOrderMain.OrderTicket) { foreach (fin_documentorderdetail detail in ticket.OrderDetail) { try { //Check Equal Key if (pKey.ArticleOid == detail.Article.Oid && pKey.Price == detail.Price && pKey.Discount == detail.Discount && pKey.Vat == detail.Vat) { articleDesignation = pKey.Designation; resultRemainQuantity += detail.Quantity; if (!isDone) { detail.Quantity -= pRemoveQuantity; //Assign references to Future Deletes if (detail.Quantity <= 0) { deleteOrderDetail = detail; } isDone = true; } else { where += string.Format(" OR Oid = '{0}'", detail.Oid); } } } catch (Exception ex) { _log.Error(ex.Message, ex); } } } } //Debug //string sql = @"SELECT * FROM fin_documentorderdetail WHERE 1=0{0};"; //_log.Debug(string.Format("Delete(): sql [{0}]", string.Format(sql, where))); //Audit FrameworkUtils.Audit("ORDER_ARTICLE_REMOVED", string.Format( resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "audit_message_order_article_removed"), articleDesignation, 1, resultRemainQuantity - 1, GlobalFramework.LoggedUser.Name ) ); if (isDone) { //Update xDocumentOrderMain UpdatedAt, Required for RealTime Update xDocumentOrderMain.UpdatedAt = FrameworkUtils.CurrentDateTimeAtomic(); //Remove Quantity resultRemainQuantity -= pRemoveQuantity; //Delete Records, OrderMain, OrderTicket and OrderDetails if (deleteOrderDetail != null) { deleteOrderTicket = deleteOrderDetail.OrderTicket; deleteOrderMain = deleteOrderTicket.OrderMain; //Delete Details deleteOrderDetail.Delete(); //Check if OrderTicket in Empty, If so Delete it, its not required anymore if (deleteOrderTicket.OrderDetail.Count <= 0) { deleteOrderTicket.Delete(); } ; //Check if OrderMain in Empty, If so Delete it, its not required anymore if (deleteOrderMain.OrderTicket.Count <= 0) { //Before Delete OrderMain, we must UnAssign DocumentMaster SourceOrderMain else we have a CONSTRAINT ERROR on FK_DocumentFinanceMaster_SourceOrderMain trying to delete used OrderMain string sql = string.Format(@"UPDATE fin_documentfinancemaster SET SourceOrderMain = NULL WHERE SourceOrderMain = '{0}';", deleteOrderMain.Oid); uowSession.ExecuteScalar(sql); //Open Table deleteOrderMain.PlaceTable.TableStatus = TableStatus.Free; //Audit FrameworkUtils.Audit("TABLE_OPEN", string.Format(resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "audit_message_table_open"), deleteOrderMain.PlaceTable.Designation)); //Delete OrderMain deleteOrderMain.Delete(); } ; } ; } ; try { //Commit UOW Changes uowSession.CommitChanges(); //Update OrderMain UpdatedAt, Required to Sync Terminals orderMain.UpdatedAt = FrameworkUtils.CurrentDateTimeAtomic(); //Update ArticleBag Price Properties this[pKey].Quantity = resultRemainQuantity; UpdateKeyProperties(pKey); //SEARCH#001 //Require to Remove PartialPayed Items Quantity return(resultRemainQuantity - FrameworkUtils.GetPartialPaymentPayedItems(uowSession, xDocumentOrderMain.Oid, pKey.ArticleOid)); } catch (Exception ex) { _log.Error(ex.Message, ex); uowSession.RollbackTransaction(); return(-1); } } }
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //Event: touchButtonPosToolbarShowChangeUser void touchButtonPosToolbarShowChangeUserDialog_Clicked(object sender, EventArgs e) { PosChangeUserDialog dialogChangeUser = new PosChangeUserDialog(this, Gtk.DialogFlags.DestroyWithParent); try { string terminalInfo = string.Empty; int responseChangeUser = dialogChangeUser.Run(); if (responseChangeUser == (int)ResponseType.Ok) { //Already logged if (GlobalFramework.SessionApp.LoggedUsers.ContainsKey(dialogChangeUser.UserDetail.Oid)) { GlobalFramework.LoggedUser = (SYS_UserDetail)FrameworkUtils.GetXPGuidObject(typeof(SYS_UserDetail), dialogChangeUser.UserDetail.Oid); GlobalFramework.LoggedUserPermissions = FrameworkUtils.GetUserPermissions(); _ticketList.UpdateTicketListButtons(); FrameworkUtils.Audit("USER_CHANGE", string.Format(Resx.audit_message_user_change, GlobalFramework.LoggedUser.Name)); terminalInfo = string.Format("{0} : {1}", GlobalFramework.LoggedTerminal.Designation, GlobalFramework.LoggedUser.Name); if (_labelTerminalInfo.Text != terminalInfo) { _labelTerminalInfo.Text = terminalInfo; } } //Not Logged, Request Pin Login else { PosPinPadDialog dialogPinPad = new PosPinPadDialog(dialogChangeUser, Gtk.DialogFlags.DestroyWithParent, dialogChangeUser.UserDetail); int responsePinPad = dialogPinPad.Run(); if (responsePinPad == (int)ResponseType.Ok) { if (!GlobalFramework.SessionApp.LoggedUsers.ContainsKey(dialogChangeUser.UserDetail.Oid)) { GlobalFramework.SessionApp.LoggedUsers.Add(dialogChangeUser.UserDetail.Oid, FrameworkUtils.CurrentDateTimeAtomic()); GlobalFramework.SessionApp.Write(); GlobalFramework.LoggedUser = (SYS_UserDetail)FrameworkUtils.GetXPGuidObject(typeof(SYS_UserDetail), dialogChangeUser.UserDetail.Oid); GlobalFramework.LoggedUserPermissions = FrameworkUtils.GetUserPermissions(); _ticketList.UpdateTicketListButtons(); FrameworkUtils.Audit("USER_LOGIN", string.Format(Resx.audit_message_user_login, GlobalFramework.LoggedUser.Name)); terminalInfo = string.Format("{0} : {1}", GlobalFramework.LoggedTerminal.Designation, GlobalFramework.LoggedUser.Name); if (_labelTerminalInfo.Text != terminalInfo) { _labelTerminalInfo.Text = terminalInfo; } //After First time Login ShowNotifications Utils.ShowNotifications(dialogPinPad); } } ; dialogPinPad.Destroy(); } } ; } catch (Exception ex) { _log.Error(ex.Message, ex); } finally { dialogChangeUser.Destroy(); } }
void _touchButtonCashDrawer_Clicked(object sender, EventArgs e) { bool result; //ProcessWorkSessionPeriod.GetSessionPeriodMovementTotalDebug(GlobalFramework.WorkSessionPeriodTerminal, true ); PosCashDrawerDialog dialogCashDrawer = new PosCashDrawerDialog(this, DialogFlags.DestroyWithParent); int response = dialogCashDrawer.Run(); if (response == (int)ResponseType.Ok) { //Get Fresh XPO Objects, Prevent Deleted Object Bug POS_WorkSessionPeriod workSessionPeriodDay = GlobalFramework.SessionXpo.GetObjectByKey <POS_WorkSessionPeriod>(GlobalFramework.WorkSessionPeriodDay.Oid); POS_WorkSessionPeriod workSessionPeriodTerminal; switch (dialogCashDrawer.MovementType.Token) { case "CASHDRAWER_OPEN": //Start Terminal Period result = ProcessWorkSessionPeriod.SessionPeriodOpen(WorkSessionPeriodType.Terminal, dialogCashDrawer.MovementDescription); if (result) { //Update UI GlobalApp.WindowPos.UpdateWorkSessionUI(); GlobalApp.WindowPos.TicketList.UpdateOrderStatusBar(); //Here we already have GlobalFramework.WorkSessionPeriodTerminal, assigned on ProcessWorkSessionPeriod.SessionPeriodStart //Get Fresh XPO Objects, Prevent Deleted Object Bug workSessionPeriodTerminal = GlobalFramework.SessionXpo.GetObjectByKey <POS_WorkSessionPeriod>(GlobalFramework.WorkSessionPeriodTerminal.Oid); result = ProcessWorkSessionMovement.PersistWorkSessionMovement( workSessionPeriodTerminal, dialogCashDrawer.MovementType, GlobalFramework.LoggedUser, GlobalFramework.LoggedTerminal, FrameworkUtils.CurrentDateTimeAtomic(), dialogCashDrawer.MovementAmountMoney, dialogCashDrawer.MovementDescription ); } if (result) { //PrintWorkSessionMovement FrameworkCalls.PrintCashDrawerOpenAndMoneyInOut(dialogCashDrawer, GlobalFramework.LoggedTerminal.Printer, Resx.ticket_title_worksession_terminal_open, 0.0m, dialogCashDrawer.TotalAmountInCashDrawer, dialogCashDrawer.MovementDescription); //Enable UI Buttons When Have Open Session GlobalApp.WindowPos.TouchButtonPosToolbarNewFinanceDocument.Sensitive = true; //Open CashDrawer Utils.ShowMessageTouch(dialogCashDrawer, DialogFlags.Modal, new Size(500, 280), MessageType.Info, ButtonsType.Close, Resx.global_information, Resx.dialog_message_cashdrawer_open_successfully); } else { Utils.ShowMessageTouch(dialogCashDrawer, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, Resx.global_error, Resx.app_error_contact_support); } break; case "CASHDRAWER_CLOSE": //Stop Terminal Period result = ProcessWorkSessionPeriod.SessionPeriodClose(GlobalFramework.WorkSessionPeriodTerminal); if (result) { //Update UI GlobalApp.WindowPos.UpdateWorkSessionUI(); GlobalApp.WindowPos.LabelCurrentTable.Text = Resx.status_message_open_cashdrawer; //Get Fresh XPO Objects, Prevent Deleted Object Bug workSessionPeriodTerminal = GlobalFramework.SessionXpo.GetObjectByKey <POS_WorkSessionPeriod>(GlobalFramework.WorkSessionPeriodTerminal.Oid); //Add CASHDRAWER_CLOSE Movement to Day Period result = ProcessWorkSessionMovement.PersistWorkSessionMovement( workSessionPeriodTerminal, dialogCashDrawer.MovementType, GlobalFramework.LoggedUser, GlobalFramework.LoggedTerminal, FrameworkUtils.CurrentDateTimeAtomic(), dialogCashDrawer.MovementAmountMoney, dialogCashDrawer.MovementDescription ); //PrintWorkSessionMovement FrameworkCalls.PrintWorkSessionMovement(dialogCashDrawer, GlobalFramework.LoggedTerminal.Printer, GlobalFramework.WorkSessionPeriodTerminal); //Enable UI Buttons When Have Open Session GlobalApp.WindowPos.TouchButtonPosToolbarNewFinanceDocument.Sensitive = false; //Show ClosePeriodMessage ShowClosePeriodMessage(dialogCashDrawer, GlobalFramework.WorkSessionPeriodTerminal); } break; case "CASHDRAWER_IN": dialogCashDrawer.TotalAmountInCashDrawer += dialogCashDrawer.MovementAmountMoney; workSessionPeriodTerminal = GlobalFramework.SessionXpo.GetObjectByKey <POS_WorkSessionPeriod>(GlobalFramework.WorkSessionPeriodTerminal.Oid); result = ProcessWorkSessionMovement.PersistWorkSessionMovement( workSessionPeriodTerminal, dialogCashDrawer.MovementType, GlobalFramework.LoggedUser, GlobalFramework.LoggedTerminal, FrameworkUtils.CurrentDateTimeAtomic(), dialogCashDrawer.MovementAmountMoney, dialogCashDrawer.MovementDescription ); if (result) { //PrintCashDrawerOpenAndMoneyInOut FrameworkCalls.PrintCashDrawerOpenAndMoneyInOut(dialogCashDrawer, GlobalFramework.LoggedTerminal.Printer, Resx.ticket_title_worksession_money_in, dialogCashDrawer.MovementAmountMoney, dialogCashDrawer.TotalAmountInCashDrawer, dialogCashDrawer.MovementDescription); //Open CashDrawer PrintRouter.OpenDoor(GlobalFramework.LoggedTerminal.Printer); //Audit FrameworkUtils.Audit("CASHDRAWER_IN", string.Format( Resx.audit_message_cashdrawer_in, FrameworkUtils.DecimalToStringCurrency(dialogCashDrawer.MovementAmountMoney), dialogCashDrawer.MovementDescription) ); //ShowMessage Utils.ShowMessageTouch(dialogCashDrawer, DialogFlags.Modal, new Size(500, 300), MessageType.Info, ButtonsType.Close, Resx.global_information, Resx.dialog_message_operation_successfully); } else { Utils.ShowMessageTouch(dialogCashDrawer, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, Resx.global_error, Resx.app_error_contact_support); } break; //Work with Terminal Session case "CASHDRAWER_OUT": dialogCashDrawer.TotalAmountInCashDrawer -= dialogCashDrawer.MovementAmountMoney; workSessionPeriodTerminal = GlobalFramework.SessionXpo.GetObjectByKey <POS_WorkSessionPeriod>(GlobalFramework.WorkSessionPeriodTerminal.Oid); //In Period Terminal result = ProcessWorkSessionMovement.PersistWorkSessionMovement( workSessionPeriodTerminal, dialogCashDrawer.MovementType, GlobalFramework.LoggedUser, GlobalFramework.LoggedTerminal, FrameworkUtils.CurrentDateTimeAtomic(), -dialogCashDrawer.MovementAmountMoney, dialogCashDrawer.MovementDescription ); if (result) { //PrintCashDrawerOpenAndMoneyInOut FrameworkCalls.PrintCashDrawerOpenAndMoneyInOut(dialogCashDrawer, GlobalFramework.LoggedTerminal.Printer, Resx.ticket_title_worksession_money_out, dialogCashDrawer.MovementAmountMoney, dialogCashDrawer.TotalAmountInCashDrawer, dialogCashDrawer.MovementDescription); //Open CashDrawer PrintRouter.OpenDoor(GlobalFramework.LoggedTerminal.Printer); //Audit FrameworkUtils.Audit("CASHDRAWER_OUT", string.Format( Resx.audit_message_cashdrawer_out, FrameworkUtils.DecimalToStringCurrency(dialogCashDrawer.MovementAmountMoney), dialogCashDrawer.MovementDescription) ); //ShowMessage Utils.ShowMessageTouch(dialogCashDrawer, DialogFlags.Modal, new Size(500, 300), MessageType.Info, ButtonsType.Close, Resx.global_information, Resx.dialog_message_operation_successfully); } else { Utils.ShowMessageTouch(dialogCashDrawer, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, Resx.global_error, Resx.app_error_contact_support); } break; case "CASHDRAWER_MONEY_OUT": break; default: break; } } ; dialogCashDrawer.Destroy(); //TODO: Remove Comments //_log.Debug(string.Format("ProcessWorkSessionPeriod: [{0}]", ProcessWorkSessionPeriod.GetSessionPeriodCashDrawerOpenOrCloseAmount(GlobalFramework.WorkSessionPeriodDay))); //if (GlobalFramework.WorkSessionPeriodDay != null) ProcessWorkSessionPeriod.GetSessionPeriodMovementTotalDebug(GlobalFramework.WorkSessionPeriodDay, true); //if (GlobalFramework.WorkSessionPeriodTerminal != null) ProcessWorkSessionPeriod.GetSessionPeriodMovementTotalDebug(GlobalFramework.WorkSessionPeriodTerminal, true); }
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)); }
public FIN_DocumentOrderTicket FinishOrder(Session pSession, bool pPrintTicket) { //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(Resx.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(); //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 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; 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, //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(); } } ; //Clean Details and Open a New Blank Ticket in Session //Increment Terminal SessionApp CurrentTicketId _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)); }