MainWindow.xaml.cs 179 KB

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