MainWindow.xaml.cs 129 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.ObjectModel;
  4. using System.ComponentModel;
  5. using System.Diagnostics;
  6. using System.Drawing;
  7. using System.Drawing.Drawing2D;
  8. using System.Drawing.Imaging;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Net.Http;
  12. using System.Reflection;
  13. using System.Runtime.InteropServices;
  14. using System.Threading.Tasks;
  15. using System.Windows;
  16. using System.Windows.Controls;
  17. using System.Windows.Forms;
  18. using System.Windows.Input;
  19. using System.Windows.Interop;
  20. using System.Windows.Media;
  21. using System.Windows.Threading;
  22. using AvalonDock.Layout;
  23. using Comal.Classes;
  24. using Comal.Stores;
  25. using Comal.TaskScheduler.Shared;
  26. using H.Pipes;
  27. using InABox.Clients;
  28. using InABox.Configuration;
  29. using InABox.Core;
  30. using InABox.Database;
  31. using InABox.Database.SQLite;
  32. using InABox.DynamicGrid;
  33. using InABox.Mail;
  34. using InABox.Core.Reports;
  35. using InABox.IPC;
  36. using InABox.Rpc;
  37. using InABox.Scripting;
  38. using InABox.Wpf;
  39. using InABox.Wpf.Console;
  40. using InABox.WPF;
  41. using NAudio.Wave;
  42. using PRS.Shared;
  43. using InABox.WPF.Themes;
  44. using PRSDesktop.Configuration;
  45. using PRSDesktop.Forms;
  46. using PRSServer;
  47. using SharpAvi.Codecs;
  48. using SharpAvi.Output;
  49. using Syncfusion.Windows.Shared;
  50. using Syncfusion.Windows.Tools;
  51. using Syncfusion.Windows.Tools.Controls;
  52. using Activity = Comal.Classes.Activity;
  53. using Application = System.Windows.Application;
  54. using ButtonBase = System.Windows.Controls.Primitives.ButtonBase;
  55. using Color = System.Windows.Media.Color;
  56. using ColorConverter = System.Windows.Media.ColorConverter;
  57. using Control = System.Windows.Controls.Control;
  58. using Image = System.Drawing.Image;
  59. using KeyEventArgs = System.Windows.Input.KeyEventArgs;
  60. using MessageBox = System.Windows.MessageBox;
  61. using Pen = System.Drawing.Pen;
  62. using PixelFormat = System.Drawing.Imaging.PixelFormat;
  63. using Role = Comal.Classes.Role;
  64. using SortDirection = InABox.Core.SortDirection;
  65. using PRSDesktop.Components.Spreadsheet;
  66. using InABox.Wpf.Reports;
  67. using Comal.Classes.SecurityDescriptors;
  68. using System.Threading;
  69. using System.Windows.Data;
  70. using System.Windows.Media.Imaging;
  71. using H.Formatters;
  72. using PRSDesktop.Panels;
  73. using Syncfusion.SfSkinManager;
  74. namespace PRSDesktop;
  75. /// <summary>
  76. /// Interaction logic for Main.xaml
  77. /// </summary>
  78. public partial class MainWindow : IPanelHostControl
  79. {
  80. //private const int WM_LBUTTONDOWN = 0x201;
  81. private static PipeServer<string>? _client;
  82. private IRpcClientTransport? _transport;
  83. private WaveIn? _audio;
  84. private bool _audioMuted;
  85. private MemoryStream? _audioStream;
  86. private readonly Dictionary<DateTime, Stream> _bitmaps = new();
  87. private DesktopConsole? _console;
  88. private Dictionary<DateTime, Tuple<Rectangle, string>> _notes = new();
  89. private DispatcherTimer? _recorder;
  90. private Process? _recordingnotes;
  91. private int _screenheight = 720;
  92. private int _screenleft;
  93. private int _screentop;
  94. private int _screenwidth = 1280;
  95. private readonly Dictionary<Guid, SecondaryWindow> SecondaryWindows = new();
  96. private CoreTable? _timesheets;
  97. private DailyActivityHistory? ActivityHistory;
  98. private readonly List<Control> CurrentModules = new();
  99. private Fluent.RibbonTabItem? CurrentTab;
  100. private Fluent.Button? CurrentButton;
  101. private readonly int FRAMES_PER_SECOND = 10;
  102. private DatabaseType DatabaseType;
  103. private readonly Dictionary<int, int> messages = new();
  104. private readonly DispatcherTimer NotificationsWatchDog;
  105. private DateTime pausestarted = DateTime.MinValue;
  106. private readonly Scheduler scheduler = new() { Interval = new TimeSpan(0, 5, 0) };
  107. // We use a Guid for the StationID rather than an IP or Mac address
  108. // because we want true single-instance restriction. Using either of
  109. // the above allows for two instances on the once machine, and thus
  110. // double-counting in the Heartbeat() function
  111. private Login station = new() { StationID = Guid.NewGuid().ToString() };
  112. private TimeSpan totalpauses = new(0);
  113. private readonly int VIDEO_HEIGHT = 1080;
  114. private readonly int VIDEO_WIDTH = 1920;
  115. private PanelHost PanelHost;
  116. public MainWindow()
  117. {
  118. PanelHost = new PanelHost(this);
  119. NotificationsWatchDog = new DispatcherTimer { IsEnabled = false };
  120. NotificationsWatchDog.Tick += Notifications_Tick;
  121. NotificationsWatchDog.Interval = new TimeSpan(0, 2, 0);
  122. ClientFactory.PushHandlers.AddHandler<Notification>(ReceiveNotification);
  123. ClientFactory.RegisterMailer(EmailType.IMAP, typeof(IMAPMailer));
  124. ClientFactory.RegisterMailer(EmailType.Exchange, typeof(ExchangeMailer));
  125. ClientFactory.OnLog += (type, userid, message, parameters) => Logger.Send(LogType.Information, ClientFactory.UserID, message, parameters);
  126. ClientFactory.OnRequestError += ClientFactory_OnRequestError;
  127. HotKeyManager.Initialize();
  128. HotKeyManager.RegisterHotKey(Key.F1, ShowHelp);
  129. //HotKeyManager.RegisterHotKey(Key.F5, ToggleRecording);
  130. //HotKeyManager.RegisterHotKey(Key.F6, ShowRecordingNotes);
  131. //HotKeyManager.RegisterHotKey(Key.F4, ToggleRecordingAudio);
  132. Logger.Send(LogType.Information, "", "Connecting to server");
  133. var settings = App.DatabaseSettings;
  134. bool dbConnected;
  135. DatabaseType = settings.DatabaseType;
  136. switch (DatabaseType)
  137. {
  138. case DatabaseType.Standalone:
  139. ClientFactory.SetClientType(typeof(LocalClient<>), Platform.Wpf, CoreUtils.GetVersion());
  140. DbFactory.ColorScheme = App.DatabaseSettings.ColorScheme;
  141. DbFactory.Logo = App.DatabaseSettings.Logo;
  142. dbConnected = true;
  143. break;
  144. case DatabaseType.Networked:
  145. if (App.DatabaseSettings.Protocol == SerializerProtocol.RPC)
  146. {
  147. _transport = new RpcClientSocketTransport(App.DatabaseSettings.URLs);
  148. _transport.OnClose += TransportConnectionLost;
  149. _transport.OnException += Transport_OnException;
  150. _transport.OnOpen += Transport_OnOpen; ;
  151. dbConnected = _transport.Connect();
  152. ClientFactory.SetClientType(typeof(RpcClient<>), Platform.Wpf, CoreUtils.GetVersion(),
  153. _transport);
  154. }
  155. else
  156. {
  157. var url = RestClient<User>.Ping(App.DatabaseSettings.URLs, out DatabaseInfo info);
  158. ClientFactory.SetClientType(typeof(RestClient<>), Platform.Wpf, CoreUtils.GetVersion(), url, true);
  159. dbConnected = true;
  160. }
  161. break;
  162. case DatabaseType.Local:
  163. //new RPC stuff (temporary disabled - for enabling when RPC is ready)
  164. var pipename = DatabaseServerProperties.GetPipeName(App.DatabaseSettings.LocalServerName, true);
  165. _transport = new RpcClientPipeTransport(pipename);
  166. _transport.OnClose += TransportConnectionLost;
  167. dbConnected = _transport.Connect();
  168. ClientFactory.SetClientType(typeof(RpcClient<>), Platform.Wpf, CoreUtils.GetVersion(), _transport );
  169. //ClientFactory.SetClientType(typeof(IPCClient<>), Platform.Wpf, CoreUtils.GetVersion(),
  170. // DatabaseServerProperties.GetPipeName(App.DatabaseSettings.LocalServerName, false));
  171. //dbConnected = true;
  172. break;
  173. default:
  174. throw new Exception($"Invalid database type {DatabaseType}");
  175. }
  176. InitializeComponent();
  177. if (!dbConnected)
  178. {
  179. switch (DoConnectionFailed())
  180. {
  181. case ConnectionFailedResult.Quit:
  182. Close();
  183. return;
  184. case ConnectionFailedResult.Restart:
  185. App.ShouldRestart = true;
  186. Close();
  187. return;
  188. case ConnectionFailedResult.Ok:
  189. // Do nothing
  190. break;
  191. }
  192. }
  193. ThemeManager.BaseColor = Colors.CornflowerBlue;
  194. Progress.DisplayImage = PRSDesktop.Resources.splash_small.AsBitmapImage();
  195. try
  196. {
  197. var dbInfo = new Client<User>().Info();
  198. ClientFactory.DatabaseID = dbInfo.DatabaseID;
  199. ThemeManager.BaseColor = (Color)ColorConverter.ConvertFromString(dbInfo.ColorScheme);
  200. if (dbInfo.Logo?.Any() == true)
  201. using (var ms = new MemoryStream(dbInfo.Logo))
  202. {
  203. Progress.DisplayImage = new Bitmap(ms).AsBitmapImage();
  204. }
  205. }
  206. catch
  207. {
  208. }
  209. VideoRecordingStatus.Source = PRSDesktop.Resources.videorecording.AsGrayScale().AsBitmapImage();
  210. AudioRecordingStatus.Source = PRSDesktop.Resources.audiorecording.AsGrayScale().AsBitmapImage();
  211. SecondaryWindowStatus.Source = PRSDesktop.Resources.target.AsGrayScale().AsBitmapImage();
  212. ConsoleStatus.Source = PRSDesktop.Resources.view.AsGrayScale().AsBitmapImage();
  213. SelectTask.Source = PRSDesktop.Resources.uparrow.Invert().AsBitmapImage();
  214. Title = $"{(String.Equals(App.Profile?.ToUpper(), "DEFAULT") ? "PRS Desktop" : App.Profile)} (Release {CoreUtils.GetVersion()})";
  215. Logger.Send(LogType.Information, "", "Checking for updates");
  216. CheckForUpdates();
  217. Exception? startupException = null;
  218. ValidationStatus? loginStatus = null;
  219. Progress.ShowModal("Loading PRS", progress =>
  220. {
  221. DynamicGridUtils.PreviewReport = (t, m) => { ReportUtils.PreviewReport(t, m, false, Security.IsAllowed<CanDesignReports>()); };
  222. DynamicGridUtils.PrintMenu = (e, s, m, p) => { ReportUtils.PrintMenu(e, s, m, Security.IsAllowed<CanDesignReports>(), p); };
  223. ImportFactory.Register(typeof(ExcelImporter<>), "Excel File", "Excel Files (*.xls;*.xlsx;*.xlsm)|*.xls;*.xlsx;*.xlsm");
  224. ImportFactory.Register(typeof(CustomImporter<>), "Custom", "All Files (*.*)|*.*");
  225. FormUtils.Register();
  226. DigitalFormDocumentFactory.Init(
  227. new WpfDigitalFormDocumentHandler(
  228. b => Dispatcher.BeginInvoke(() =>
  229. {
  230. BackgroundUploadStatus.Visibility = b
  231. ? Visibility.Visible
  232. : Visibility.Hidden;
  233. }
  234. ),
  235. () => _transport?.IsConnected() ?? false
  236. )
  237. );
  238. DigitalFormDocumentFactory.Run();
  239. Logger.Send(LogType.Information, "", "Registering Classes");
  240. progress.Report("Registering Classes");
  241. var tasks = new List<Task>
  242. {
  243. Task.Run(() =>
  244. {
  245. CoreUtils.RegisterClasses(typeof(TaskGrid).Assembly);
  246. CoreUtils.RegisterClasses();
  247. ComalUtils.RegisterClasses();
  248. PRSSharedUtils.RegisterClasses();
  249. ReportUtils.RegisterClasses();
  250. ConfigurationUtils.RegisterClasses();
  251. DynamicGridUtils.RegisterClasses();
  252. }),
  253. Task.Run(() =>
  254. {
  255. ScriptDocument.DefaultAssemblies.AddRange(
  256. Assembly.Load("RoslynPad.Roslyn.Windows"),
  257. Assembly.Load("RoslynPad.Editor.Windows"),
  258. typeof(Control).Assembly,
  259. typeof(MessageBox).Assembly,
  260. typeof(SolidColorBrush).Assembly
  261. );
  262. ScriptDocument.Initialize();
  263. }),
  264. Task.Run(() => DatabaseUpdateScripts.RegisterScripts())
  265. };
  266. Task.WaitAll(tasks.ToArray());
  267. Logger.Send(LogType.Information, "", "Configuring Application");
  268. progress.Report("Configuring Application");
  269. RegisterModules(progress);
  270. if (DatabaseType == DatabaseType.Standalone)
  271. {
  272. progress.Report("Starting local database...");
  273. try
  274. {
  275. StartLocalDatabase(progress);
  276. }
  277. catch (Exception err)
  278. {
  279. startupException = new Exception(
  280. string.Format(
  281. "Unable to open database ({0})\n\n{1}\n\n{2}",
  282. App.DatabaseSettings.FileName,
  283. err.Message,
  284. err.StackTrace
  285. )
  286. );
  287. }
  288. }
  289. if (startupException is null && App.DatabaseSettings.Autologin)
  290. {
  291. try
  292. {
  293. Logger.Send(LogType.Information, "", "Logging in");
  294. progress.Report("Logging in");
  295. Dispatcher.Invoke(() =>
  296. {
  297. loginStatus = TryAutoLogin();
  298. });
  299. if(loginStatus == ValidationStatus.VALID)
  300. {
  301. // Do the AfterLogin() here so that we aren't opening and closing progress windows again and again.
  302. AfterLogin(progress);
  303. }
  304. }
  305. catch(Exception e)
  306. {
  307. startupException = e;
  308. }
  309. }
  310. });
  311. if (startupException != null)
  312. {
  313. MessageWindow.ShowError("Error during startup.", startupException);
  314. }
  315. // If the login status is valid, then we've already loaded everything, so we don't here.
  316. if(loginStatus != ValidationStatus.VALID)
  317. {
  318. Logger.Send(LogType.Information, "", "Logging in");
  319. if (DoLogin() == ValidationStatus.VALID)
  320. {
  321. AfterLogin(null);
  322. }
  323. }
  324. ProfileName.Content = App.Profile;
  325. URL.Content = GetDatabaseConnectionDescription();
  326. if (loginStatus == ValidationStatus.VALID && DatabaseType == DatabaseType.Standalone)
  327. {
  328. Progress.ShowModal("Starting Scheduler", progress =>
  329. {
  330. scheduler.Start();
  331. });
  332. }
  333. }
  334. #region Connection Management
  335. private string GetDatabaseConnectionDescription()
  336. {
  337. return DatabaseType switch
  338. {
  339. #if RPC
  340. DatabaseType.Networked => (ClientFactory.Parameters?.FirstOrDefault() as RpcClientSocketTransport)?.Host,
  341. #else
  342. DatabaseType.Networked => ClientFactory.Parameters?.FirstOrDefault() as string,
  343. #endif
  344. DatabaseType.Standalone => App.DatabaseSettings?.FileName,
  345. DatabaseType.Local => App.DatabaseSettings?.LocalServerName,
  346. _ => ""
  347. } ?? "";
  348. }
  349. /// <summary>
  350. /// Reconnect to the server.
  351. /// </summary>
  352. /// <returns><see langword="true"/> if connection was successful.</returns>
  353. private bool Reconnect()
  354. {
  355. if (_transport != null)
  356. {
  357. return _transport.Connect();
  358. }
  359. Logger.Send(LogType.Error, ClientFactory.UserID, "Trying to reconnect without a transport set.");
  360. return true; // Returning true so we don't get stuck in infinite loops in exceptional circumstances.
  361. }
  362. private enum ConnectionFailedResult
  363. {
  364. Quit,
  365. Restart,
  366. Ok
  367. }
  368. /// <summary>
  369. /// To be called when initial connection to the server has failed; asks the user if they want to retry,
  370. /// change the database settings, or simply quit PRS.
  371. /// </summary>
  372. /// <returns>The action to take next.</returns>
  373. /// <exception cref="Exception"></exception>
  374. private ConnectionFailedResult DoConnectionFailed()
  375. {
  376. bool connected = false;
  377. while (!connected)
  378. {
  379. var connectionFailedWindow = new ConnectionFailed();
  380. connectionFailedWindow.ShowDialog();
  381. var reconnect = false;
  382. switch (connectionFailedWindow.Result)
  383. {
  384. case ConnectionFailedWindowResult.OpenDatabaseConfiguration:
  385. var result = ShowDatabaseConfiguration();
  386. switch (result)
  387. {
  388. case DatabaseConfigurationResult.RestartRequired:
  389. var shouldRestart = MessageBox.Show(
  390. "A restart is required to apply these changes. Do you wish to restart now?",
  391. "Restart?",
  392. MessageBoxButton.YesNo);
  393. if (shouldRestart == MessageBoxResult.Yes)
  394. {
  395. return ConnectionFailedResult.Restart;
  396. }
  397. else
  398. {
  399. reconnect = true;
  400. }
  401. break;
  402. case DatabaseConfigurationResult.RestartNotRequired:
  403. reconnect = true;
  404. break;
  405. case DatabaseConfigurationResult.Cancel:
  406. reconnect = true;
  407. break;
  408. default:
  409. throw new Exception($"Invalid enum result {result}");
  410. }
  411. break;
  412. case ConnectionFailedWindowResult.RetryConnection:
  413. reconnect = true;
  414. break;
  415. case ConnectionFailedWindowResult.Quit:
  416. return ConnectionFailedResult.Quit;
  417. default:
  418. throw new Exception($"Invalid enum result {connectionFailedWindow.Result}");
  419. }
  420. if (!reconnect)
  421. {
  422. return ConnectionFailedResult.Quit;
  423. }
  424. connected = Reconnect();
  425. }
  426. return ConnectionFailedResult.Ok;
  427. }
  428. private void Transport_OnOpen(IRpcTransport transport, RpcTransportOpenArgs e)
  429. {
  430. Logger.Send(LogType.Information, ClientFactory.UserID, "Connection opened");
  431. }
  432. private void Transport_OnException(IRpcTransport transport, RpcTransportExceptionArgs e)
  433. {
  434. Logger.Send(LogType.Error, ClientFactory.UserID, $"Error in connection: {CoreUtils.FormatException(e.Exception)}");
  435. }
  436. private void TransportConnectionLost(IRpcTransport transport, RpcTransportCloseArgs e)
  437. {
  438. Logger.Send(LogType.Information, ClientFactory.UserID, "Connection lost");
  439. if (transport is IRpcClientTransport client)
  440. {
  441. Dispatcher.Invoke(() =>
  442. {
  443. var reconnection = new ReconnectionWindow();
  444. var cancellationTokenSource = new CancellationTokenSource();
  445. reconnection.OnCancelled = () => cancellationTokenSource.Cancel();
  446. var ct = cancellationTokenSource.Token;
  447. var work = () =>
  448. {
  449. try
  450. {
  451. DateTime lost = DateTime.Now;
  452. while (!client.IsConnected() && !ct.IsCancellationRequested)
  453. {
  454. try
  455. {
  456. Logger.Send(LogType.Error, ClientFactory.UserID, $"Reconnecting - ({DateTime.Now - lost:hh\\:mm})");
  457. if (client.Connect(ct))
  458. {
  459. break;
  460. }
  461. }
  462. catch (System.Exception e1)
  463. {
  464. Logger.Send(LogType.Error, ClientFactory.UserID, $"Reconnect Failed: {e1.Message}");
  465. // TODO: Remove this suppression
  466. if (e1.Message.StartsWith("The socket is connected, you needn't connect again!"))
  467. {
  468. break;
  469. }
  470. }
  471. }
  472. if (client.IsConnected())
  473. {
  474. Logger.Send(LogType.Information, ClientFactory.UserID, "Reconnected");
  475. ClientFactory.Validate(ClientFactory.SessionID);
  476. Logger.Send(LogType.Information, ClientFactory.UserID, "Validated");
  477. return true;
  478. }
  479. }
  480. catch (Exception e)
  481. {
  482. Logger.Send(LogType.Error, ClientFactory.UserID, $"Reconnect Failed: {e.Message}");
  483. }
  484. return false;
  485. };
  486. var task = Task.Run(() =>
  487. {
  488. var result = work();
  489. Dispatcher.Invoke(() =>
  490. {
  491. reconnection.Close();
  492. });
  493. return result;
  494. }, ct);
  495. reconnection.ShowDialog();
  496. if (!task.Result)
  497. {
  498. Close();
  499. }
  500. });
  501. }
  502. }
  503. #endregion
  504. private bool _loggingOut = false;
  505. private void ClientFactory_OnRequestError(RequestException e)
  506. {
  507. if (e.Status == StatusCode.Unauthenticated)
  508. {
  509. switch (e.Method)
  510. {
  511. case RequestMethod.Query:
  512. case RequestMethod.Save:
  513. case RequestMethod.Delete:
  514. case RequestMethod.MultiQuery:
  515. case RequestMethod.MultiSave:
  516. case RequestMethod.MultiDelete:
  517. if (!_loggingOut)
  518. {
  519. Dispatcher.InvokeAsync(() =>
  520. {
  521. _loggingOut = true;
  522. try
  523. {
  524. Logout(null, true);
  525. }
  526. finally
  527. {
  528. _loggingOut = false;
  529. }
  530. });
  531. }
  532. break;
  533. default:
  534. break;
  535. }
  536. }
  537. }
  538. private void ApplyColorScheme()
  539. {
  540. Color baseColor;
  541. try
  542. {
  543. baseColor = (Color)ColorConverter.ConvertFromString(App.DatabaseSettings.ColorScheme);
  544. }
  545. catch
  546. {
  547. baseColor = Colors.CornflowerBlue;
  548. }
  549. ThemeManager.BaseColor = baseColor;
  550. DynamicGridUtils.SelectionBackground = ThemeManager.SelectionBackgroundBrush;
  551. DynamicGridUtils.SelectionForeground = ThemeManager.SelectionForegroundBrush;
  552. DynamicGridUtils.FilterBackground = ThemeManager.FilterBackgroundBrush;
  553. //_ribbon.Background = new SolidColorBrush(Colors.White);
  554. //_ribbon.BackStageColor = ThemeConverter.GetBrush(ElementType.Ribbon, BrushType.Background);
  555. ////_ribbon.BackStage.Background = ThemeConverter.GetBrush(ElementType.Ribbon, BrushType.Background);
  556. ////_ribbon.BackStage.Foreground = ThemeConverter.GetBrush(ElementType.Ribbon, BrushType.Foreground);
  557. UpdateRibbonColors();
  558. PanelHost.Refresh();
  559. }
  560. #region Configuration
  561. /*
  562. protected override void OnSourceInitialized(EventArgs e)
  563. {
  564. base.OnSourceInitialized(e);
  565. var source = PresentationSource.FromVisual(this) as HwndSource;
  566. source?.AddHook(WndProc);
  567. }
  568. private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
  569. {
  570. var message = (App.Message)msg;
  571. switch (message)
  572. {
  573. case App.Message.Maximise:
  574. WindowState = WindowState.Maximized;
  575. break;
  576. }
  577. return IntPtr.Zero;
  578. }*/
  579. private void ConfigureMainScreen(IProgress<string>? progress)
  580. {
  581. var bMaps = Security.CanView<Equipment>()
  582. || Security.CanView<Job>()
  583. || Security.CanView<TimeSheet>()
  584. || Security.CanView<GPSTracker>();
  585. var sections = new[]
  586. {
  587. new ProgressSection("Configuring Main Screen", SetupMainScreen),
  588. new ProgressSection("Configuring Projects", () => SetupProjectsTab(bMaps)),
  589. new ProgressSection("Configuring Manufacturing", () => SetupManufacturingTab(bMaps)),
  590. new ProgressSection("Configuring Logistics", () => SetupLogisticsTab(bMaps)),
  591. new ProgressSection("Configuring Products", () => SetupProductsTab(bMaps)),
  592. new ProgressSection("Configuring Human Resources", () => SetupHumanResourcesTab(bMaps)),
  593. new ProgressSection("Configuring Accounts", () => SetupAccountsTab(bMaps)),
  594. new ProgressSection("Configuring Equipment", () => SetupEquipmentTab(bMaps)),
  595. new ProgressSection("Configuring DigitalForms", () => SetupDigitalFormsTab(bMaps)),
  596. new ProgressSection("Configuring Dashboards", () => SetupDashboardsTab(bMaps)),
  597. new ProgressSection("Configuring System Modules", SetupSystemModules)
  598. };
  599. if(progress is not null)
  600. {
  601. Dispatcher.Invoke(SetupScreen);
  602. foreach(var section in sections)
  603. {
  604. progress.Report(section.Message);
  605. Dispatcher.Invoke(section.Action);
  606. }
  607. }
  608. else
  609. {
  610. SetupScreen();
  611. Progress.ShowModal(sections);
  612. }
  613. }
  614. private void SetupScreen()
  615. {
  616. var button = _ribbon.FindVisualChildren<Fluent.DropDownButton>().FirstOrDefault();
  617. if (button != null)
  618. button.Visibility = Visibility.Collapsed;
  619. if (ClientFactory.UserGuid == Guid.Empty)
  620. _ribbonRow.Height = new GridLength(30, GridUnitType.Pixel);
  621. else
  622. _ribbonRow.Height = new GridLength(1, GridUnitType.Auto);
  623. }
  624. private void SetupMainScreen()
  625. {
  626. //DockManager.SidePanelSize = OutstandingDailyReports(false) ? 0.00F : 30.00F;
  627. // Notifications Area
  628. SetVisibility(SendNotification, Security.CanView<Notification>());
  629. SetVisibility(Notifications, Security.CanView<Notification>());
  630. SetVisibility(TaskTracking, Security.IsAllowed<CanTrackTasksInDailyReport>());
  631. UserID.Content = ClientFactory.UserID;
  632. if (ClientFactory.PasswordExpiration != DateTime.MinValue)
  633. {
  634. var timeUntilExpiration = ClientFactory.PasswordExpiration - DateTime.Now;
  635. if (timeUntilExpiration.Days < 14)
  636. {
  637. PasswordExpiryNotice.Content = $"Password will expire in {timeUntilExpiration.Days} days!";
  638. PasswordExpiryNotice.Visibility = Visibility.Visible;
  639. }
  640. else
  641. {
  642. PasswordExpiryNotice.Visibility = Visibility.Collapsed;
  643. }
  644. }
  645. }
  646. private void SetupSystemModules()
  647. {
  648. SetVisibility(CompanyInformation, Security.CanView<CompanyInformation>());
  649. SetVisibleIfAny(BackstageSeparator0, CompanyInformation);
  650. SetVisibility(SecurityDefaultsButton,
  651. ClientFactory.IsSupported<GlobalSecurityToken>() && Security.IsAllowed<CanCustomiseSecurityDefaults>());
  652. SetVisibleIfAny(BackstageSeparator1, SecurityDefaultsButton);
  653. BackstageSeparator1a.Visibility = Visibility.Visible;
  654. SystemLogsButton.Visibility = Visibility.Visible;
  655. SetVisibility(DocumentTypeList, ClientFactory.IsSupported<DocumentType>() && Security.IsAllowed<CanViewDocumentTypes>());
  656. SetVisibleIfAny(BackstageSeparator2, DocumentTypeList);
  657. SetVisibility(VideoRecordingButton, Security.IsAllowed<CanRecordScreen>());
  658. LogoutButton.Visibility = ClientFactory.UserGuid == Guid.Empty ? Visibility.Collapsed : Visibility.Visible;
  659. LoginButton.Visibility = ClientFactory.UserGuid != Guid.Empty ? Visibility.Collapsed : Visibility.Visible;
  660. EditDetailsButton.Visibility = ClientFactory.UserGuid == Guid.Empty ? Visibility.Collapsed : Visibility.Visible;
  661. SetupDock<CanViewContactsDock>(ContactDock, Contacts);
  662. SetupDock<CanViewJobDock>(JobDock, Jobs);
  663. SetupDock<CanViewConsignmentDock>(ConsignmentDock, Consignments);
  664. SetupDock<CanViewDeliveryDock>(DeliveryDock, Deliveries);
  665. SetupDock<CanViewProductDock>(ProductLookupDock, ProductLookup);
  666. SetupDock<CanViewDigitalFormsDock>(DigitalFormsDock, DigitalForms);
  667. SetupDock<CanViewRequisitionsDock>(RequisitionsDock, Requisitions);
  668. _ribbon.InvalidateArrange();
  669. }
  670. private void SetupDashboardsTab(bool bMaps)
  671. {
  672. if (!Security.IsAllowed<ViewDesktopDashboardsTab>())
  673. return;
  674. SetVisibility(DashboardsDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  675. SetVisibility(DashboardMessagesButton, Security.CanView<Notification>());
  676. SetVisibility(DashboardsTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  677. SetVisibility(DashboardsAttendanceButton, ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  678. SetVisibility(DashboardsMapButton, bMaps);
  679. SetVisibility(DashboardsDailyReportButton,
  680. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  681. SetVisibility(FactoryProductivityButton,
  682. ClientFactory.IsSupported<ManufacturingHistory>()
  683. && Security.IsAllowed<CanViewFactoryKPIs>()
  684. && Security.IsAllowed<ViewDesktopFactoryKPIsDashboard>());
  685. SetVisibility(TemplateAnalysisButton,
  686. ClientFactory.IsSupported<ManufacturingTemplate, ManufacturingHistory>()
  687. && Security.IsAllowed<CanViewTemplateAnalysis>()
  688. && Security.IsAllowed<ViewDesktopTemplateAnalysisDashboard>());
  689. SetVisibility(FactoryAnalysisButton,
  690. ClientFactory.IsSupported<ManufacturingTemplate, ManufacturingHistory>()
  691. && Security.IsAllowed<CanViewFactoryAnalysis>()
  692. && Security.IsAllowed<ViewDesktopFactoryAnalysisDashboard>());
  693. SetVisibility(DatabaseActivityButton,
  694. ClientFactory.IsSupported<UserTracking>()
  695. && Security.IsAllowed<CanViewDatabaseActivity>()
  696. && Security.IsAllowed<ViewDesktopDatabaseActivityDashboard>());
  697. SetVisibility(UserActivityButton, ClientFactory.IsSupported<ModuleTracking>()
  698. && Security.IsAllowed<CanViewUserActivity>()
  699. && Security.IsAllowed<ViewDesktopUserActivityDashboard>());
  700. SetVisibility(QuickStatusButton, Security.IsAllowed<CanViewQuickStatus>() && Security.IsAllowed<ViewDesktopQuickStatusDashboard>());
  701. SetVisibleIfEither(DashboardsTaskSeparator,
  702. new FrameworkElement[]
  703. {
  704. DashboardsDashboardButton, DashboardMessagesButton, DashboardsTaskButton, DashboardsAttendanceButton,
  705. DashboardsMapButton,
  706. DashboardsDailyReportButton
  707. },
  708. new FrameworkElement[]
  709. {
  710. FactoryProductivityButton, TemplateAnalysisButton, FactoryAnalysisButton, DatabaseActivityButton, UserActivityButton, QuickStatusButton
  711. });
  712. SetVisibleIfAny(DashboardsActions, DashboardsDashboardButton, DashboardMessagesButton, DashboardsTaskButton,
  713. DashboardsAttendanceButton, DashboardsDailyReportButton, FactoryProductivityButton, TemplateAnalysisButton,
  714. FactoryAnalysisButton, DatabaseActivityButton, UserActivityButton, QuickStatusButton);
  715. //DashboardsActions.IsLauncherButtonVisible = Security.IsAllowed<CanCustomiseModules>();
  716. //DashboardsReports.IsLauncherButtonVisible = Security.IsAllowed<CanDesignReports>();
  717. SetVisibleIfAny(DashboardsTab, FactoryProductivityButton, TemplateAnalysisButton, FactoryAnalysisButton,
  718. DatabaseActivityButton,
  719. UserActivityButton, QuickStatusButton);
  720. }
  721. private void SetupDigitalFormsTab(bool bMaps)
  722. {
  723. if (!Security.IsAllowed<ViewDesktopDigitalFormsTab>())
  724. return;
  725. SetVisibility(DigitalFormsDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  726. SetVisibility(DigitalFormsMessagesButton, Security.CanView<Notification>());
  727. SetVisibility(DigitalFormsTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  728. SetVisibility(DigitalFormsAttendanceButton, ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  729. SetVisibility(DigitalFormsMapButton, bMaps);
  730. SetVisibility(DigitalFormsDailyReportButton,
  731. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  732. SetVisibility(DigitalFormsFormsLibraryButton, ClientFactory.IsSupported<DigitalForm>()
  733. && Security.CanView<DigitalForm>()
  734. && Security.IsAllowed<CanAdministerDigitalFormsLibrary>());
  735. SetVisibility(DigitalFormsCompletedFormsButton, Security.IsAllowed<CanViewDigitalFormsDashbaord>() && Security.IsAllowed<ViewDesktopDigitalFormsDashboard>());
  736. SetVisibleIfEither(DigitalFormsTaskSeparator,
  737. new FrameworkElement[]
  738. {
  739. DigitalFormsDashboardButton, DigitalFormsMessagesButton, DigitalFormsTaskButton, DigitalFormsAttendanceButton, DigitalFormsMapButton,
  740. DigitalFormsDailyReportButton
  741. }, new FrameworkElement[] { DigitalFormsFormsLibraryButton, DigitalFormsCompletedFormsButton });
  742. SetVisibleIfAny(DigitalFormsActions, DigitalFormsDashboardButton, DigitalFormsMessagesButton, DigitalFormsTaskButton,
  743. DigitalFormsAttendanceButton, DigitalFormsDailyReportButton, DigitalFormsFormsLibraryButton, DigitalFormsCompletedFormsButton);
  744. SetTabVisibleIfAny(DigitalFormsTab, DigitalFormsFormsLibraryButton, DigitalFormsCompletedFormsButton);
  745. }
  746. private void SetupEquipmentTab(bool bMaps)
  747. {
  748. if (!Security.IsAllowed<ViewDesktopEquipmentTab>())
  749. return;
  750. SetVisibility(EquipmentDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  751. SetVisibility(EquipmentMessagesButton, Security.CanView<Notification>());
  752. SetVisibility(EquipmentTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  753. SetVisibility(EquipmentAttendanceButton, ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  754. SetVisibility(EquipmentMapButton, bMaps);
  755. SetVisibility(EquipmentDailyReportButton,
  756. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  757. SetVisibility(EquipmentButton, ClientFactory.IsSupported<Equipment>()
  758. && Security.CanView<Equipment>()
  759. && Security.IsAllowed<ViewDesktopEquipmentListScreen>());
  760. SetVisibility(EquipmentPlannerButton,
  761. ClientFactory.IsSupported<Equipment>()
  762. && Security.CanView<Equipment>()
  763. && ClientFactory.IsSupported<Assignment>()
  764. && Security.CanView<Assignment>()
  765. && Security.IsAllowed<ViewDesktopEquipmentPlannerScreen>());
  766. SetVisibleIfEither(EquipmentTaskSeparator,
  767. new FrameworkElement[]
  768. {
  769. EquipmentDashboardButton, EquipmentMessagesButton, EquipmentTaskButton, EquipmentAttendanceButton, EquipmentMapButton,
  770. EquipmentDailyReportButton
  771. }, new FrameworkElement[] { EquipmentButton, EquipmentPlannerButton });
  772. SetVisibleIfAny(EquipmentActions, EquipmentDashboardButton, EquipmentMessagesButton, EquipmentTaskButton,
  773. EquipmentAttendanceButton, EquipmentDailyReportButton, EquipmentButton, EquipmentPlannerButton);
  774. SetVisibility(TrackersMasterList, Security.CanView<GPSTracker>() && Security.IsAllowed<ViewDesktopGPSTrackersScreen>());
  775. SetTabVisibleIfAny(EquipmentTab, EquipmentButton, TrackersMasterList);
  776. }
  777. private void SetupAccountsTab(bool bMaps)
  778. {
  779. if (!Security.IsAllowed<ViewDesktopAccountsTab>())
  780. return;
  781. SetVisibility(AccountsDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  782. SetVisibility(AccountsMessagesButton, Security.CanView<Notification>());
  783. SetVisibility(AccountsTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  784. SetVisibility(AccountsAttendanceButton, ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  785. SetVisibility(AccountsMapButton, bMaps);
  786. SetVisibility(AccountsDailyReportButton,
  787. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  788. SetVisibility(CustomerList, ClientFactory.IsSupported<Customer>()
  789. && Security.CanView<Customer>()
  790. && Security.IsAllowed<ViewDesktopCustomersScreen>());
  791. SetVisibility(InvoiceList, ClientFactory.IsSupported<Invoice>()
  792. && Security.CanView<Invoice>()
  793. && Security.IsAllowed<ViewDesktopInvoicesScreen>());
  794. SetVisibility(ReceiptList, ClientFactory.IsSupported<Receipt>()
  795. && Security.CanView<Receipt>()
  796. && Security.IsAllowed<ViewDesktopReceiptsScreen>());
  797. SetVisibility(SupplierList, ClientFactory.IsSupported<Supplier>()
  798. && Security.CanView<Supplier>()
  799. && Security.IsAllowed<ViewDesktopSuppliersScreen>());
  800. SetVisibility(AccountsDataButton, Security.IsAllowed<CanViewDataEntryPanel>());
  801. SetVisibility(PurchasesList, ClientFactory.IsSupported<PurchaseOrder>()
  802. && Security.CanView<PurchaseOrder>()
  803. && Security.IsAllowed<ViewDesktopPurchaseOrdersScreen>());
  804. SetVisibility(BillsList, ClientFactory.IsSupported<Bill>()
  805. && Security.CanView<Bill>()
  806. && Security.IsAllowed<ViewDesktopBillsScreen>());
  807. SetVisibility(PaymentsList, ClientFactory.IsSupported<Payment>()
  808. && Security.CanView<Payment>()
  809. && Security.IsAllowed<ViewDesktopPaymentsScreen>());
  810. SetVisibleIfEither(AccountsTaskSeparator1,
  811. new FrameworkElement[]
  812. {
  813. AccountsDashboardButton, AccountsMessagesButton, AccountsTaskButton, AccountsAttendanceButton, AccountsMapButton,
  814. AccountsDailyReportButton
  815. }, new FrameworkElement[] { CustomerList, InvoiceList, ReceiptList });
  816. SetVisibleIfEither(AccountsTaskSeparator2, new FrameworkElement[] { CustomerList, InvoiceList, ReceiptList },
  817. new FrameworkElement[] { SupplierList, AccountsDataButton, PurchasesList, BillsList, PaymentsList });
  818. SetVisibleIfAny(AccountsActions, AccountsDashboardButton, AccountsMessagesButton, AccountsTaskButton,
  819. AccountsAttendanceButton,
  820. AccountsDailyReportButton, CustomerList, InvoiceList, ReceiptList, SupplierList, PurchasesList, BillsList, PaymentsList);
  821. SetTabVisibleIfAny(AccountsTab, CustomerList, InvoiceList, ReceiptList, SupplierList, AccountsDataButton, PurchasesList, BillsList, PaymentsList);
  822. }
  823. private void SetupHumanResourcesTab(bool bMaps)
  824. {
  825. if (!Security.IsAllowed<ViewDesktopHumanResourcesTab>())
  826. return;
  827. SetVisibility(HumanResourcesDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  828. SetVisibility(HumanResourcesMessagesButton, Security.CanView<Notification>());
  829. SetVisibility(HumanResourcesTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  830. SetVisibility(HumanResourcesAttendanceButton,
  831. ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  832. SetVisibility(HumanResourcesMapButton, bMaps);
  833. SetVisibility(HumanResourcesDailyReportButton,
  834. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  835. SetVisibility(CalendarButton, Security.CanView<Assignment>() && Security.IsAllowed<ViewDesktopCalendarScreen>());
  836. SetVisibility(EmployeePlannerButton, Security.CanView<Assignment>() && Security.IsAllowed<ViewDesktopEmployeePlannerScreen>());
  837. SetVisibility(TimesheetsButton, Security.CanView<TimeSheet>() && Security.IsAllowed<ViewDesktopStaffTimeSheetsScreen>());
  838. SetVisibility(LeaveRequestsButton, Security.CanView<LeaveRequest>() && Security.IsAllowed<ViewDesktopLeaveRequestsScreen>());
  839. SetVisibility(OrgChartButton,
  840. ClientFactory.IsSupported<Employee>()
  841. &&
  842. Security.IsAllowed<ViewDesktopOrgChartScreen>()
  843. );
  844. SetVisibility(MeetingsButton, Security.IsAllowed<ViewDesktopMeetingsScreen>());
  845. SetVisibleIfEither(HumanResourcesTaskSeparator,
  846. new FrameworkElement[]
  847. {
  848. HumanResourcesDashboardButton, HumanResourcesMessagesButton, HumanResourcesTaskButton, HumanResourcesAttendanceButton,
  849. HumanResourcesMapButton, HumanResourcesDailyReportButton
  850. }, new FrameworkElement[] { CalendarButton, EmployeePlannerButton, TimesheetsButton, LeaveRequestsButton, OrgChartButton });
  851. SetVisibleIfAny(HumanResourcesActions, HumanResourcesDashboardButton, HumanResourcesTaskButton,
  852. HumanResourcesAttendanceButton,
  853. HumanResourcesDailyReportButton, CalendarButton, EmployeePlannerButton, TimesheetsButton, LeaveRequestsButton, OrgChartButton);
  854. SetVisibility(UsersButton, Security.CanView<User>() && Security.IsAllowed<ViewDesktopUserAccountsScreen>());
  855. SetVisibility(EmployeesButton, Security.CanView<Employee>() && Security.IsAllowed<ViewDesktopEmployeeListScreen>());
  856. SetVisibleIfEither(HumanResourcesSetupSeparator1,
  857. new FrameworkElement[] { CalendarButton, TimesheetsButton, LeaveRequestsButton, OrgChartButton },
  858. new FrameworkElement[] { UsersButton, EmployeesButton });
  859. SetTabVisibleIfAny(HumanResourcesTab, CalendarButton, TimesheetsButton, LeaveRequestsButton, OrgChartButton, UsersButton, EmployeesButton);
  860. }
  861. private void SetupProductsTab(bool bMaps)
  862. {
  863. if (!Security.IsAllowed<ViewDesktopProductManagementTab>())
  864. return;
  865. SetVisibility(ProductsDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  866. SetVisibility(ProductsMessagesButton, Security.CanView<Notification>());
  867. SetVisibility(ProductsTaskButton, Security.CanView<Kanban>());
  868. SetVisibility(ProductsAttendanceButton, Security.IsAllowed<CanViewInOutBoard>());
  869. SetVisibility(ProductsMapButton, bMaps);
  870. SetVisibility(ProductsDailyReportButton,
  871. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  872. SetVisibility(ProductsMasterList, Security.CanView<Product>() && Security.IsAllowed<ViewDesktopProductListScreen>());
  873. SetVisibility(StockLocationList, Security.CanView<StockLocation>() && Security.IsAllowed<ViewDesktopStockLocationsScreen>());
  874. SetVisibility(StockMovementList, Security.CanView<StockMovement>() && Security.IsAllowed<ViewDesktopStockMovementsScreen>());
  875. SetVisibility(StockForecastButton, Security.CanView<Product>()
  876. && Security.CanView<JobMaterial>()
  877. && Security.IsAllowed<ViewDesktopStockForecastScreen>());
  878. SetVisibility(ReservationManagementButton, Security.IsAllowed<ViewDesktopReservationManagementScreen>());
  879. SetVisibleIfEither(ProductsTaskSeparator,
  880. new FrameworkElement[]
  881. {
  882. ProductsDashboardButton, ProductsMessagesButton, ProductsTaskButton, ProductsAttendanceButton, ProductsMapButton,
  883. ProductsDailyReportButton
  884. }, new FrameworkElement[] { ProductsMasterList, StockLocationList, StockMovementList, StockForecastButton });
  885. SetVisibleIfAny(ProductActions, ProductsMasterList, StockLocationList, StockMovementList, StockForecastButton);
  886. SetTabVisibleIfAny(ProductTab, ProductActions);
  887. }
  888. private void SetupLogisticsTab(bool bMaps)
  889. {
  890. if (!Security.IsAllowed<ViewDesktopLogisticsTab>())
  891. return;
  892. SetVisibility(LogisticsDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  893. SetVisibility(LogisticsMessagesButton, Security.CanView<Notification>());
  894. SetVisibility(LogisticsTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  895. SetVisibility(LogisticsAttendanceButton, ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  896. SetVisibility(LogisticsMapButton, bMaps);
  897. SetVisibility(LogisticsDailyReportButton,
  898. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  899. SetVisibility(ReadyToGoItemsButton,
  900. ClientFactory.IsSupported<DeliveryItem>()
  901. && Security.IsAllowed<CanViewLogisticsReadyToGo>()
  902. && Security.IsAllowed<ViewDesktopReadyToGoScreen>());
  903. SetVisibility(DispatchButton, Security.CanView<Shipment>()
  904. && Security.CanView<DeliveryItem>()
  905. && Security.IsAllowed<ViewDesktopRackListScreen>());
  906. SetVisibility(RequisitionsButton, Security.CanView<Requisition>() && Security.IsAllowed<ViewDesktopSiteRequisitionsScreen>());
  907. SetVisibility(DeliveriesButton, Security.IsAllowed<CanViewDeliveriesModule>() && Security.IsAllowed<ViewDesktopDeliveriesScren>());
  908. SetVisibility(DeliveredItemsButton,
  909. ClientFactory.IsSupported<DeliveryItem>()
  910. && Security.IsAllowed<CanViewDeliveredOnSite>()
  911. && Security.IsAllowed<ViewDesktopDeliveredOnSiteScreen>());
  912. SetVisibility(ConsignmentButton, Security.CanView<Consignment>() && Security.IsAllowed<ViewDesktopIncomingConsignmentsScreen>());
  913. SetVisibleIfEither(LogisticsTaskSeparator1,
  914. new FrameworkElement[]
  915. {
  916. LogisticsDashboardButton, LogisticsMessagesButton, LogisticsTaskButton, LogisticsAttendanceButton, LogisticsMapButton,
  917. LogisticsDailyReportButton
  918. },
  919. new FrameworkElement[]
  920. { ReadyToGoItemsButton, DispatchButton, RequisitionsButton, DeliveriesButton, DeliveredItemsButton });
  921. SetVisibleIfEither(LogisticsTaskSeparator2,
  922. new FrameworkElement[]
  923. { ReadyToGoItemsButton, DispatchButton, RequisitionsButton, DeliveriesButton, DeliveredItemsButton },
  924. new FrameworkElement[] { ConsignmentButton });
  925. SetTabVisibleIfAny(LogisticsTab, DispatchButton, RequisitionsButton, DeliveriesButton, ReadyToGoItemsButton,
  926. DeliveredItemsButton,
  927. ConsignmentButton);
  928. }
  929. private void SetupManufacturingTab(bool bMaps)
  930. {
  931. if (!Security.IsAllowed<ViewDesktopManufacturingTab>())
  932. return;
  933. SetVisibility(ManufacturingDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  934. SetVisibility(ManufacturingMessagesButton, Security.CanView<Notification>());
  935. SetVisibility(ManufacturingTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  936. SetVisibility(ManufacturingAttendanceButton,
  937. ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  938. SetVisibility(ManufacturingMapButton, bMaps);
  939. SetVisibility(ManufacturingDailyReportButton,
  940. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  941. SetVisibleIfAny(ManufacturingTaskSeparator,
  942. new FrameworkElement[]
  943. {
  944. ManufacturingDashboardButton, ManufacturingMessagesButton, ManufacturingTaskButton, ManufacturingAttendanceButton,
  945. ManufacturingMapButton, ManufacturingDailyReportButton
  946. });
  947. SetVisibility(DesignManagementButton, Security.CanView<Job>() && Security.IsAllowed<ViewDesktopDesignManagementScreen>());
  948. SetVisibility(ManufacturingDesignSeparator, Security.CanView<Job>() && Security.IsAllowed<ViewDesktopDesignManagementScreen>());
  949. SetVisibility(FactoryStatusButton,
  950. ClientFactory.IsSupported<ManufacturingFactory, ManufacturingPacket>()
  951. && Security.IsAllowed<CanViewFactoryStatus>()
  952. && Security.IsAllowed<ViewDesktopManufacturingStatusScreen>());
  953. SetVisibility(FactoryAllocationButton,
  954. ClientFactory.IsSupported<ManufacturingFactory, ManufacturingPacket, ManufacturingPacketStage>()
  955. && Security.IsAllowed<CanViewFactoryAllocation>()
  956. && Security.IsAllowed<ViewDesktopFactoryAllocationScreen>());
  957. //SetVisibility(FactoryScheduleButton, ClientFactory.IsSupported<Booking>() && ClientFactory.IsEnabled<>());
  958. SetVisibility(FactoryFloorButton,
  959. ClientFactory.IsSupported<ManufacturingPacket>()
  960. && Security.IsAllowed<CanViewFactoryFloor>()
  961. && Security.IsAllowed<ViewDesktopFactoryFloorScreen>());
  962. //SetVisibility(FactoryReadyButton, ClientFactory.IsSupported<ManufacturingPacket>() && Security.IsAllowed<CanViewFactoryReadyToGo>());
  963. SetVisibleIfAny(ManufacturingActionSeparator,
  964. new FrameworkElement[]
  965. {
  966. FactoryStatusButton, FactoryAllocationButton, FactoryFloorButton
  967. });
  968. SetVisibleIfAny(ManufacturingActions, ManufacturingDashboardButton, ManufacturingMessagesButton, ManufacturingTaskButton,
  969. ManufacturingAttendanceButton, ManufacturingDailyReportButton, FactoryStatusButton, FactoryAllocationButton,
  970. FactoryFloorButton);
  971. SetTabVisibleIfAny(ManufacturingTab, FactoryStatusButton, FactoryAllocationButton, FactoryFloorButton);
  972. }
  973. private void SetupProjectsTab(bool bMaps)
  974. {
  975. if (!Security.IsAllowed<ViewDesktopProjectsTab>())
  976. return;
  977. SetVisibility(ProjectsDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  978. SetVisibility(ProjectMessagesButton, Security.CanView<Notification>());
  979. SetVisibility(ProjectTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  980. SetVisibility(ProjectAttendanceButton, ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  981. SetVisibility(ProjectsMapButton, bMaps);
  982. SetVisibility(ProjectDailyReportButton,
  983. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  984. SetVisibility(ProjectsButton, Security.CanView<Job>() && Security.IsAllowed<ViewDesktopProjectsScreen>());
  985. //SetVisibility(ServiceButton, Security.CanView<Job>() && Security.IsAllowed<ViewDesktopServiceScreen>());
  986. SetVisibility(ProjectPlannerButton, Security.CanView<Job>() && Security.IsAllowed<ViewDesktopProjectPlannerScreen>());
  987. SetVisibleIfEither(ProjectTaskSeparator,
  988. new FrameworkElement[]
  989. {
  990. ProjectsDashboardButton, ProjectMessagesButton, ProjectTaskButton, ProjectAttendanceButton, ProjectsMapButton,
  991. ProjectDailyReportButton
  992. }, new FrameworkElement[] { QuotesButton, ProjectsButton, ProjectPlannerButton });
  993. SetVisibility(QuotesButton, Security.CanView<Quote>() && Security.IsAllowed<ViewDesktopQuotesScreen>());
  994. SetVisibility(KitsMasterList, Security.CanView<Kit>() && Security.IsAllowed<ViewDesktopProductKitsScreen>());
  995. SetVisibility(CostSheetsMasterList, Security.CanView<CostSheet>() && Security.IsAllowed<ViewDesktopCostSheetsScreen>());
  996. SetVisibleIfAny(ProjectsSetup, KitsMasterList, CostSheetsMasterList);
  997. //ProjectsActions.IsLauncherButtonVisible = Security.IsAllowed<CanCustomiseModules>();
  998. //ProjectReports.IsLauncherButtonVisible = Security.IsAllowed<CanDesignReports>();
  999. SetTabVisibleIfAny(ProjectsTab, QuotesButton, ProjectsButton, ProjectPlannerButton, CostSheetsMasterList, KitsMasterList);
  1000. }
  1001. private void SetupDock<TSecurityDescriptor>(LayoutAnchorable layout, IDockPanel dock)
  1002. where TSecurityDescriptor : ISecurityDescriptor, new()
  1003. {
  1004. if (Security.IsAllowed<TSecurityDescriptor>())
  1005. {
  1006. if (!DockGroup.Children.Any(x => x == layout))
  1007. {
  1008. DockGroup.Children.Add(layout);
  1009. }
  1010. if (layout.IsVisible && (ClientFactory.UserGuid != Guid.Empty))
  1011. dock.Setup();
  1012. }
  1013. else
  1014. {
  1015. DockGroup.RemoveChild(layout);
  1016. }
  1017. }
  1018. private void LoadApplicationState()
  1019. {
  1020. if (ClientFactory.UserGuid != Guid.Empty)
  1021. {
  1022. _ribbon.IsCollapsed = false;
  1023. if (OutstandingDailyReports(false))
  1024. {
  1025. MessageWindow.ShowMessage("There are outstanding Daily Reports that must be filled out before continuing!"
  1026. + "\n\nAccess to PRS is restricted until this is corrected.",
  1027. "Outstanding Reports");
  1028. var dailyReportPanel = LoadWindow<DailyReport>(ProjectDailyReportButton);
  1029. if(dailyReportPanel is not null)
  1030. {
  1031. dailyReportPanel.OnTimeSheetConfirmed += e =>
  1032. {
  1033. if (!OutstandingDailyReports(true))
  1034. {
  1035. ConfigureMainScreen(null);
  1036. LoadApplicationState();
  1037. }
  1038. };
  1039. }
  1040. return;
  1041. }
  1042. using (new WaitCursor())
  1043. {
  1044. _ribbon.IsCollapsed = false;
  1045. LoadInitialWindow();
  1046. }
  1047. }
  1048. }
  1049. private void LoadInitialWindow()
  1050. {
  1051. var app = new LocalConfiguration<AppSettings>().Load();
  1052. if (app.Settings.ContainsKey("CurrentPanel"))
  1053. {
  1054. try
  1055. {
  1056. var bFound = false;
  1057. var module = app.Settings["CurrentPanel"].Split(new[] { " / " }, StringSplitOptions.None);
  1058. if (module.Length == 2)
  1059. foreach (Fluent.RibbonTabItem tab in _ribbon.Tabs)
  1060. {
  1061. if (String.Equals(tab.Header, module.First()))
  1062. {
  1063. _ribbon.SelectedTabItem = tab;
  1064. foreach (Fluent.RibbonGroupBox bar in tab.Groups)
  1065. {
  1066. foreach (var item in bar.Items)
  1067. {
  1068. var button = item as Fluent.Button;
  1069. if (button != null && String.Equals(button.Header, module.Last()))
  1070. {
  1071. bFound = true;
  1072. button.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));
  1073. break;
  1074. }
  1075. }
  1076. if (bFound)
  1077. break;
  1078. }
  1079. }
  1080. if (bFound)
  1081. break;
  1082. }
  1083. }
  1084. catch (Exception e)
  1085. {
  1086. MessageWindow.ShowError($"Unable to load {app.Settings["CurrentPanel"]}", e);
  1087. }
  1088. }
  1089. }
  1090. private void _ribbon_OnLoaded(object sender, RoutedEventArgs e)
  1091. {
  1092. _ribbon.SelectedTabItem = CurrentTab;
  1093. }
  1094. private void LoadSecondaryWindows()
  1095. {
  1096. if (ClientFactory.UserGuid != Guid.Empty)
  1097. {
  1098. var windows = App.DatabaseSettings.SecondaryWindows;
  1099. foreach (var key in windows.Keys.ToArray())
  1100. {
  1101. SecondaryWindows[key] = new SecondaryWindow(
  1102. key,
  1103. windows[key].Item1,
  1104. windows[key].Item2,
  1105. windows[key].Item3,
  1106. windows[key].Item4,
  1107. windows[key].Item5,
  1108. windows[key].Item6
  1109. );
  1110. SecondaryWindows[key].Closed += (o, e) => { SecondaryWindows.Remove(key); };
  1111. SecondaryWindows[key].Show();
  1112. }
  1113. }
  1114. else
  1115. {
  1116. foreach (var key in SecondaryWindows.Keys.ToArray())
  1117. {
  1118. App.IsClosing = true;
  1119. SecondaryWindows[key].Close();
  1120. App.IsClosing = false;
  1121. }
  1122. }
  1123. }
  1124. private Fluent.RibbonTabItem GetTabItem(FrameworkElement? sender)
  1125. {
  1126. if (sender == null)
  1127. throw new Exception("No Tab Found!");
  1128. if (sender is Fluent.RibbonTabItem)
  1129. return (Fluent.RibbonTabItem)sender;
  1130. return GetTabItem(sender.Parent as FrameworkElement);
  1131. }
  1132. private IEnumerable<IBasePanel> Panels
  1133. {
  1134. get
  1135. {
  1136. if(PanelHost.CurrentPanel is not null)
  1137. {
  1138. yield return PanelHost.CurrentPanel;
  1139. }
  1140. foreach(var window in SecondaryWindows.Values)
  1141. {
  1142. yield return window.Panel;
  1143. }
  1144. }
  1145. }
  1146. private T? LoadWindow<T>(Fluent.Button sender) where T : class, IBasePanel, new()
  1147. {
  1148. return LoadWindow<T>(sender, new CancelEventArgs());
  1149. }
  1150. private T? LoadWindow<T>(Fluent.Button sender, CancelEventArgs cancel) where T : class, IBasePanel, new()
  1151. {
  1152. using (new WaitCursor())
  1153. {
  1154. UnloadWindow(cancel);
  1155. if (cancel.Cancel)
  1156. {
  1157. return null;
  1158. }
  1159. CurrentTab = GetTabItem(sender);
  1160. CurrentButton = sender;
  1161. //CurrentButton.IsSelected = true;
  1162. UpdateRibbonColors();
  1163. var moduleName = sender.Header?.ToString() ?? "";
  1164. var panel = PanelHost.LoadPanel<T>(moduleName);
  1165. ContentControl.Content = panel;
  1166. Title =
  1167. $"{moduleName} - {(String.Equals(App.Profile?.ToUpper(), "DEFAULT") ? "PRS Desktop" : App.Profile)} (Release {CoreUtils.GetVersion()})";
  1168. PanelHost.Refresh();
  1169. if (panel is NotificationPanel)
  1170. {
  1171. Logger.Send(LogType.Information, ClientFactory.UserID, "Disabling Heartbeat");
  1172. NotificationsWatchDog.IsEnabled = false;
  1173. Notifications.Visibility = Visibility.Collapsed;
  1174. DockingGrid.ColumnDefinitions[1].Width = new GridLength(0, GridUnitType.Pixel);
  1175. DockingGrid.ColumnDefinitions[2].Width = new GridLength(0, GridUnitType.Pixel);
  1176. }
  1177. else
  1178. {
  1179. ReloadNotifications();
  1180. }
  1181. if (sender != null)
  1182. {
  1183. var settings = new LocalConfiguration<AppSettings>().Load();
  1184. var module = string.Format("{0} / {1}", CurrentTab?.Header, sender.Header);
  1185. if (!settings.Settings.ContainsKey("CurrentPanel") || module != settings.Settings["CurrentPanel"])
  1186. {
  1187. settings.Settings["CurrentPanel"] = module;
  1188. try
  1189. {
  1190. new LocalConfiguration<AppSettings>().Save(settings);
  1191. }
  1192. catch (Exception e)
  1193. {
  1194. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  1195. }
  1196. }
  1197. }
  1198. return panel;
  1199. }
  1200. }
  1201. private void UpdateRibbonColors()
  1202. {
  1203. foreach (var tab in _ribbon.Tabs)
  1204. {
  1205. bool bFound = false;
  1206. foreach (var grp in tab.Groups)
  1207. {
  1208. foreach (var btn in grp.Items)
  1209. {
  1210. if (btn is Fluent.Button fluentbutton)
  1211. {
  1212. bFound = bFound || (btn == CurrentButton);
  1213. fluentbutton.Background = (btn == CurrentButton) ? ThemeManager.SelectedTabItemBackgroundBrush : new SolidColorBrush(Colors.White);
  1214. fluentbutton.Foreground = (btn == CurrentButton) ? ThemeManager.SelectedTabItemForegroundBrush : new SolidColorBrush(Colors.Black);
  1215. }
  1216. }
  1217. tab.Background = bFound ? ThemeManager.SelectedTabItemBackgroundBrush : new SolidColorBrush(Colors.White);
  1218. tab.Foreground = bFound ? ThemeManager.SelectedTabItemForegroundBrush : new SolidColorBrush(Colors.Black);
  1219. }
  1220. }
  1221. }
  1222. private static void StartLocalDatabase(IProgress<string> progress)
  1223. {
  1224. var dirName = Path.GetDirectoryName(App.DatabaseSettings.FileName);
  1225. if (!Directory.Exists(dirName) && dirName != null)
  1226. Directory.CreateDirectory(dirName);
  1227. var FileName = App.DatabaseSettings.FileName;
  1228. var Exists = File.Exists(FileName);
  1229. progress.Report("Configuring Stores");
  1230. DbFactory.Stores = CoreUtils.TypeList(
  1231. new[]
  1232. {
  1233. typeof(Store<>).Assembly,
  1234. typeof(EquipmentStore).Assembly
  1235. },
  1236. myType =>
  1237. myType.IsClass
  1238. && !myType.IsAbstract
  1239. && !myType.IsGenericType
  1240. && myType.GetInterfaces().Contains(typeof(IStore))
  1241. ).ToArray();
  1242. DbFactory.ProviderFactory = new SQLiteProviderFactory(App.DatabaseSettings.FileName);
  1243. DbFactory.ColorScheme = App.DatabaseSettings.ColorScheme;
  1244. DbFactory.Logo = App.DatabaseSettings.Logo;
  1245. progress.Report("Starting Local Database");
  1246. DbFactory.Start();
  1247. ClientFactory.DatabaseID = DbFactory.ID;
  1248. progress.Report("Checking Database");
  1249. var users = DbFactory.NewProvider(Logger.Main).Load<User>();
  1250. if (!users.Any())
  1251. {
  1252. var user = new User { UserID = "ADMIN", Password = "admin" };
  1253. DbFactory.NewProvider(Logger.Main).Save(user);
  1254. var employee = DbFactory.NewProvider(Logger.Main).Load(new Filter<Employee>(x => x.Code).IsEqualTo("ADMIN")).FirstOrDefault();
  1255. employee ??= new Employee { Code = "ADMIN", Name = "Administrator Account" };
  1256. employee.UserLink.ID = user.ID;
  1257. DbFactory.NewProvider(Logger.Main).Save(employee);
  1258. }
  1259. StoreUtils.GoogleAPIKey = App.DatabaseSettings.GoogleAPIKey;
  1260. Job.JobNumberPrefix = App.DatabaseSettings.JobPrefix;
  1261. PurchaseOrder.PONumberPrefix = App.DatabaseSettings.PurchaseOrderPrefix;
  1262. }
  1263. #endregion
  1264. #region Login Management
  1265. private ValidationStatus? TryAutoLogin()
  1266. {
  1267. ValidationStatus? result = null;
  1268. if (App.DatabaseSettings.LoginType == LoginType.UserID)
  1269. {
  1270. try
  1271. {
  1272. result = ClientFactory.Validate(App.DatabaseSettings.UserID, App.DatabaseSettings.Password);
  1273. }
  1274. catch (Exception e)
  1275. {
  1276. MessageWindow.ShowError("Error connecting to server.\nPlease check the server URL and port number.", e);
  1277. result = null;
  1278. }
  1279. if (result == ValidationStatus.INVALID)
  1280. {
  1281. MessageWindow.ShowMessage("Unable to Login with User ID: " + App.DatabaseSettings.UserID, "Login failed");
  1282. }
  1283. }
  1284. return result;
  1285. }
  1286. private ValidationStatus? DoLogin()
  1287. {
  1288. ValidationStatus? result = null;
  1289. if (result != ValidationStatus.VALID)
  1290. {
  1291. var login = new PinLogin(CoreUtils.GetVersion(), result ?? ValidationStatus.INVALID);
  1292. if (login.ShowDialog() == true)
  1293. {
  1294. result = ValidationStatus.VALID;
  1295. }
  1296. }
  1297. return result ?? ValidationStatus.INVALID;
  1298. }
  1299. /// <summary>
  1300. /// To be called after <see cref="DoLogin(bool)"/> and if a valid login session exists. Configures the main screen and loads the windows.
  1301. /// </summary>
  1302. /// <param name="progress">If not <see langword="null"/>, then rather than opening a new progress window, just uses that.</param>
  1303. private void AfterLogin(IProgress<string>? progress)
  1304. {
  1305. Logger.Send(LogType.Information, "", "Loading employee");
  1306. LoadCurrentEmployee();
  1307. if (CheckTimesheetBypass(true))
  1308. {
  1309. UpdateCurrentLogin();
  1310. }
  1311. else
  1312. {
  1313. MessageWindow.ShowMessage("You must clock on before logging in to PRS!", "Not clocked in.");
  1314. ClientFactory.InvalidateUser();
  1315. App.EmployeeID = Guid.Empty;
  1316. App.EmployeeName = "";
  1317. App.EmployeeCode = "";
  1318. App.EmployeeEmail = "";
  1319. }
  1320. Logger.Send(LogType.Information, "", "Setting colours");
  1321. if(progress is null)
  1322. {
  1323. ApplyColorScheme();
  1324. }
  1325. else
  1326. {
  1327. Dispatcher.Invoke(ApplyColorScheme);
  1328. }
  1329. Logger.Send(LogType.Information, "", "Configuring main window");
  1330. ConfigureMainScreen(progress);
  1331. Logger.Send(LogType.Information, "", "Loading current window");
  1332. if(progress is null)
  1333. {
  1334. LoadApplicationState();
  1335. }
  1336. else
  1337. {
  1338. Dispatcher.Invoke(LoadApplicationState);
  1339. }
  1340. Logger.Send(LogType.Information, "", "Loading secondary window");
  1341. if(progress is null)
  1342. {
  1343. LoadSecondaryWindows();
  1344. }
  1345. else
  1346. {
  1347. Dispatcher.Invoke(LoadSecondaryWindows);
  1348. }
  1349. //if (_ribbon.Menu.IsVisible)
  1350. //{
  1351. // _ribbon.;
  1352. //}
  1353. }
  1354. /// <summary>
  1355. /// Creates a new <see cref="Login"/> if one does not already exist. Otherwise, updates the <see cref="Login"/> entry in the database with new Station ID.
  1356. /// </summary>
  1357. private void UpdateCurrentLogin()
  1358. {
  1359. if (CoreUtils.GetVersion().Equals("???"))
  1360. return;
  1361. // Register this station with the Server
  1362. // Later on, the heartbeat will check to make sure
  1363. // that the StationID hasn't changed. If it has,
  1364. // then we've logged in somewhere else and we'll
  1365. // drop out of this station
  1366. var curr = new Client<Login>().Query(
  1367. new Filter<Login>(x => x.User.ID).IsEqualTo(ClientFactory.UserGuid),
  1368. null
  1369. ).Rows.FirstOrDefault();
  1370. if (curr != null)
  1371. {
  1372. var c = curr.ToObject<Login>();
  1373. c.StationID = station.StationID;
  1374. station = c;
  1375. }
  1376. else
  1377. {
  1378. station.User.ID = ClientFactory.UserGuid;
  1379. station.TimeStamp = DateTime.Now;
  1380. }
  1381. new Client<Login>().Save(station, "", (o, e) => { });
  1382. }
  1383. private void LoadCurrentEmployee()
  1384. {
  1385. var me = new Client<Employee>().Query(
  1386. new Filter<Employee>(x => x.UserLink.ID).IsEqualTo(ClientFactory.UserGuid),
  1387. Columns.None<Employee>().Add(x => x.ID).Add(x => x.Email).Add(x => x.Name)
  1388. );
  1389. App.EmployeeID = me.Rows.FirstOrDefault()?.Get<Employee, Guid>(x => x.ID) ?? Guid.Empty;
  1390. App.EmployeeName = me.Rows.FirstOrDefault()?.Get<Employee, String>(x => x.Name) ?? "";
  1391. App.EmployeeCode = me.Rows.FirstOrDefault()?.Get<Employee, String>(x => x.Code) ?? "";
  1392. App.EmployeeEmail = me.Rows.FirstOrDefault()?.Get<Employee, String>(x => x.Email) ?? "";
  1393. }
  1394. private void ExecuteLogout()
  1395. {
  1396. new Client<Login>().Delete(station, "");
  1397. station.ID = Guid.Empty;
  1398. App.EmployeeID = Guid.Empty;
  1399. App.EmployeeName = "";
  1400. App.EmployeeEmail = "";
  1401. }
  1402. /// <summary>
  1403. /// Logs the user out and unloads windows
  1404. /// </summary>
  1405. /// <param name="message">A message to display as the reason for logging out, or <c>null</c> for no message.</param>
  1406. private bool Logout(string? message = null, bool force = false)
  1407. {
  1408. // I really don't like all these try-catch blocks; unfortunately, if we are trying to log out and invalidate due to an unauthenticated user,
  1409. // all the queries that get called here will throw exceptions and thus break our system, failing to log out.
  1410. try
  1411. {
  1412. FinalizeAutoTimesheet();
  1413. }
  1414. catch
  1415. {
  1416. if (!force) throw;
  1417. }
  1418. // Try to unload the window;
  1419. try
  1420. {
  1421. UnloadWindow(null);
  1422. if (DatabaseType == DatabaseType.Standalone && !CoreUtils.GetVersion().Equals("???"))
  1423. scheduler.Stop();
  1424. }
  1425. catch
  1426. {
  1427. if (!force) throw;
  1428. }
  1429. // Next, try to set things to being empty
  1430. try
  1431. {
  1432. if (!CoreUtils.GetVersion().Equals("???"))
  1433. if (station.ID != Guid.Empty)
  1434. {
  1435. ExecuteLogout();
  1436. }
  1437. ClearTrackingKanban();
  1438. }
  1439. catch
  1440. {
  1441. if (!force) throw;
  1442. }
  1443. ClientFactory.InvalidateUser();
  1444. ConfigureMainScreen(null);
  1445. LoadSecondaryWindows();
  1446. if (message != null)
  1447. {
  1448. MessageWindow.ShowMessage(message, "Logged out");
  1449. }
  1450. if (DoLogin() == ValidationStatus.VALID)
  1451. {
  1452. AfterLogin(null);
  1453. }
  1454. return true;
  1455. }
  1456. #endregion
  1457. #region Timesheets
  1458. private void RefreshTimeSheets()
  1459. {
  1460. if (App.EmployeeID == Guid.Empty)
  1461. return;
  1462. var filter = new Filter<TimeSheet>(x => x.EmployeeLink.ID).IsEqualTo(App.EmployeeID);
  1463. filter = filter.And(new Filter<TimeSheet>(x => x.Confirmed).IsEqualTo(DateTime.MinValue).Or(x => x.Date).IsEqualTo(DateTime.Today));
  1464. _timesheets = new Client<TimeSheet>().Query(
  1465. filter,
  1466. Columns.None<TimeSheet>().Add(
  1467. x => x.ID,
  1468. x => x.Date,
  1469. x => x.Finish
  1470. )
  1471. );
  1472. }
  1473. private CoreTable GetTimesheet()
  1474. {
  1475. return new Client<TimeSheet>().Query(
  1476. new Filter<TimeSheet>(x => x.Date).IsEqualTo(DateTime.Today)
  1477. .And(x => x.EmployeeLink.ID).IsEqualTo(App.EmployeeID)
  1478. .And(x => x.Finish).IsEqualTo(TimeSpan.Zero)
  1479. );
  1480. }
  1481. private bool CheckTimesheetBypass(bool message)
  1482. {
  1483. if (!ClientFactory.IsSupported<TimeSheet>())
  1484. return true;
  1485. var isClockedOn = IsClockedOn();
  1486. if (!Security.IsAllowed<CanBypassTimeBench>())
  1487. {
  1488. if (!isClockedOn)
  1489. {
  1490. if (message)
  1491. MessageBox.Show("You must clock on before opening this screen");
  1492. return false;
  1493. }
  1494. return true;
  1495. }
  1496. if (Security.IsAllowed<AutoGenerateTimesheet>())
  1497. if (!isClockedOn)
  1498. {
  1499. var ts = new TimeSheet();
  1500. ts.Date = DateTime.Today;
  1501. ts.Start = DateTime.Now.TimeOfDay;
  1502. ts.EmployeeLink.ID = App.EmployeeID;
  1503. ts.Notes = "Automatic Login from PRS Desktop";
  1504. new Client<TimeSheet>().Save(ts, "AutoLogon because Timebench Bypass is enabled", (o, e) => { });
  1505. }
  1506. return true;
  1507. }
  1508. private bool IsClockedOn()
  1509. {
  1510. RefreshTimeSheets();
  1511. if (_timesheets == null)
  1512. return false;
  1513. return _timesheets.Rows.Any(r =>
  1514. r.Get<TimeSheet, DateTime>(c => c.Date).Date == DateTime.Today && r.Get<TimeSheet, TimeSpan>(c => c.Finish) == new TimeSpan());
  1515. }
  1516. private void FinalizeAutoTimesheet()
  1517. {
  1518. if (Security.IsAllowed<AutoGenerateTimesheet>())
  1519. {
  1520. var check = new Client<TimeSheet>().Query(
  1521. new Filter<TimeSheet>(x => x.Date).IsEqualTo(DateTime.Today).And(x => x.EmployeeLink.ID).IsEqualTo(App.EmployeeID).And(x => x.Finish)
  1522. .IsEqualTo(TimeSpan.Zero)
  1523. );
  1524. if (check.Rows.Any())
  1525. {
  1526. var ts = check.Rows.First().ToObject<TimeSheet>();
  1527. if (DateTime.Now.TimeOfDay < ts.Start.Add(new TimeSpan(0, 2, 0)))
  1528. {
  1529. new Client<TimeSheet>().Delete(ts, "Deleting Auto TimeSheet because TimeBench Bypass is enabled", (o, ex) => { });
  1530. }
  1531. else
  1532. {
  1533. ts.Finish = DateTime.Now.TimeOfDay;
  1534. new Client<TimeSheet>().Save(ts, "Clocking off Auto Timesheet because Timesheet Bypass is enabled", (o, ex) => { });
  1535. }
  1536. }
  1537. }
  1538. }
  1539. #endregion
  1540. private string CurrentPanelSlug()
  1541. {
  1542. var app = new LocalConfiguration<AppSettings>().Load();
  1543. var module = app.Settings["CurrentPanel"].Split(new[] { " / " }, StringSplitOptions.None);
  1544. return module.LastOrDefault()?.Replace(" ", "_").Replace("/", "") ?? "";
  1545. }
  1546. private bool ShowHelp()
  1547. {
  1548. Process.Start(new ProcessStartInfo("https://prsdigital.com.au/wiki/index.php/" + CurrentPanelSlug()) { UseShellExecute = true });
  1549. return true;
  1550. }
  1551. private void Wiki_Click(object sender, RoutedEventArgs e)
  1552. {
  1553. ShowHelp();
  1554. }
  1555. private void Window_Loaded(object sender, RoutedEventArgs e)
  1556. {
  1557. }
  1558. private void UnloadWindow(CancelEventArgs? cancel)
  1559. {
  1560. PanelHost.UnloadPanel(cancel);
  1561. if (cancel?.Cancel == true)
  1562. {
  1563. return;
  1564. }
  1565. Title =
  1566. $" - {(String.Equals(App.Profile?.ToUpper(), "DEFAULT") ? "PRS Desktop" : App.Profile)} (Release {CoreUtils.GetVersion()})";
  1567. if (CurrentTab is not null)
  1568. {
  1569. var border = VisualUtils.EnumChildrenOfType(CurrentTab, typeof(Border)).LastOrDefault();
  1570. if (border != null)
  1571. {
  1572. ((Border)border).Background = new SolidColorBrush(Colors.Transparent);
  1573. ((Border)border).BorderBrush = new SolidColorBrush(Colors.Transparent);
  1574. }
  1575. var ReportsBar = FindRibbonBar(CurrentTab, x => x.Header.Equals("Print"));
  1576. if (ReportsBar is not null)
  1577. {
  1578. ReportsBar.Items.Clear();
  1579. ReportsBar.Visibility = Visibility.Collapsed;
  1580. ReportsBar.IsLauncherVisible = false;
  1581. }
  1582. var ActionBar = FindRibbonBar(CurrentTab, x => x.Header.Equals("Actions"));
  1583. if (ActionBar is not null)
  1584. {
  1585. ActionBar.IsLauncherVisible = false;
  1586. foreach (var module in CurrentModules)
  1587. ActionBar.Items.Remove(module);
  1588. }
  1589. }
  1590. CurrentTab = null;
  1591. CurrentButton = null;
  1592. ContentControl.Content = null;
  1593. }
  1594. private void SecondaryWindow_Click(object sender, RoutedEventArgs e)
  1595. {
  1596. var panel = PanelHost.CurrentPanel;
  1597. if (panel is null) return;
  1598. var id = Guid.NewGuid();
  1599. var window = new Tuple<string, string, double, double, double, double>(
  1600. panel.GetType().EntityName(),
  1601. PanelHost.CurrentModuleName,
  1602. Left + 100,
  1603. Top + 100,
  1604. Width - 200,
  1605. Height - 200
  1606. );
  1607. App.DatabaseSettings.SecondaryWindows[id] = window;
  1608. new LocalConfiguration<DatabaseSettings>(App.Profile).Save(App.DatabaseSettings);
  1609. SecondaryWindows[id] = new SecondaryWindow(
  1610. id,
  1611. window.Item1,
  1612. window.Item2,
  1613. window.Item3,
  1614. window.Item4,
  1615. window.Item5,
  1616. window.Item6
  1617. );
  1618. SecondaryWindows[id].Show();
  1619. }
  1620. private void RibbonWindow_Activated(object sender, EventArgs e)
  1621. {
  1622. }
  1623. private void RegisterModules(IProgress<string> progress)
  1624. {
  1625. foreach (Fluent.RibbonTabItem tab in _ribbon.Tabs)
  1626. foreach (Fluent.RibbonGroupBox bar in tab.Groups)
  1627. foreach (var item in bar.Items)
  1628. Dispatcher.Invoke(() =>
  1629. {
  1630. var button = item as RibbonButton;
  1631. if (button != null && button.Label != "Refresh")
  1632. if (bar.Header.Equals("Actions"))
  1633. Modules.Register(button.Label);
  1634. });
  1635. }
  1636. #region Visibility
  1637. private void SetVisibility(FrameworkElement button, bool visible)
  1638. {
  1639. var vResult = true;
  1640. var eResult = ClientFactory.UserGuid != Guid.Empty && visible;
  1641. button.Visibility = vResult && eResult ? Visibility.Visible : Visibility.Collapsed;
  1642. if (button is RibbonButton rb)
  1643. {
  1644. CustomModules.Register(rb.Label);
  1645. rb.IsEnabled = !OutstandingDailyReports(false);
  1646. }
  1647. }
  1648. private static void SetVisibleIfEither(FrameworkElement separator, FrameworkElement[] left, FrameworkElement[] right)
  1649. {
  1650. var bLeft = false;
  1651. foreach (var button in left)
  1652. bLeft = bLeft || button.Visibility == Visibility.Visible;
  1653. var bRight = false;
  1654. foreach (var button in right)
  1655. bRight = bRight || button.Visibility == Visibility.Visible;
  1656. separator.Visibility = bLeft && bRight ? Visibility.Visible : Visibility.Collapsed;
  1657. }
  1658. private static void SetVisibleIfAny(FrameworkElement separator, params FrameworkElement[] buttons)
  1659. {
  1660. var bVisible = false;
  1661. foreach (var button in buttons)
  1662. bVisible = bVisible || button.Visibility == Visibility.Visible;
  1663. separator.Visibility = bVisible ? Visibility.Visible : Visibility.Collapsed;
  1664. }
  1665. private static void SetTabVisibleIfAny(Fluent.RibbonTabItem tab, params FrameworkElement[] buttons)
  1666. {
  1667. var bVisible = false;
  1668. foreach (var button in buttons)
  1669. bVisible = bVisible || button.Visibility == Visibility.Visible;
  1670. tab.Visibility = bVisible ? Visibility.Visible : Visibility.Collapsed;
  1671. }
  1672. #endregion
  1673. private static Fluent.RibbonGroupBox? FindRibbonBar(Fluent.RibbonTabItem tab, Func<Fluent.RibbonGroupBox, bool> predicate)
  1674. {
  1675. foreach (var group in tab.Groups)
  1676. {
  1677. if (group != null)
  1678. if (predicate.Invoke(group))
  1679. return group;
  1680. }
  1681. return null;
  1682. }
  1683. #region Button Event Handlers
  1684. #region Common
  1685. private void Tasks_Checked(object sender, RoutedEventArgs e)
  1686. {
  1687. //LoadWindow<KanbanPanel>((RibbonButton)sender);
  1688. LoadWindow<TaskPanel>((Fluent.Button)sender);
  1689. }
  1690. private void DataEntry_Click(object sender, RoutedEventArgs e)
  1691. {
  1692. LoadWindow<DataEntryPanel>((Fluent.Button)sender);
  1693. }
  1694. private void Attendance_Checked(object sender, RoutedEventArgs e)
  1695. {
  1696. LoadWindow<AttendancePanel>((Fluent.Button)sender);
  1697. }
  1698. #endregion
  1699. #region Quotes
  1700. private void Quotes_Checked(object sender, RoutedEventArgs e)
  1701. {
  1702. LoadWindow<QuotePanel>((Fluent.Button)sender);
  1703. }
  1704. #endregion
  1705. #region Projects
  1706. private void Jobs_Checked(object sender, RoutedEventArgs e)
  1707. {
  1708. LoadWindow<ProjectsPanel>((Fluent.Button)sender);
  1709. }
  1710. private void ProjectPlanner_Checked(object sender, RoutedEventArgs e)
  1711. {
  1712. LoadWindow<JobResourcePlannerPanel>((Fluent.Button)sender);
  1713. }
  1714. private void DesignManagement_Checked(object sender, RoutedEventArgs e)
  1715. {
  1716. LoadWindow<StagingPanel>((Fluent.Button)sender);
  1717. }
  1718. //private void Service_Checked(object sender, RoutedEventArgs e)
  1719. //{
  1720. // LoadWindow<ServicePanel>((Fluent.Button)sender);
  1721. //}
  1722. #endregion
  1723. #region Manufacturing
  1724. private void ManufacturingMenu_Checked(object sender, RoutedEventArgs e)
  1725. {
  1726. LoadWindow<ManufacturingPanel>((Fluent.Button)sender);
  1727. }
  1728. private void FactoryFloorButton_Click(object sender, RoutedEventArgs e)
  1729. {
  1730. LoadWindow<FactoryPanel>((Fluent.Button)sender);
  1731. }
  1732. #endregion
  1733. #region Logistics
  1734. private void ReadyToGoMenu_Checked(object sender, RoutedEventArgs e)
  1735. {
  1736. LoadWindow<ReadyToGoPanel>((Fluent.Button)sender);
  1737. }
  1738. private void DispatchMenu_Checked(object sender, RoutedEventArgs e)
  1739. {
  1740. LoadWindow<DispatchPanel>((Fluent.Button)sender);
  1741. }
  1742. private void Requisitions_Checked(object sender, RoutedEventArgs e)
  1743. {
  1744. LoadWindow<RequisitionPanel>((Fluent.Button)sender);
  1745. }
  1746. #endregion
  1747. #region Products
  1748. #endregion
  1749. #region Human Resources
  1750. private void Timesheets_Checked(object sender, RoutedEventArgs e)
  1751. {
  1752. LoadWindow<TimesheetPanel>((Fluent.Button)sender);
  1753. }
  1754. #endregion
  1755. #region Accounts
  1756. #endregion
  1757. #region Equipment
  1758. private void Equipment_Checked(object sender, RoutedEventArgs e)
  1759. {
  1760. LoadWindow<EquipmentPanel>((Fluent.Button)sender);
  1761. }
  1762. private void EquipmentMaintenance_Checked(object sender, RoutedEventArgs e)
  1763. {
  1764. LoadWindow<EquipmentMaintenancePanel>((Fluent.Button)sender);
  1765. }
  1766. #endregion
  1767. #region Dashboards
  1768. #endregion
  1769. private void Console_Click(object sender, RoutedEventArgs a)
  1770. {
  1771. if (_console is null)
  1772. {
  1773. _console = new DesktopConsole("Console");
  1774. _console.Closing += (o, args) => _console = null;
  1775. }
  1776. _console.Show();
  1777. }
  1778. //private void Purchases_Checked(object sender, RoutedEventArgs e)
  1779. //{
  1780. // LoadWindow(PurchasesMenu, new PurchasesPanel());
  1781. //}
  1782. private void Maps_Checked(object sender, RoutedEventArgs e)
  1783. {
  1784. LoadWindow<MapsPanel>((Fluent.Button)sender);
  1785. }
  1786. private void RefreshMenu_Click(object sender, RoutedEventArgs e)
  1787. {
  1788. PanelHost.Refresh();
  1789. }
  1790. private void UserSetup_Click(object sender, RoutedEventArgs e)
  1791. {
  1792. LoadWindow<UserPanel>((Fluent.Button)sender);
  1793. }
  1794. private void Employees_Click(object sender, RoutedEventArgs e)
  1795. {
  1796. LoadWindow<EmployeePanel>((Fluent.Button)sender);
  1797. }
  1798. private void Trackers_Click(object sender, RoutedEventArgs e)
  1799. {
  1800. LoadWindow<GPSTrackers>((Fluent.Button)sender);
  1801. }
  1802. private void DeliveredOnSiteMenu_Checked(object sender, RoutedEventArgs e)
  1803. {
  1804. LoadWindow<DeliveredOnSitePanel>((Fluent.Button)sender);
  1805. }
  1806. private void Products_Checked(object sender, RoutedEventArgs e)
  1807. {
  1808. LoadWindow<ProductsPanel>((Fluent.Button)sender);
  1809. }
  1810. private void StockLocations_Checked(object sender, RoutedEventArgs e)
  1811. {
  1812. LoadWindow<StockLocationPanel>((Fluent.Button)sender);
  1813. }
  1814. private void StockMovements_Checked(object sender, RoutedEventArgs e)
  1815. {
  1816. LoadWindow<StockMovementPanel>((Fluent.Button)sender);
  1817. }
  1818. private void StockForecastButton_Clicked(object sender, RoutedEventArgs e)
  1819. {
  1820. LoadWindow<StockForecastPanel>((Fluent.Button)sender);
  1821. }
  1822. private void ReservationManagementButton_Clicked(object sender, RoutedEventArgs e)
  1823. {
  1824. LoadWindow<ReservationManagementPanel>((Fluent.Button)sender);
  1825. }
  1826. private void KitsMasterList_Click(object sender, RoutedEventArgs e)
  1827. {
  1828. LoadWindow<KitPanel>((Fluent.Button)sender);
  1829. }
  1830. private void CostSheetsMasterList_Click(object sender, RoutedEventArgs e)
  1831. {
  1832. LoadWindow<CostSheetPanel>((Fluent.Button)sender);
  1833. }
  1834. private void LeaveRequestsButton_Click(object sender, RoutedEventArgs e)
  1835. {
  1836. LoadWindow<LeaveRequestPanel>((Fluent.Button)sender);
  1837. }
  1838. private void MeetingsButton_Click(object sender, RoutedEventArgs e)
  1839. {
  1840. LoadWindow<MeetingPanel>((Fluent.Button)sender);
  1841. }
  1842. private void OrgChartButton_Click(object sender, RoutedEventArgs e)
  1843. {
  1844. LoadWindow<OrgChartPanel>((Fluent.Button)sender);
  1845. }
  1846. private void SupplierList_Click(object sender, RoutedEventArgs e)
  1847. {
  1848. LoadWindow<SupplierPanel>((Fluent.Button)sender);
  1849. }
  1850. private void CustomerList_Click(object sender, RoutedEventArgs e)
  1851. {
  1852. LoadWindow<CustomerPanel>((Fluent.Button)sender);
  1853. }
  1854. private void CalendarButton_Click(object sender, RoutedEventArgs e)
  1855. {
  1856. LoadWindow<CalendarPanel>((Fluent.Button)sender);
  1857. }
  1858. private void EmployeePlannerButton_Click(object sender, RoutedEventArgs e)
  1859. {
  1860. LoadWindow<EmployeeResourcePlannerPanel>((Fluent.Button)sender);
  1861. }
  1862. private void EquipmentPlannerButton_Click(object sender, RoutedEventArgs e)
  1863. {
  1864. LoadWindow<EquipmentPlannerPanel>((Fluent.Button)sender);
  1865. }
  1866. private void InvoiceList_Click(object sender, RoutedEventArgs e)
  1867. {
  1868. LoadWindow<InvoicePanel>((Fluent.Button)sender);
  1869. }
  1870. private void ReceiptList_Click(object sender, RoutedEventArgs e)
  1871. {
  1872. LoadWindow<CustomerReceipts>((Fluent.Button)sender);
  1873. }
  1874. private void PaymentsList_Click(object sender, RoutedEventArgs e)
  1875. {
  1876. LoadWindow<SupplierPayments>((Fluent.Button)sender);
  1877. }
  1878. private void BillsList_Click(object sender, RoutedEventArgs e)
  1879. {
  1880. LoadWindow<SupplierBillPanel>((Fluent.Button)sender);
  1881. }
  1882. private void PurchasesList_Click(object sender, RoutedEventArgs e)
  1883. {
  1884. LoadWindow<SupplierPurchaseOrderPanel>((Fluent.Button)sender);
  1885. }
  1886. private void DeliveriesButton_Click(object sender, RoutedEventArgs e)
  1887. {
  1888. LoadWindow<DeliveryPanel>((Fluent.Button)sender);
  1889. }
  1890. private void FactoryAllocationButton_Click(object sender, RoutedEventArgs e)
  1891. {
  1892. LoadWindow<ManufacturingAllocationPanel>((Fluent.Button)sender);
  1893. }
  1894. private void Messages_Checked(object sender, RoutedEventArgs e)
  1895. {
  1896. LoadWindow<NotificationPanel>((Fluent.Button)sender);
  1897. }
  1898. private void DatabaseActivityButton_Click(object sender, RoutedEventArgs e)
  1899. {
  1900. LoadWindow<DatabaseActivityDashboard>((Fluent.Button)sender);
  1901. }
  1902. private void FactoryProductivityButton_Click(object sender, RoutedEventArgs e)
  1903. {
  1904. LoadWindow<FactoryProductivityDashboard>((Fluent.Button)sender);
  1905. }
  1906. private void TemplateAnalysisButton_Click(object sender, RoutedEventArgs e)
  1907. {
  1908. LoadWindow<ManufacturingTemplateAnalysis>((Fluent.Button)sender);
  1909. }
  1910. private void FactoryAnalysisButton_Click(object sender, RoutedEventArgs e)
  1911. {
  1912. LoadWindow<FactoryFloorAnalysis>((Fluent.Button)sender);
  1913. }
  1914. private void UserActivityButton_Click(object sender, RoutedEventArgs e)
  1915. {
  1916. LoadWindow<UserActivity>((Fluent.Button)sender);
  1917. }
  1918. private void QuickStatus_Click(object sender, RoutedEventArgs e)
  1919. {
  1920. LoadWindow<WidgetDashboard>((Fluent.Button)sender);
  1921. }
  1922. private void ConsignmentButton_Click(object sender, RoutedEventArgs e)
  1923. {
  1924. LoadWindow<ConsignmentsPanel>((Fluent.Button)sender);
  1925. }
  1926. //private void NotificationsList_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
  1927. //{
  1928. // if (NotificationsList.SelectedIndex < 0)
  1929. // return;
  1930. // var editors = NotificationsList.FindVisualChildren<InABox.DynamicGrid.ExtendedRichTextEditor>().ToArray();
  1931. // var selected = editors[NotificationsList.SelectedIndex];
  1932. // selected.Text = (String)selected.Tag; //NotificationsList.SelectedIndex.ToString();
  1933. //}
  1934. //private void ViewNotification_Click(object sender, System.Windows.Input.MouseButtonEventArgs e)
  1935. //{
  1936. // Notification notification = (sender as Label).Tag as Notification;
  1937. // NotificationDetails details = new NotificationDetails(notification);
  1938. // details.ShowDialog();
  1939. // ReloadNotifications();
  1940. //}
  1941. private void DailyReport_Checked(object sender, RoutedEventArgs e)
  1942. {
  1943. LoadWindow<DailyReport>((Fluent.Button)sender);
  1944. }
  1945. private void Library_Click(object sender, RoutedEventArgs e)
  1946. {
  1947. Process.Start(
  1948. new ProcessStartInfo
  1949. {
  1950. FileName = App.DatabaseSettings.LibraryLocation,
  1951. UseShellExecute = true,
  1952. Verb = "open"
  1953. }
  1954. );
  1955. }
  1956. private void SendNotificationClick(object sender, RoutedEventArgs e)
  1957. {
  1958. var form = new NotificationForm { Description = "" };
  1959. if (form.ShowDialog() == true)
  1960. ReloadNotifications();
  1961. }
  1962. private void CompanyInformation_Click(object sender, RoutedEventArgs e)
  1963. {
  1964. var info = new Client<CompanyInformation>().Load().FirstOrDefault();
  1965. if (info == null)
  1966. info = new CompanyInformation();
  1967. new DynamicDataGrid<CompanyInformation>().EditItems(new[] { info });
  1968. }
  1969. #region Digital Forms
  1970. private void DigitalFormsFormsLibraryButton_Click(object sender, RoutedEventArgs e)
  1971. {
  1972. LoadWindow<DigitalFormsLibrary>((Fluent.Button)sender);
  1973. }
  1974. private void DigitalFormsCompletedFormsButton_Click(object sender, RoutedEventArgs e)
  1975. {
  1976. LoadWindow<CompletedFormsPanel>((Fluent.Button)sender);
  1977. }
  1978. #endregion
  1979. private void Dashboards_Checked(object sender, RoutedEventArgs e)
  1980. {
  1981. LoadWindow<UtilityDashboard>((Fluent.Button)sender);
  1982. }
  1983. private void Setup_Click(object sender, RoutedEventArgs e)
  1984. {
  1985. var tab = _ribbon.SelectedTabItem;
  1986. if (tab is null)
  1987. return;
  1988. var menu = new ContextMenu();
  1989. PanelHost.InitialiseSetupMenu(menu);
  1990. menu.IsOpen = true;
  1991. }
  1992. private void StartForm<TEntityForm, TEntity, TEntityLink>(DigitalForm form)
  1993. where TEntityForm : EntityForm<TEntity, TEntityLink, TEntityForm>, new()
  1994. where TEntity : Entity, new()
  1995. where TEntityLink : EntityLink<TEntity>, new()
  1996. {
  1997. var entityForm = new TEntityForm();
  1998. entityForm.Form.ID = form.ID;
  1999. entityForm.Description = form.Description;
  2000. var entity = DFUtils.NewEntity<TEntityForm, TEntity, TEntityLink>(form);
  2001. if (DynamicFormEditWindow.EditDigitalForm(entityForm, out var dataModel, entity))
  2002. {
  2003. dataModel.Update(null);
  2004. }
  2005. }
  2006. private void Forms_Click(object sender, RoutedEventArgs e)
  2007. {
  2008. var select = new MultiSelectDialog<DigitalForm>(
  2009. Filter<DigitalForm>.And(
  2010. LookupFactory.DefineChildFilter<KanbanForm, DigitalForm>(Array.Empty<KanbanForm>()),
  2011. new Filter<DigitalForm>(x => x.ID).InQuery(
  2012. new Filter<EmployeeDigitalForm>(x => x.Employee.ID).IsEqualTo(App.EmployeeID),
  2013. x => x.Form.ID)),
  2014. LookupFactory.DefineChildColumns<KanbanForm, DigitalForm>()
  2015. .Add(x => x.Description),
  2016. false);
  2017. if (select.ShowDialog() == true)
  2018. {
  2019. var digitalForm = select.Data().Rows.FirstOrDefault()?.ToObject<DigitalForm>();
  2020. if (digitalForm is not null)
  2021. {
  2022. StartForm<KanbanForm, Kanban, KanbanLink>(digitalForm);
  2023. }
  2024. };
  2025. }
  2026. #endregion
  2027. private bool OutstandingDailyReports(bool refresh)
  2028. {
  2029. if (!Security.IsAllowed<CanViewDailyReports>() || Security.IsAllowed<BypassOutstandingDailyReports>())
  2030. return false;
  2031. if (refresh)
  2032. RefreshTimeSheets();
  2033. if (_timesheets == null)
  2034. return false;
  2035. return _timesheets.Rows.Any(r => r.Get<TimeSheet, DateTime>(c => c.Date).Date < DateTime.Today);
  2036. }
  2037. private void ShutDownTransport()
  2038. {
  2039. if (_transport != null)
  2040. {
  2041. _transport.OnClose -= TransportConnectionLost;
  2042. if (_transport.IsConnected())
  2043. _transport.Disconnect();
  2044. _transport = null;
  2045. }
  2046. }
  2047. private void Window_Unloaded(object sender, RoutedEventArgs e)
  2048. {
  2049. ShutDownTransport();
  2050. }
  2051. private void RibbonWindow_Closed(object sender, EventArgs e)
  2052. {
  2053. ShutDownTransport();
  2054. DisconnectRecorderNotes();
  2055. Application.Current.Shutdown();
  2056. }
  2057. //private bool _closingFromSystemMenu = false;
  2058. private void Window_Closing(object sender, CancelEventArgs e)
  2059. {
  2060. /*if (!_closingFromSystemMenu && !CoreUtils.GetVersion().Equals("???"))
  2061. {
  2062. WindowState = WindowState.Minimized;
  2063. e.Cancel = true;
  2064. return;
  2065. }*/
  2066. PanelHost.UnloadPanel(e);
  2067. if (e.Cancel)
  2068. {
  2069. return;
  2070. }
  2071. App.IsClosing = true;
  2072. FinalizeAutoTimesheet();
  2073. if (!CoreUtils.GetVersion().Equals("???"))
  2074. scheduler.Stop();
  2075. CurrentTab = null;
  2076. UpdateRibbonColors();
  2077. if (!CoreUtils.GetVersion().Equals("???"))
  2078. if (station.ID != Guid.Empty)
  2079. ExecuteLogout();
  2080. ShutDownTransport();
  2081. }
  2082. #region Notifications + Heartbeat
  2083. private void ReceiveNotification(Notification notification)
  2084. {
  2085. if (Security.CanView<Notification>())
  2086. {
  2087. Notifications.AddNotification(notification);
  2088. }
  2089. foreach(var panel in Panels.OfType<NotificationPanel>())
  2090. {
  2091. panel.AddNotification(notification);
  2092. }
  2093. }
  2094. private void Notifications_Tick(object? sender, EventArgs e)
  2095. {
  2096. if (ClientFactory.UserGuid != Guid.Empty)
  2097. {
  2098. try
  2099. {
  2100. ReloadNotifications();
  2101. }
  2102. catch (Exception err)
  2103. {
  2104. Logger.Send(LogType.Error, ClientFactory.UserID,
  2105. string.Format("Exception in Notifications_Tick:ReloadNotifications() {0}\n{1}", err.Message, err.StackTrace));
  2106. }
  2107. Heartbeat();
  2108. try
  2109. {
  2110. CheckIsLoggedOn();
  2111. }
  2112. catch (Exception err2)
  2113. {
  2114. Logger.Send(LogType.Error, ClientFactory.UserID,
  2115. string.Format("Exception in Notifications_Tick:CheckIsLoggedOn() {0}\n{1}", err2.Message, err2.StackTrace));
  2116. }
  2117. }
  2118. //else
  2119. //{
  2120. // Logger.Send(LogType.Information, ClientFactory.UserID, "Notifications_Tick: ClientFactory.UserGuid is empty");
  2121. //}
  2122. }
  2123. private void CheckIsLoggedOn()
  2124. {
  2125. if (CoreUtils.GetVersion().Equals("???"))
  2126. return;
  2127. var bLogout = false;
  2128. if (!Security.IsAllowed<CanBypassTimeBench>())
  2129. if (!IsClockedOn())
  2130. {
  2131. Logger.Send(LogType.Information, ClientFactory.UserID, "User is no longer clocked in!");
  2132. bLogout = true;
  2133. Dispatcher.Invoke(() => { Logout(); });
  2134. }
  2135. if (!bLogout)
  2136. new Client<Login>().Query(
  2137. new Filter<Login>(x => x.User.ID).IsEqualTo(ClientFactory.UserGuid),
  2138. Columns.None<Login>().Add(x => x.StationID),
  2139. null,
  2140. CoreRange.All,
  2141. (o, e) =>
  2142. {
  2143. if (e is RemoteException remote)
  2144. {
  2145. if (remote.Status == StatusCode.Unauthenticated)
  2146. {
  2147. Logger.Send(LogType.Information, ClientFactory.UserID, "User has been logged out");
  2148. Dispatcher.Invoke(() =>
  2149. {
  2150. Logout("You have been logged out due to inactivity");
  2151. });
  2152. }
  2153. else
  2154. {
  2155. Logger.Send(LogType.Information, ClientFactory.UserID, $"Error in CheckIsLoggedOn(): {CoreUtils.FormatException(remote)}");
  2156. }
  2157. }
  2158. else if (e is not null)
  2159. {
  2160. Logger.Send(LogType.Information, ClientFactory.UserID, $"Error in CheckIsLoggedOn(): {CoreUtils.FormatException(e)}");
  2161. }
  2162. else if (o is not null)
  2163. {
  2164. var row = o.Rows.FirstOrDefault();
  2165. if (row == null)
  2166. {
  2167. station.ID = Guid.Empty;
  2168. new Client<Login>().Save(station, "", (o1, e1) => { });
  2169. }
  2170. else if (!row.Get<Login, string>(c => c.StationID).Equals(station.StationID))
  2171. {
  2172. Logger.Send(LogType.Information, ClientFactory.UserID, "User logged in somewhere else!");
  2173. bLogout = true;
  2174. Dispatcher.Invoke(() => { Logout(); });
  2175. }
  2176. }
  2177. }
  2178. );
  2179. }
  2180. private void Heartbeat()
  2181. {
  2182. //Task.Run(() =>
  2183. //{
  2184. try
  2185. {
  2186. bool IsClockedOn = this.IsClockedOn();
  2187. if (IsClockedOn)
  2188. {
  2189. if ((_kanbantrackingassignment != null) && (_kanbantrackingassignment.Actual.Finish < DateTime.Now.TimeOfDay))
  2190. {
  2191. _kanbantrackingassignment.Actual.Finish = DateTime.Now.TimeOfDay;
  2192. new Client<Assignment>().Save(_kanbantrackingassignment, "");
  2193. }
  2194. if (Security.IsAllowed<MonitorApplicationWindows>())
  2195. {
  2196. if (ActivityHistory == null)
  2197. ActivityHistory = new LocalConfiguration<DailyActivityHistory>().Load();
  2198. var appname = OpenWindowGetter.GetActiveWindowProcess();
  2199. var title = OpenWindowGetter.GetActiveWindowTitle();
  2200. ActivityHistory.Activities[DateTime.Now] = (!string.IsNullOrWhiteSpace(appname) ? appname.Trim() + " - " : "") + title;
  2201. new LocalConfiguration<DailyActivityHistory>().Save(ActivityHistory);
  2202. }
  2203. }
  2204. PanelHost.Heartbeat();
  2205. foreach(var window in SecondaryWindows.Values)
  2206. {
  2207. window.Heartbeat();
  2208. }
  2209. }
  2210. catch (Exception err)
  2211. {
  2212. Logger.Send(LogType.Error, ClientFactory.UserID, string.Format("Exception in Heartbeat: {0}\n{1}", err.Message, err.StackTrace));
  2213. }
  2214. //});
  2215. }
  2216. private void Notifications_Changed(object sender)
  2217. {
  2218. if (Notifications.IsActive)
  2219. {
  2220. Notifications.Visibility = Visibility.Visible;
  2221. DockingGrid.ColumnDefinitions[1].Width = new GridLength(4, GridUnitType.Pixel);
  2222. DockingGrid.ColumnDefinitions[2].Width = Equals(0.0, DockingGrid.ColumnDefinitions[2].Width.Value)
  2223. ? new GridLength(300, GridUnitType.Pixel)
  2224. : DockingGrid.ColumnDefinitions[2].Width;
  2225. }
  2226. else
  2227. {
  2228. Notifications.Visibility = Visibility.Collapsed;
  2229. DockingGrid.ColumnDefinitions[1].Width = new GridLength(0, GridUnitType.Pixel);
  2230. DockingGrid.ColumnDefinitions[2].Width = new GridLength(0, GridUnitType.Pixel);
  2231. }
  2232. }
  2233. private void ReloadNotifications()
  2234. {
  2235. if (Security.CanView<Notification>())
  2236. Notifications.Refresh();
  2237. if (!NotificationsWatchDog.IsEnabled)
  2238. {
  2239. //Logger.Send(LogType.Information, ClientFactory.UserID, "Enabling Heartbeat");
  2240. NotificationsWatchDog.IsEnabled = true;
  2241. }
  2242. }
  2243. #endregion
  2244. private void RibbonWindow_PreviewMouseUp(object sender, MouseButtonEventArgs e)
  2245. {
  2246. PanelHost.IncrementTrackingModuleClick();
  2247. }
  2248. private void RibbonWindow_PreviewKeyUp(object sender, KeyEventArgs e)
  2249. {
  2250. PanelHost.IncrementTrackingModuleKey();
  2251. }
  2252. #region Recording
  2253. //private IntPtr myHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
  2254. //{
  2255. // switch (msg)
  2256. // {
  2257. // case 0x100:
  2258. // if (_subject != null)
  2259. // {
  2260. // _recorder.Stop();
  2261. // pausestarted = DateTime.Now;
  2262. // _subject.OnNext(new WampEvent() { Arguments = new[] { "EDIT" } });
  2263. // }
  2264. // break;
  2265. // default:
  2266. // messages.TryGetValue(msg, out int value);
  2267. // messages[msg] = value + 1;
  2268. // break;
  2269. // }
  2270. // return IntPtr.Zero;
  2271. //}
  2272. private void RecordScreenButton_Click(object sender, RoutedEventArgs e)
  2273. {
  2274. ToggleRecording();
  2275. }
  2276. private bool ToggleRecording()
  2277. {
  2278. if (!Security.IsAllowed<CanRecordScreen>())
  2279. return true;
  2280. if (_recorder is null)
  2281. {
  2282. var windowInteropHelper = new WindowInteropHelper(this);
  2283. var screen = Screen.FromHandle(windowInteropHelper.Handle);
  2284. _screenleft = screen.WorkingArea.Left;
  2285. _screentop = screen.WorkingArea.Top;
  2286. _screenwidth = screen.WorkingArea.Width;
  2287. _screenheight = screen.WorkingArea.Height;
  2288. //VIDEO_WIDTH = _screenwidth;
  2289. //VIDEO_HEIGHT = _screenheight;
  2290. //SetupJPEGEncoder();
  2291. messages.Clear();
  2292. _bitmaps.Clear();
  2293. ConnectToRecordNotes();
  2294. StartAudio();
  2295. _recorder = new DispatcherTimer();
  2296. _recorder.Tick += (timer, args) => { TakeScreenShot(); };
  2297. _recorder.Interval = TimeSpan.FromMilliseconds(1000 / FRAMES_PER_SECOND);
  2298. _recorder.Start();
  2299. VideoRecordingStatus.Source = PRSDesktop.Resources.videorecording.AsBitmapImage();
  2300. RecordingNotesStatus.Source = PRSDesktop.Resources.speechbubble.AsGrayScale().AsBitmapImage();
  2301. RecordingNotesButton.Visibility = Visibility.Visible;
  2302. AudioRecordingStatus.Source = PRSDesktop.Resources.audiorecording.AsGrayScale().AsBitmapImage();
  2303. AudioRecordingButton.Visibility = Visibility.Visible;
  2304. }
  2305. else
  2306. {
  2307. using (new WaitCursor())
  2308. {
  2309. StopRecording();
  2310. _recorder.Stop();
  2311. _recorder = null;
  2312. DisconnectRecorderNotes();
  2313. VideoRecordingStatus.Source = PRSDesktop.Resources.videorecording.AsGrayScale().AsBitmapImage();
  2314. RecordingNotesStatus.Source = PRSDesktop.Resources.speechbubble.AsGrayScale().AsBitmapImage();
  2315. RecordingNotesButton.Visibility = Visibility.Hidden;
  2316. AudioRecordingStatus.Source = PRSDesktop.Resources.audiorecording.AsGrayScale().AsBitmapImage();
  2317. AudioRecordingButton.Visibility = Visibility.Hidden;
  2318. var filename = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyVideos),
  2319. string.Format("PRS Screen Recording {0:yyyy-MM-dd hh-mm-ss-ff}.avi", DateTime.Now));
  2320. ProcessScreenShots(filename);
  2321. }
  2322. }
  2323. return true;
  2324. }
  2325. private void StopRecording()
  2326. {
  2327. try
  2328. {
  2329. _audio?.StopRecording();
  2330. AudioRecordingStatus.Source = PRSDesktop.Resources.audiorecording.AsGrayScale().AsBitmapImage();
  2331. }
  2332. catch (Exception e)
  2333. {
  2334. Logger.Send(LogType.Error, "", string.Format("Unable to stop Audio Recording: {0}\n{1}", e.Message, e.StackTrace));
  2335. }
  2336. }
  2337. private void StartAudio()
  2338. {
  2339. _audioMuted = true;
  2340. _audioStream = new MemoryStream();
  2341. _audio = new WaveIn
  2342. {
  2343. DeviceNumber = 0,
  2344. WaveFormat = new WaveFormat(44100, 16, 2)
  2345. };
  2346. _audio.DataAvailable += (o, e) =>
  2347. {
  2348. var buf = _audioMuted ? new byte[e.BytesRecorded] : e.Buffer;
  2349. _audioStream.Write(buf, 0, e.BytesRecorded);
  2350. };
  2351. try
  2352. {
  2353. _audio.StartRecording();
  2354. AudioRecordingStatus.Source = PRSDesktop.Resources.audiorecording.AsBitmapImage();
  2355. }
  2356. catch (Exception e)
  2357. {
  2358. Logger.Send(LogType.Error, "", string.Format("Unable to start Audio Recording: {0}\n{1}", e.Message, e.StackTrace));
  2359. AudioRecordingStatus.Source = PRSDesktop.Resources.audiorecording.AsGrayScale().AsBitmapImage();
  2360. }
  2361. }
  2362. private bool ToggleRecordingAudio()
  2363. {
  2364. if (!Security.IsAllowed<CanRecordScreen>())
  2365. return true;
  2366. if (_recorder != null)
  2367. {
  2368. _audioMuted = !_audioMuted;
  2369. AudioRecordingStatus.Source = _audioMuted
  2370. ? PRSDesktop.Resources.audiorecording.AsGrayScale().AsBitmapImage()
  2371. : PRSDesktop.Resources.audiorecording.AsBitmapImage();
  2372. }
  2373. return true;
  2374. }
  2375. private void DisconnectRecorderNotes()
  2376. {
  2377. if (_client != null)
  2378. {
  2379. _client.WriteAsync("QUIT");
  2380. _client.StopAsync();
  2381. _client = null;
  2382. }
  2383. }
  2384. private void ConnectToRecordNotes()
  2385. {
  2386. var filename = Debugger.IsAttached
  2387. ? "c:\\development\\comal\\prsrecordingnotes\\bin\\debug\\prsrecordingnotes.exe"
  2388. : Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "recordingnotes", "prsrecordingnotes.exe");
  2389. Logger.Send(LogType.Information, "", "Recording Notes: " + filename);
  2390. _recordingnotes = Process.Start(filename);
  2391. //PipeSecurity sec = new System.IO.Pipes.PipeSecurity();
  2392. //sec.SetAccessRule(new PipeAccessRule("Everyone", PipeAccessRights.ReadWrite, AccessControlType.Allow));
  2393. _client = new PipeServer<string>("PRSScreenRecorder", formatter:new BinaryFormatter()); //, sec);
  2394. _client.ClientConnected += (o, args) => args.Connection.WriteAsync("Connected to PRSScreenRecorder");
  2395. _client.MessageReceived += (o, args) =>
  2396. {
  2397. if (string.Equals(args.Message, "RESUME"))
  2398. Dispatcher.Invoke(() =>
  2399. {
  2400. _audio?.StartRecording();
  2401. totalpauses += DateTime.Now - pausestarted;
  2402. _recorder?.Start();
  2403. Activate();
  2404. Focus();
  2405. });
  2406. };
  2407. _client.StartAsync();
  2408. }
  2409. private bool ShowRecordingNotes()
  2410. {
  2411. if (_recorder != null)
  2412. {
  2413. _audio?.StopRecording();
  2414. _recorder.Stop();
  2415. pausestarted = DateTime.Now;
  2416. _client?.WriteAsync("EDIT");
  2417. //_subject.OnNext(new WampEvent() { Arguments = new[] { "EDIT" } });
  2418. }
  2419. return true;
  2420. }
  2421. private void TakeScreenShot()
  2422. {
  2423. using (var bmp = new ScreenCapture().CaptureScreen(_screenleft, _screentop, _screenwidth, _screenheight))
  2424. {
  2425. var cursor = PointToScreen(Mouse.GetPosition(this));
  2426. using (var g = Graphics.FromImage(bmp))
  2427. {
  2428. var brush = new SolidBrush(System.Drawing.Color.FromArgb(128, 255, 255, 0));
  2429. g.FillEllipse(brush, new RectangleF((float)cursor.X - 25F, (float)cursor.Y - 25F, 50F, 50F));
  2430. var pen = new Pen(System.Drawing.Color.Black, 0.75F);
  2431. g.DrawLine(pen, (float)cursor.X - 10F, (float)cursor.Y, (float)cursor.X + 10F, (float)cursor.Y);
  2432. g.DrawLine(pen, (float)cursor.X, (float)cursor.Y - 10F, (float)cursor.X, (float)cursor.Y + 10F);
  2433. }
  2434. var key = DateTime.Now - totalpauses;
  2435. using (var reduced = ReduceBitmap(bmp, VIDEO_WIDTH, VIDEO_HEIGHT))
  2436. {
  2437. var ms = new MemoryStream();
  2438. reduced.Save(ms, ImageFormat.Png);
  2439. ms.Position = 0;
  2440. _bitmaps[key] = ms;
  2441. }
  2442. }
  2443. }
  2444. public Bitmap ReduceBitmap(Bitmap original, int reducedWidth, int reducedHeight)
  2445. {
  2446. var reduced = new Bitmap(reducedWidth, reducedHeight);
  2447. using (var dc = Graphics.FromImage(reduced))
  2448. {
  2449. // Figure out the ratio
  2450. var ratioX = (double)reducedWidth / original.Width;
  2451. var ratioY = (double)reducedHeight / original.Height;
  2452. // use whichever multiplier is smaller
  2453. var ratio = ratioX < ratioY ? ratioX : ratioY;
  2454. // now we can get the new height and width
  2455. var newHeight = Convert.ToInt32(original.Height * ratio);
  2456. var newWidth = Convert.ToInt32(original.Width * ratio);
  2457. // Now calculate the X,Y position of the upper-left corner
  2458. // (one of these will always be zero)
  2459. var posX = Convert.ToInt32((reducedWidth - original.Width * ratio) / 2);
  2460. var posY = Convert.ToInt32((reducedHeight - original.Height * ratio) / 2);
  2461. dc.InterpolationMode = InterpolationMode.HighQualityBicubic;
  2462. dc.Clear(System.Drawing.Color.Black); // white padding
  2463. //dc.DrawImage(original, posX, posY, newWidth, newHeight);
  2464. dc.DrawImage(original, new Rectangle(posX, posY, newWidth, newHeight), new Rectangle(0, 0, original.Width, original.Height),
  2465. GraphicsUnit.Pixel);
  2466. }
  2467. return reduced;
  2468. }
  2469. public static byte[] BitmapToByteArray(Bitmap bitmap, int width, int height)
  2470. {
  2471. // and buffer of appropriate size for storing its bits
  2472. var buffer = new byte[width * height * 4];
  2473. var pixelFormat = PixelFormat.Format32bppRgb;
  2474. // Now copy bits from bitmap to buffer
  2475. var bits = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, pixelFormat);
  2476. //Marshal.Copy(bits.Scan0, buffer, 0, buffer.Length);
  2477. Marshal.Copy(bits.Scan0, buffer, 0, buffer.Length);
  2478. bitmap.UnlockBits(bits);
  2479. return buffer;
  2480. }
  2481. private void ProcessScreenShots(string filename)
  2482. {
  2483. if (!_bitmaps.Any() || _audioStream is null)
  2484. return;
  2485. Progress.Show("Saving Video");
  2486. var framRate = 10;
  2487. using (var writer = new AviWriter(filename))
  2488. {
  2489. writer.FramesPerSecond = framRate;
  2490. writer.EmitIndex1 = true;
  2491. _audioStream.Position = 0;
  2492. var audio = writer.AddAudioStream(2);
  2493. //audio.WriteBlock(_audioStream.GetBuffer(), 0, (int)_audioStream.Length);
  2494. //File.WriteAllBytes(Path.ChangeExtension(filename, "wav"), _audioStream.GetBuffer());
  2495. var audioByteRate = audio.BitsPerSample / 8 * audio.ChannelCount * audio.SamplesPerSecond;
  2496. var audioBlockSize = (int)(audioByteRate / writer.FramesPerSecond);
  2497. var audioBuffer = new byte[audioBlockSize];
  2498. _audioStream.Position = 0;
  2499. var encoder = new MJpegWpfVideoEncoder(VIDEO_WIDTH, VIDEO_HEIGHT, 50);
  2500. var stream = writer.AddEncodingVideoStream(encoder, true, VIDEO_WIDTH, VIDEO_HEIGHT);
  2501. //var encoder = new SharpAvi.Codecs.UncompressedVideoEncoder(VIDEO_WIDTH, VIDEO_HEIGHT);
  2502. //var stream = writer.AddEncodingVideoStream(encoder,true,VIDEO_WIDTH, VIDEO_HEIGHT);
  2503. //stream.Codec = CodecIds.Uncompressed;
  2504. //stream.BitsPerPixel = BitsPerPixel.Bpp16;
  2505. IEnumerable<DateTime> keys = _bitmaps.Keys.OrderBy(x => x);
  2506. var start = keys.First();
  2507. var end = keys.Last();
  2508. for (var cur = start; cur <= end; cur = cur + TimeSpan.FromMilliseconds(100))
  2509. {
  2510. Progress.SetMessage(string.Format("Processing ({0:F2} complete)",
  2511. (cur - start).TotalSeconds * 100.0F / (end - start).TotalSeconds));
  2512. var key = keys.LastOrDefault(x => x <= cur);
  2513. if (_bitmaps.ContainsKey(key))
  2514. {
  2515. var frame = (Image.FromStream(_bitmaps[key]) as Bitmap)!;
  2516. //frame.RotateFlip(RotateFlipType.RotateNoneFlipY);
  2517. var buf = BitmapToByteArray(frame, stream.Width, stream.Height);
  2518. stream.WriteFrame(true, buf, 0, buf.Length);
  2519. if (_audioStream.Position < _audioStream.Length)
  2520. {
  2521. var bytes = _audioStream.Read(audioBuffer, 0, audioBlockSize);
  2522. audio.WriteBlock(audioBuffer, 0, bytes);
  2523. }
  2524. }
  2525. }
  2526. writer.Close();
  2527. //foreach (var key in _bitmaps.Keys)
  2528. // File.Delete(_bitmaps[key]);
  2529. }
  2530. Progress.SetMessage("Transcoding");
  2531. //var inputFile = new MediaFile { Filename = filename };
  2532. //var outputFile = new MediaFile { Filename = Path.ChangeExtension(filename, "mp4") };
  2533. //using (var engine = new Engine())
  2534. //{
  2535. // //engine.ConvertProgressEvent += ConvertProgressEvent;
  2536. // engine.Convert(inputFile, outputFile);
  2537. //}
  2538. Progress.Close();
  2539. var dirName = Path.GetDirectoryName(filename);
  2540. if (dirName is not null)
  2541. {
  2542. var startInfo = new ProcessStartInfo(dirName);
  2543. startInfo.Verb = "open";
  2544. startInfo.UseShellExecute = true;
  2545. Process.Start(startInfo);
  2546. //MessageBox.Show("Recording Saved");
  2547. }
  2548. }
  2549. private void VideoRecordingButton_Click(object sender, RoutedEventArgs e)
  2550. {
  2551. ToggleRecording();
  2552. }
  2553. private void AudioRecordingButton_Click(object sender, RoutedEventArgs e)
  2554. {
  2555. ToggleRecordingAudio();
  2556. }
  2557. private void RecordingNotesButton_Click(object sender, RoutedEventArgs e)
  2558. {
  2559. ShowRecordingNotes();
  2560. }
  2561. #endregion
  2562. public static void ActivateWindow(Window window)
  2563. {
  2564. var hwnd = new WindowInteropHelper(window).EnsureHandle();
  2565. var threadId1 = GetWindowThreadProcessId(GetForegroundWindow(), IntPtr.Zero);
  2566. var threadId2 = GetWindowThreadProcessId(hwnd, IntPtr.Zero);
  2567. if (threadId1 != threadId2)
  2568. {
  2569. AttachThreadInput(threadId1, threadId2, true);
  2570. SetForegroundWindow(hwnd);
  2571. AttachThreadInput(threadId1, threadId2, false);
  2572. }
  2573. else
  2574. {
  2575. SetForegroundWindow(hwnd);
  2576. }
  2577. }
  2578. private static IntPtr GetForegroundWindow()
  2579. {
  2580. var active = GetActiveWindow();
  2581. var window = Application.Current.Windows.OfType<Window>().SingleOrDefault(x => new WindowInteropHelper(x).Handle == active);
  2582. var hwnd = new WindowInteropHelper(window).EnsureHandle();
  2583. return hwnd;
  2584. }
  2585. [DllImport("user32.dll", SetLastError = true)]
  2586. private static extern IntPtr SetForegroundWindow(IntPtr hWnd);
  2587. [DllImport("user32.dll")]
  2588. private static extern uint GetWindowThreadProcessId(IntPtr hWnd, IntPtr ProcessId);
  2589. [DllImport("user32.dll")]
  2590. private static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, bool fAttach);
  2591. [DllImport("user32.dll")]
  2592. private static extern IntPtr GetActiveWindow();
  2593. #region Check For Updates
  2594. private string GetUpdateLocation()
  2595. {
  2596. if (App.DatabaseSettings.DatabaseType == DatabaseType.Networked)
  2597. {
  2598. string url = "";
  2599. //var domain = App.DatabaseSettings.URL.Split(new[] { "://" }, StringSplitOptions.RemoveEmptyEntries).Last();
  2600. //var port = App.DatabaseSettings.Port;
  2601. var domain = ClientFactory.Parameters?.FirstOrDefault()?.ToString() ?? "";
  2602. domain = domain.Split(new[] { "://" }, StringSplitOptions.RemoveEmptyEntries).LastOrDefault() ?? "";
  2603. if (!String.IsNullOrWhiteSpace(domain))
  2604. {
  2605. try
  2606. {
  2607. var client = new HttpClient { BaseAddress = new Uri($"https://{domain}") };
  2608. client.GetAsync("operations").Wait();
  2609. url = $"https://{domain}";
  2610. }
  2611. catch (Exception)
  2612. {
  2613. url = $"http://{domain}";
  2614. }
  2615. }
  2616. return url;
  2617. }
  2618. else
  2619. return Path.Combine(CoreUtils.GetCommonAppData("PRSServer"), "update");
  2620. }
  2621. private string GetLatestVersion(string location)
  2622. {
  2623. return Client.Version();
  2624. }
  2625. private string GetReleaseNotes(string location)
  2626. {
  2627. return Client.ReleaseNotes();
  2628. }
  2629. private byte[]? GetInstaller(string location)
  2630. {
  2631. return Client.Installer();
  2632. }
  2633. private void CheckForUpdates()
  2634. {
  2635. Update.CheckForUpdates(
  2636. GetUpdateLocation, GetLatestVersion, GetReleaseNotes, GetInstaller, null, App.AutoUpdateSettings.Elevated, "PRSDesktopSetup.exe");
  2637. }
  2638. #endregion
  2639. #region Modules + Reports
  2640. public void ClearActions()
  2641. {
  2642. foreach (var module in CurrentModules)
  2643. {
  2644. if (module.Parent is Fluent.RibbonGroupBox bar)
  2645. bar.Items.Remove(module);
  2646. }
  2647. CurrentModules.Clear();
  2648. }
  2649. public void ClearReports()
  2650. {
  2651. if (CurrentTab is not null)
  2652. {
  2653. var ReportsBar = FindRibbonBar(CurrentTab, x => x.Header.Equals("Print"));
  2654. if (ReportsBar is not null)
  2655. {
  2656. ReportsBar.Visibility = Security.IsAllowed<CanPrintReports>() ? Visibility.Visible : Visibility.Collapsed;
  2657. ReportsBar.Items.Clear();
  2658. }
  2659. }
  2660. }
  2661. public void CreateReport(PanelAction action)
  2662. {
  2663. if (CurrentTab is null)
  2664. return;
  2665. var ReportsBar = FindRibbonBar(CurrentTab, x => x.Header.Equals("Print"));
  2666. if (ReportsBar is not null)
  2667. {
  2668. var button = new Fluent.Button
  2669. {
  2670. Header = action.Caption,
  2671. LargeIcon = action.Image.AsBitmapImage(),
  2672. MinWidth = 60
  2673. };
  2674. if (action.Menu is not null)
  2675. {
  2676. button.ContextMenu = action.Menu;
  2677. }
  2678. button.Click += (o, e) =>
  2679. {
  2680. action.Execute();
  2681. };
  2682. ReportsBar.Items.Add(button);
  2683. }
  2684. }
  2685. private NullConverter<Visibility>? _vis = null;
  2686. public void CreatePanelAction(PanelAction action)
  2687. {
  2688. if (CurrentTab is null)
  2689. return;
  2690. if (_vis == null)
  2691. {
  2692. _vis = new();
  2693. _vis.Converting += (o, e) =>
  2694. {
  2695. };
  2696. }
  2697. var Actions = FindRibbonBar(CurrentTab, x => x.Header.Equals("Actions"));
  2698. if (Actions is not null)
  2699. {
  2700. if (!CurrentModules.Any(x => x.GetType().Equals(typeof(RibbonSeparator))))
  2701. {
  2702. var sep = new RibbonSeparator();
  2703. CurrentModules.Add(sep);
  2704. Actions.Items.Add(sep);
  2705. }
  2706. if (action.OnPopulate != null)
  2707. {
  2708. Fluent.DropDownButton button = null;
  2709. if (action.OnExecute != null)
  2710. {
  2711. button = new Fluent.SplitButton();
  2712. ((Fluent.SplitButton)button).Click += (o, e) => action.Execute();
  2713. }
  2714. else
  2715. button = new Fluent.DropDownButton();
  2716. button.MinWidth = 60;
  2717. button.DataContext = action;
  2718. button.DropDownOpened += (sender, args) => { button.ItemsSource = CreateMenuItems(action); };
  2719. button.Bind<PanelAction, String>(Fluent.DropDownButton.HeaderProperty, x => x.Caption, null);
  2720. button.Bind<PanelAction, Bitmap?>(Fluent.DropDownButton.LargeIconProperty, x => x.Image,
  2721. new BitmapToBitmapImageConverter());
  2722. button.Bind<PanelAction, ContextMenu?>(ContextMenuProperty, x => x.Menu);
  2723. button.Bind<PanelAction, bool>(IsEnabledProperty, x => x.IsEnabled);
  2724. button.Bind<PanelAction, Visibility>(Fluent.DropDownButton.VisibilityProperty, x => x.Visibility, _vis);
  2725. Actions.Items.Add(button);
  2726. CurrentModules.Add(button);
  2727. }
  2728. else
  2729. {
  2730. var button = new Fluent.Button()
  2731. {
  2732. MinWidth = 60,
  2733. DataContext = action
  2734. };
  2735. button.Bind<PanelAction, String>(Fluent.Button.HeaderProperty, x => x.Caption, null);
  2736. button.Bind<PanelAction, Bitmap?>(Fluent.Button.LargeIconProperty, x => x.Image,
  2737. new BitmapToBitmapImageConverter());
  2738. button.Bind<PanelAction, ContextMenu?>(Fluent.Button.ContextMenuProperty, x => x.Menu);
  2739. button.Bind<PanelAction, bool>(Fluent.Button.IsEnabledProperty, x => x.IsEnabled);
  2740. button.Bind<PanelAction, Visibility>(Fluent.Button.VisibilityProperty, x => x.Visibility, _vis);
  2741. button.Click += (o, e) => action.Execute();
  2742. Actions.Items.Add(button);
  2743. CurrentModules.Add(button);
  2744. }
  2745. }
  2746. }
  2747. private static ObservableCollection<MenuItem> CreateMenuItems(PanelAction action)
  2748. {
  2749. var items = new ObservableCollection<MenuItem>();
  2750. var entries = action.Populate();
  2751. if (entries != null)
  2752. {
  2753. foreach (var entry in entries)
  2754. {
  2755. var item = new Fluent.MenuItem()
  2756. {
  2757. Header = entry.Caption,
  2758. DataContext = entry.Data,
  2759. Icon = entry.Image?.AsBitmapImage()
  2760. };
  2761. item.Click += (o, eventArgs) => entry.Execute();
  2762. items.Add(item);
  2763. }
  2764. }
  2765. return items;
  2766. }
  2767. #endregion
  2768. #region Tracking Kanban
  2769. private void SelectTask_Click(object sender, RoutedEventArgs e)
  2770. {
  2771. ContextMenu menu = new ContextMenu();
  2772. MenuItem others = new MenuItem() { Header = "Other Tasks" };
  2773. using (new WaitCursor())
  2774. {
  2775. var kanbans = new Client<KanbanSubscriber>().Query(
  2776. new Filter<KanbanSubscriber>(x => x.Employee.UserLink.ID).IsEqualTo(ClientFactory.UserGuid)
  2777. .And(x => x.Kanban.Completed).IsEqualTo(DateTime.MinValue)
  2778. .And(x => x.Kanban.Closed).IsEqualTo(DateTime.MinValue),
  2779. Columns.None<KanbanSubscriber>().Add(x => x.Kanban.ID)
  2780. .Add(x => x.Kanban.Number)
  2781. .Add(x => x.Kanban.Title)
  2782. .Add(x => x.Assignee),
  2783. new SortOrder<KanbanSubscriber>(x => x.Kanban.Number, SortDirection.Ascending)
  2784. );
  2785. foreach (var row in kanbans.Rows)
  2786. {
  2787. CreateTaskMenu(row.Get<KanbanSubscriber, bool>(c => c.Assignee) ? menu.Items : others.Items,
  2788. String.Format("{0} {1}",
  2789. row.Get<KanbanSubscriber, int>(c => c.Kanban.Number),
  2790. row.Get<KanbanSubscriber, String>(c => c.Kanban.Title)),
  2791. row.Get<KanbanSubscriber, Guid>(c => c.Kanban.ID)
  2792. );
  2793. }
  2794. menu.Items.Add(new Separator());
  2795. menu.Items.Add(others);
  2796. menu.Items.Add(new Separator());
  2797. CreateTaskMenu(menu.Items, "(No Task Selected)", Guid.Empty);
  2798. }
  2799. menu.IsOpen = true;
  2800. }
  2801. private Assignment? _kanbantrackingassignment = null;
  2802. private void SetTrackingKanban(Guid kanbanID, string header)
  2803. {
  2804. SelectedTaskName.Content = header;
  2805. var createNewAssignment = false;
  2806. if (_kanbantrackingassignment is not null)
  2807. {
  2808. if (_kanbantrackingassignment.Actual.Finish < DateTime.Now.TimeOfDay)
  2809. {
  2810. _kanbantrackingassignment.Actual.Finish = DateTime.Now.TimeOfDay;
  2811. new Client<Assignment>().Save(_kanbantrackingassignment, "");
  2812. }
  2813. // Update Existing Kanban
  2814. if (kanbanID == Guid.Empty)
  2815. _kanbantrackingassignment = null;
  2816. else if (_kanbantrackingassignment.Task.ID != kanbanID)
  2817. {
  2818. createNewAssignment = true;
  2819. }
  2820. }
  2821. else if (kanbanID != Guid.Empty)
  2822. {
  2823. createNewAssignment = true;
  2824. }
  2825. if (createNewAssignment)
  2826. {
  2827. _kanbantrackingassignment = new Assignment();
  2828. _kanbantrackingassignment.Task.ID = kanbanID;
  2829. _kanbantrackingassignment.EmployeeLink.ID = App.EmployeeID;
  2830. _kanbantrackingassignment.Title = header;
  2831. _kanbantrackingassignment.Date = DateTime.Today;
  2832. _kanbantrackingassignment.Actual.Start = DateTime.Now.TimeOfDay;
  2833. _kanbantrackingassignment.Actual.Finish = DateTime.Now.TimeOfDay.Add(new TimeSpan(0, 2, 0));
  2834. new Client<Assignment>().Save(_kanbantrackingassignment, "");
  2835. }
  2836. }
  2837. private void ClearTrackingKanban()
  2838. => SetTrackingKanban(Guid.Empty, "(No Task Selected)");
  2839. private void CreateTaskMenu(ItemCollection items, String title, Guid id)
  2840. {
  2841. var item = new MenuItem()
  2842. {
  2843. Header = title,
  2844. Tag = id
  2845. };
  2846. item.Click += (o, args) =>
  2847. {
  2848. if (o is not MenuItem menu) return;
  2849. SetTrackingKanban((Guid)item.Tag, (menu.Header as string) ?? "");
  2850. };
  2851. items.Add(item);
  2852. }
  2853. #endregion
  2854. private void DockPanelBorder_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
  2855. {
  2856. if (sender is not Border border || !border.IsVisible)
  2857. return;
  2858. var dock = border.Child is IDockPanel panel ? panel : border.Child?.FindVisualChildren<IDockPanel>().FirstOrDefault();
  2859. if (dock is null)
  2860. return;
  2861. dock.Refresh();
  2862. }
  2863. private void DockPanel_OnIsActiveChanged(object? sender, EventArgs e)
  2864. {
  2865. if (sender is not LayoutAnchorable layout)
  2866. return;
  2867. var content = layout.Content as DependencyObject;
  2868. var dock = content is IDockPanel panel ? panel : content?.FindVisualChildren<IDockPanel>().FirstOrDefault();
  2869. if (dock is null)
  2870. return;
  2871. if (layout.IsActive && layout.IsVisible)
  2872. dock.Refresh();
  2873. }
  2874. private void _ribbon_OnPreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
  2875. {
  2876. e.Handled = true;
  2877. }
  2878. #region Backstage Functions
  2879. private enum DatabaseConfigurationResult
  2880. {
  2881. RestartRequired,
  2882. RestartNotRequired,
  2883. Cancel
  2884. }
  2885. private DatabaseConfigurationResult ShowDatabaseConfiguration()
  2886. {
  2887. DatabaseConfigurationResult result;
  2888. var config = new DataBaseConfiguration();
  2889. if (config.ShowDialog() == true)
  2890. {
  2891. var newsettings = new LocalConfiguration<DatabaseSettings>(App.Profile).Load();
  2892. if (newsettings.RestartRequired(App.DatabaseSettings))
  2893. {
  2894. result = DatabaseConfigurationResult.RestartRequired;
  2895. }
  2896. else
  2897. {
  2898. result = DatabaseConfigurationResult.RestartNotRequired;
  2899. }
  2900. if ((newsettings.DatabaseType == DatabaseType.Standalone) && (newsettings.ColorScheme != App.DatabaseSettings.ColorScheme))
  2901. {
  2902. App.DatabaseSettings.ColorScheme = newsettings.ColorScheme;
  2903. ApplyColorScheme();
  2904. }
  2905. }
  2906. else
  2907. {
  2908. result = DatabaseConfigurationResult.Cancel;
  2909. }
  2910. return result;
  2911. }
  2912. private void DatabaseSettings_OnClick(object sender, RoutedEventArgs e)
  2913. {
  2914. switch (ShowDatabaseConfiguration())
  2915. {
  2916. case DatabaseConfigurationResult.RestartRequired:
  2917. MessageBox.Show("Please restart the application to apply these changes!");
  2918. break;
  2919. }
  2920. }
  2921. private void CompanyInformation_OnClick(object sender, RoutedEventArgs e)
  2922. {
  2923. var info = new Client<CompanyInformation>().Load().FirstOrDefault();
  2924. if (info == null)
  2925. info = new CompanyInformation();
  2926. new DynamicDataGrid<CompanyInformation>().EditItems(new[] { info });
  2927. }
  2928. private void SecurityDefaultsButton_OnClick(object sender, RoutedEventArgs e)
  2929. {
  2930. var window = new GlobalTokenWindow();
  2931. window.ShowDialog();
  2932. Security.Reset();
  2933. }
  2934. private void SystemLogsButton_OnClick(object sender, RoutedEventArgs e)
  2935. {
  2936. var logfile = Path.Combine(CoreUtils.GetPath(), string.Format("{0:yyyy-MM-dd}.log", DateTime.Today));
  2937. if (File.Exists(logfile))
  2938. {
  2939. var startInfo = new ProcessStartInfo("notepad.exe", logfile);
  2940. startInfo.Verb = "open";
  2941. startInfo.UseShellExecute = true;
  2942. Process.Start(startInfo);
  2943. }
  2944. else
  2945. {
  2946. MessageBox.Show(logfile + " does not exist!");
  2947. }
  2948. }
  2949. private void DocumentTypeList_OnClick(object sender, RoutedEventArgs e)
  2950. {
  2951. var list = new MasterList(typeof(DocumentType));
  2952. list.ShowDialog();
  2953. }
  2954. private void EditDetailsButton_OnClick(object sender, RoutedEventArgs e)
  2955. {
  2956. var employee = new Client<Employee>().Query(
  2957. new Filter<Employee>(x => x.UserLink.ID).IsEqualTo(ClientFactory.UserGuid))
  2958. .Rows.FirstOrDefault()?.ToObject<Employee>();
  2959. var item = new MyDetailsConfiguration(employee);
  2960. item.User = ClientFactory.UserGuid;
  2961. var buttons = new DynamicEditorButtons();
  2962. buttons.Add("Change Password", null, item, (sender, item) =>
  2963. {
  2964. var details = (item as MyDetailsConfiguration)!;
  2965. var changePassword = new ChangePassword(details.User);
  2966. if (changePassword.ShowDialog() == true && changePassword.Password != null)
  2967. {
  2968. var newUser = new User();
  2969. newUser.ID = details.User;
  2970. ChangePassword.ChangeUserPassword(newUser, changePassword.Password);
  2971. new Client<User>().Save(newUser, "Changed Password");
  2972. MessageBox.Show("Password changed!");
  2973. }
  2974. });
  2975. var editor = new DynamicEditorForm(typeof(MyDetailsConfiguration), buttons: buttons);
  2976. if (employee == null)
  2977. {
  2978. editor.OnFormCustomiseEditor += (sender, items, column, editor) =>
  2979. {
  2980. editor.Editable = Editable.Disabled;
  2981. };
  2982. }
  2983. editor.Items = new BaseObject[] { item };
  2984. if (editor.ShowDialog() == true)
  2985. {
  2986. if (employee != null)
  2987. {
  2988. item.SaveTo(employee);
  2989. new Client<Employee>().Save(employee, "Edited by user");
  2990. }
  2991. }
  2992. }
  2993. private void LogoutButton_OnClick(object sender, RoutedEventArgs e)
  2994. {
  2995. Logout();
  2996. }
  2997. private void LoginButton_OnClick(object sender, RoutedEventArgs e)
  2998. {
  2999. if (DoLogin() == ValidationStatus.VALID)
  3000. AfterLogin(null);
  3001. }
  3002. private void ExitButton_OnClick(object sender, RoutedEventArgs e)
  3003. {
  3004. //_closingFromSystemMenu = true;
  3005. Close();
  3006. }
  3007. #endregion
  3008. }