MainWindow.xaml.cs 174 KB

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