MainWindow.xaml.cs 179 KB

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