MainWindow.xaml.cs 168 KB

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