MainWindow.xaml.cs 169 KB

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