MainWindow.xaml.cs 176 KB

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