MainWindow.xaml.cs 176 KB

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