MainWindow.xaml.cs 163 KB

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