MainWindow.xaml.cs 168 KB

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