MainWindow.xaml.cs 157 KB

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