MainWindow.xaml.cs 169 KB

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