FactoryPanel.xaml.cs 124 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.ObjectModel;
  4. using System.Drawing;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using System.Windows;
  9. using System.Windows.Controls;
  10. using System.Windows.Controls.Primitives;
  11. using System.Windows.Input;
  12. using System.Windows.Media;
  13. using System.Windows.Media.Imaging;
  14. using Comal.Classes;
  15. using InABox.Clients;
  16. using InABox.Configuration;
  17. using InABox.Core;
  18. using InABox.DynamicGrid;
  19. using InABox.Core.Reports;
  20. using InABox.Wpf.Reports;
  21. using InABox.WPF;
  22. using Motorola.Snapi;
  23. using Motorola.Snapi.Constants.Enums;
  24. using Motorola.Snapi.EventArguments;
  25. using BarcodeType = Comal.Classes.BarcodeType;
  26. using Color = System.Drawing.Color;
  27. using Image = System.Windows.Controls.Image;
  28. using InABox.Wpf;
  29. using System.ComponentModel;
  30. namespace PRSDesktop
  31. {
  32. /// <summary>
  33. /// Interaction logic for FactoryPanel.xaml
  34. /// </summary>
  35. public partial class FactoryPanel : IPanel<ManufacturingPacket>
  36. {
  37. private readonly BitmapImage barcode = PRSDesktop.Resources.barcode.AsBitmapImage();
  38. private readonly BitmapImage disabled = PRSDesktop.Resources.disabled.AsBitmapImage();
  39. private readonly BitmapImage speechbubble = PRSDesktop.Resources.speechbubble.AsBitmapImage();
  40. private readonly BitmapImage starred = PRSDesktop.Resources.report.AsBitmapImage(48, 48);
  41. private readonly BitmapImage grouped = PRSDesktop.Resources.grouped.AsBitmapImage();
  42. private SetoutDocument[] documents = [];
  43. private readonly List<IMotorolaBarcodeScanner> _scanners = [];
  44. private readonly string NEARLYDUE_COLOR = "Orange";
  45. private readonly string NOTYETDUE_COLOR = "PaleGreen";
  46. private readonly string OVERDUE_COLOR = "Salmon";
  47. private readonly string PRIORITY_COLOR = "Red";
  48. private readonly string QA_COLOR = "Silver";
  49. private readonly string SELECTED_COLOR = "Yellow";
  50. private readonly string SHARED_COLOR = "Lime";
  51. private readonly string TREATED_COLOR = "DarkOrchid";
  52. private Button? _currentButton;
  53. private PDFEditorControl? PDFEditor;
  54. private QAGrid? QAGrid;
  55. private readonly FactoryFloorLocalSettings _settings;
  56. private readonly PanelAction _togglePackPanel;
  57. public FactoryPanel()
  58. {
  59. _settings = new LocalConfiguration<FactoryFloorLocalSettings>().Load();
  60. if (_settings.Section.Equals(CoreUtils.FullGuid) && _settings.Station.Equals(-1))
  61. {
  62. var user = new UserConfiguration<FactoryFloorSettings>().Load();
  63. _settings.Section = user.Section;
  64. _settings.Station = user.Station;
  65. new LocalConfiguration<FactoryFloorLocalSettings>().Save(_settings);
  66. }
  67. InitializeComponent();
  68. var CanConfigure = Security.IsAllowed<CanConfigureFactoryFloor>();
  69. Section.IsEnabled = CanConfigure;
  70. Station.IsEnabled = CanConfigure;
  71. PendingVisible = Security.IsAllowed<CanManagePendingPackets>();
  72. Kanbans = new ObservableCollection<ManufacturingKanban>();
  73. RackContents.ItemsSource = rackcontents;
  74. RackPanel.Visibility = _settings.SidePanel == FactorySidePanel.Racks
  75. ? Visibility.Visible
  76. : Visibility.Collapsed;
  77. PackPanel.Visibility = _settings.SidePanel == FactorySidePanel.Packs
  78. ? Visibility.Visible
  79. : Visibility.Collapsed;
  80. }
  81. public bool IsReady { get; set; }
  82. public void Setup()
  83. {
  84. var setups = new MultiQuery();
  85. setups.Add<ManufacturingFactory>();
  86. setups.Add(
  87. new Filter<ManufacturingSection>(x => x.Hidden).IsEqualTo(false),
  88. null,
  89. new SortOrder<ManufacturingSection>(x => x.Factory.Sequence).ThenBy(x => x.Sequence)
  90. );
  91. setups.Add<ManufacturingTrolley>();
  92. setups.Add(
  93. LookupFactory.DefineFilter<Employee>(),
  94. new Columns<Employee>(x => x.ID, x => x.Name, x => x.UserLink.ID),
  95. new SortOrder<Employee>(x => x.Name)
  96. );
  97. setups.Add(
  98. LookupFactory.DefineFilter<Shipment>(),
  99. new Columns<Shipment>(x => x.ID, x => x.Code, x => x.Description, x => x.BarCode)
  100. );
  101. if (_settings.AreaID != Guid.Empty)
  102. setups.Add(
  103. new Filter<StockArea>(x=>x.ID).IsEqualTo(_settings.AreaID),
  104. new Columns<StockArea>(x=>x.ID).Add(x=>x.Code).Add(x=>x.Description)
  105. );
  106. setups.Query();
  107. Factories = setups.Get<ManufacturingFactory>().Rows.Select(x => x.ToObject<ManufacturingFactory>()).ToArray();
  108. Sections = setups.Get<ManufacturingSection>().Rows.Select(x => x.ToObject<ManufacturingSection>()).ToArray();
  109. Trolleys = setups.Get<ManufacturingTrolley>().Rows.Select(x => x.ToObject<ManufacturingTrolley>()).ToArray();
  110. Employees = setups.Get<Employee>().ToDictionary<Employee, Guid, string>(x => x.ID, x => x.Name);
  111. var myRow = setups.Get<Employee>().Rows.FirstOrDefault(r => r.Get<Employee, Guid>(c => c.UserLink.ID).Equals(ClientFactory.UserGuid));
  112. myID = myRow?.Get<Employee, Guid>(c => c.ID) ?? Guid.Empty;
  113. myName = myRow?.Get<Employee, string>(c => c.Name) ?? "(Unknown Employee)";
  114. Shipments = setups.Get<Shipment>();
  115. CurrentSection = Sections.FirstOrDefault(x => x.ID.Equals(_settings.Section))
  116. ?? Sections.FirstOrDefault();
  117. var iSection = 0;
  118. var iCount = 0;
  119. foreach (var section in Sections)
  120. {
  121. if (section == CurrentSection)
  122. {
  123. iSection = Section.Items.Count;
  124. iCount = section.Stations; //Sections[id].Item2;
  125. }
  126. Section.Items.Add($"{section.Factory.Name}: {section.Name}");
  127. }
  128. Section.SelectedIndex = iSection;
  129. Station.Items.Clear();
  130. for (var i = 1; i <= (CurrentSection?.Stations ?? 0); i++)
  131. Station.Items.Add($"Station #{i}");
  132. CurrentStation = _settings.Station + 1;
  133. if (CurrentStation < 1)
  134. CurrentStation = 1;
  135. if (CurrentStation > iCount)
  136. CurrentStation = iCount;
  137. Station.SelectedIndex = CurrentStation - 1;
  138. if (_settings.AreaID != Guid.Empty)
  139. {
  140. var area = setups.Get<StockArea>().ToObjects<StockArea>().FirstOrDefault();
  141. if (area != null)
  142. {
  143. _packGrid.Area = area;
  144. _areaDescription.Text = $"{area.Code}";
  145. _addPack.IsEnabled = true;
  146. }
  147. else
  148. {
  149. _packGrid.Area = null;
  150. _areaDescription.Text = "Set\r\nArea";
  151. _settings.AreaID = Guid.Empty;
  152. new LocalConfiguration<FactoryFloorLocalSettings>().Save(_settings);
  153. _addPack.IsEnabled = false;
  154. }
  155. }
  156. else
  157. {
  158. _packGrid.Area = null;
  159. _areaDescription.Text = "Set\r\nArea";
  160. }
  161. _packGrid.Refresh(true,true);
  162. SetupScanner();
  163. }
  164. public void Shutdown(CancelEventArgs? cancel)
  165. {
  166. ShutdownScanner();
  167. //UpdateTimeTracking(true);
  168. LoadDrawing(null);
  169. }
  170. public void CreateToolbarButtons(IPanelHost host)
  171. {
  172. ManufacturingSetupActions.Standard(host);
  173. //if (Security.IsAllowed<CanViewManufacturingSelfAssessment>())
  174. // host.CreatePanelAction(new PanelAction() { Caption = "Self Assessment", Image = PRSDesktop.Resources.star, OnExecute = DoSelfAssessment });
  175. host.CreatePanelAction(new PanelAction { Caption = "Lost Time", Image = PRSDesktop.Resources.smiley, OnExecute = DoSelectLostTime });
  176. host.CreatePanelAction(new PanelAction
  177. { Caption = "Treament PO", Image = PRSDesktop.Resources.purchase, OnExecute = DoCreatePurchaseOrder });
  178. host.CreatePanelAction(new PanelAction
  179. { Caption = "Treatment Delivery", Image = PRSDesktop.Resources.barcode, OnExecute = DoScanDeliveryItems });
  180. host.CreatePanelAction(new PanelAction { Caption = "Select Rack", Image = PRSDesktop.Resources.forklift, OnExecute = DoSelectRack });
  181. host.CreatePanelAction(new PanelAction { Caption = "Close Rack", Image = PRSDesktop.Resources.forklift, OnExecute = DoCloseRack });
  182. host.CreatePanelAction(new PanelAction { Caption = "Scan Barcode", Image = PRSDesktop.Resources.product, OnExecute = DoScanBarcode });
  183. host.CreatePanelAction(new PanelAction { Caption = _settings.SidePanel == FactorySidePanel.Packs ? "Hide Stock" : "Show Stock", Image = PRSDesktop.Resources.trolley, OnExecute = TogglePackPanel});
  184. }
  185. private void TogglePackPanel(PanelAction pa)
  186. {
  187. RackPanel.Visibility = Visibility.Collapsed;
  188. PackPanel.Visibility = _settings.SidePanel == FactorySidePanel.Packs
  189. ? Visibility.Collapsed
  190. : Visibility.Visible;
  191. _settings.SidePanel = PackPanel.Visibility == Visibility.Visible
  192. ? FactorySidePanel.Packs
  193. : FactorySidePanel.None;
  194. new LocalConfiguration<FactoryFloorLocalSettings>().Save(_settings);
  195. pa.Caption = _settings.SidePanel == FactorySidePanel.Packs
  196. ? "Hide Stock"
  197. : "Show Stock";
  198. _addPack.IsEnabled = _settings.AreaID != Guid.Empty;
  199. }
  200. public Dictionary<string, object[]> Selected()
  201. {
  202. var rows = Packets.Rows.Where(p => Kanbans.Any(k => k.Checked && p.Get<ManufacturingPacket, Guid>(c => c.ID).ToString().Equals(k.ID)));
  203. var pkts = rows.ToArray().Select(r => r.ToObject<ManufacturingPacket>());
  204. return new Dictionary<string, object[]> { { typeof(ManufacturingPacket).EntityName(), pkts.ToArray() } };
  205. }
  206. public string SectionName => "Factory";
  207. public DataModel DataModel(Selection selection)
  208. {
  209. var rows = (Packets == null) || (selection == Selection.None)
  210. ? new CoreRow[] { }
  211. : selection == Selection.Selected
  212. ? Packets.Rows.Where(p => Kanbans.Any(k => k.Checked && p.Get<ManufacturingPacket, Guid>(c => c.ID).ToString().Equals(k.ID)))
  213. : Packets.Rows;
  214. var ids = rows.Any() ? rows.Select(r => r.Get<ManufacturingPacket, Guid>(x => x.ID)).ToArray() : new[] { CoreUtils.FullGuid };
  215. return new ManufacturingPacketDataModel(new Filter<ManufacturingPacket>(x => x.ID).InList(ids));
  216. }
  217. public event DataModelUpdateEvent? OnUpdateDataModel;
  218. public void Heartbeat(TimeSpan time)
  219. {
  220. // Security Descriptor should be disabled for non-manufacturing staff
  221. if (!Security.IsAllowed<CanTrackManufacturingHistory>() || CurrentSection == null)
  222. return;
  223. // If Lost Time is Active, let's record that
  224. if (LostTime != null)
  225. {
  226. var history = new ManufacturingHistory();
  227. history.Date = DateTime.Today;
  228. history.Employee.ID = myID;
  229. history.Packet.ID = Guid.Empty;
  230. history.LostTime.ID = LostTime.ID;
  231. history.Description = LostTime.Description;
  232. //history.Setout.ID = CheckedPackets[id].Item3;
  233. //history.Job.ID = CheckedPackets[id].Item4;
  234. history.Section.ID = CurrentSection.ID;
  235. history.Station = CurrentStation;
  236. history.Activity.ID = LostTime.Activity.ID;
  237. history.WorkDuration = new TimeSpan(time.Ticks);
  238. history.QACompleted = 0;
  239. history.WorkCompleted = 0;
  240. history.Window = time;
  241. new Client<ManufacturingHistory>().Save(history, "", (o, e) => { });
  242. }
  243. else
  244. {
  245. var CheckedPackets = new Dictionary<Guid, Tuple<DateTime, DateTime, Guid, Guid, string>>();
  246. foreach (var kanban in Kanbans.Where(x => x.Checked))
  247. {
  248. var packet = KanbanToPacket(kanban);
  249. if (packet != null)
  250. {
  251. var stagerow = Stages.Rows.FirstOrDefault(r => r.Get<ManufacturingPacketStage, Guid>(c => c.Parent.ID).Equals(packet.ID)
  252. && r.Get<ManufacturingPacketStage, Guid>(c => c.ManufacturingSectionLink.ID)
  253. .Equals(_settings.Section));
  254. if (stagerow != null)
  255. {
  256. var stage = stagerow.ToObject<ManufacturingPacketStage>();
  257. if (stage.Station != 0)
  258. CheckedPackets[packet.ID] = new Tuple<DateTime, DateTime, Guid, Guid, string>(stage.Started, stage.Completed,
  259. packet.SetoutLink.ID, packet.SetoutLink.JobLink.ID, packet.Serial);
  260. }
  261. }
  262. }
  263. if (!CheckedPackets.Any())
  264. CheckedPackets[Guid.Empty] =
  265. new Tuple<DateTime, DateTime, Guid, Guid, string>(DateTime.MinValue, DateTime.MinValue, Guid.Empty, Guid.Empty, "No Packet");
  266. var updates = new List<ManufacturingHistory>();
  267. var slice = time.Ticks / CheckedPackets.Count;
  268. foreach (var id in CheckedPackets.Keys)
  269. {
  270. var history = new ManufacturingHistory();
  271. history.Date = DateTime.Today;
  272. history.Employee.ID = myID;
  273. history.Packet.ID = id;
  274. history.Description = CheckedPackets[id].Item5;
  275. //history.Setout.ID = CheckedPackets[id].Item3;
  276. //history.Job.ID = CheckedPackets[id].Item4;
  277. history.Section.ID = CurrentSection.ID;
  278. history.Activity.ID = CurrentSection.Activity.ID;
  279. history.Station = CurrentStation;
  280. if (CheckedPackets[id].Item1.Equals(DateTime.MinValue))
  281. history.QADuration = new TimeSpan(slice);
  282. else
  283. history.WorkDuration = new TimeSpan(slice);
  284. history.QACompleted = CheckedPackets[id].Item1.Equals(DateTime.MinValue) ? 0 : 0;
  285. history.WorkCompleted = CheckedPackets[id].Item2.Equals(DateTime.MinValue) ? 0 : 1;
  286. history.Window = time;
  287. updates.Add(history);
  288. }
  289. if (updates.Any())
  290. new Client<ManufacturingHistory>().Save(updates, "", (o, e) => { });
  291. }
  292. }
  293. private void ShutdownScanner()
  294. {
  295. try
  296. {
  297. foreach (var scanner in _scanners) scanner.Actions.ToggleLed(LedMode.GreenOff);
  298. BarcodeScannerManager.Instance.DataReceived -= Instance_DataReceived;
  299. BarcodeScannerManager.Instance.Close();
  300. }
  301. catch (Exception e)
  302. {
  303. MessageBox.Show("Error Shutting down Scanner!\n\n" + e.Message);
  304. }
  305. }
  306. private void SetupScanner()
  307. {
  308. _scanners.Clear();
  309. BarcodeScannerManager.Instance.Open();
  310. BarcodeScannerManager.Instance.RegisterForEvents(EventType.Barcode, EventType.Pnp, EventType.Image, EventType.Other, EventType.Rmd);
  311. BarcodeScannerManager.Instance.GetDevices();
  312. foreach (var scanner in BarcodeScannerManager.Instance.GetDevices())
  313. {
  314. _scanners.Add(scanner);
  315. scanner.Actions.ToggleLed(LedMode.RedOn);
  316. scanner.Actions.SoundBeeper(BeepPattern.FastWarble);
  317. }
  318. BarcodeScannerManager.Instance.DataReceived += Instance_DataReceived;
  319. }
  320. private void Instance_DataReceived(object? sender, BarcodeScanEventArgs e)
  321. {
  322. Dispatcher.Invoke(() => { ProcessCode(_scanners[(int)e.ScannerId], e.Data); });
  323. }
  324. private void ProcessCode(IMotorolaBarcodeScanner scanner, string code)
  325. {
  326. try
  327. {
  328. var isGuid = Guid.TryParse(code, out var guid);
  329. if (isGuid)
  330. {
  331. if (Sections.Any(x => x.ID.Equals(guid)))
  332. {
  333. IsReady = false;
  334. CurrentSection = Sections.First(x => x.ID.Equals(guid));
  335. Section.SelectedIndex = Array.IndexOf(Sections, CurrentSection);
  336. IsReady = true;
  337. Progress.Show("Changing Sections");
  338. DoRefresh(true);
  339. Progress.Close();
  340. scanner?.Actions.SoundBeeper(BeepPattern.FastWarble);
  341. }
  342. else if (Trolleys.Any(x => x.ID.Equals(guid)))
  343. {
  344. var trolley = Trolleys.First().Code;
  345. var updates = new List<ManufacturingPacket>();
  346. foreach (var kanban in Kanbans.Where(x => x.Checked))
  347. {
  348. var packet = KanbanToPacket(kanban);
  349. packet.Trolleys = trolley;
  350. updates.Add(packet);
  351. var pktrow = Packets.Rows.FirstOrDefault(r => r.Get<ManufacturingPacket, Guid>(c => c.ID).Equals(Guid.Parse(kanban.ID)));
  352. var stagerow = Stages.Rows.FirstOrDefault(r => r.Get<ManufacturingPacketStage, Guid>(c => c.Parent.ID).Equals(packet.ID)
  353. && r.Get<ManufacturingPacketStage, Guid>(
  354. c => c.ManufacturingSectionLink.ID)
  355. .Equals(_settings.Section));
  356. pktrow.Set<ManufacturingPacket, string>(x => x.Trolleys, packet.Trolleys);
  357. LoadModel(kanban, pktrow, stagerow, true);
  358. UpdateSelectedKanban(false);
  359. }
  360. if (updates.Any())
  361. new Client<ManufacturingPacket>().Save(updates, "Set Trolley to " + trolley, (o, e) => { });
  362. scanner?.Actions.SoundBeeper(BeepPattern.LowHigh);
  363. }
  364. else
  365. {
  366. scanner?.Actions.SoundBeeper(BeepPattern.FourLowShort);
  367. }
  368. }
  369. else
  370. {
  371. var shiprow = Shipments.Rows.FirstOrDefault(r => r.Get<Shipment, string>(c => c.BarCode).Equals(code));
  372. if (shiprow != null)
  373. {
  374. if (string.Equals(code, rackbarcode))
  375. {
  376. RackPanel.Visibility = Visibility.Collapsed;
  377. _settings.SidePanel = FactorySidePanel.None;
  378. new LocalConfiguration<FactoryFloorLocalSettings>().Save(_settings);
  379. RackContents.ItemsSource = null;
  380. rackid = Guid.Empty;
  381. rackbarcode = "";
  382. scanner?.Actions.SoundBeeper(BeepPattern.ThreeLowShort);
  383. }
  384. else
  385. {
  386. RackContents.ItemsSource = null;
  387. rackid = shiprow.Get<Shipment, Guid>(c => c.ID);
  388. rackbarcode = code;
  389. var rows = DeliveryItems.Rows.Where(r => r.Get<DeliveryItem, Guid>(c => c.ShipmentLink.ID).Equals(rackid)).ToArray();
  390. rackcontents.Clear();
  391. rackcontents.AddRange(rows.Select(x => x.ToObject<DeliveryItem>()));
  392. RackContents.ItemsSource = rackcontents;
  393. RackName.Content = $"Rack {shiprow.Get<Shipment, string>(c => c.Code)}";
  394. RackCount.Content = rows.Length.ToString();
  395. PackPanel.Visibility = Visibility.Collapsed;
  396. RackPanel.Visibility = Visibility.Visible;
  397. _settings.SidePanel = FactorySidePanel.Racks;
  398. new LocalConfiguration<FactoryFloorLocalSettings>().Save(_settings);
  399. scanner?.Actions.SoundBeeper(BeepPattern.ThreeHighShort);
  400. }
  401. }
  402. else
  403. {
  404. if (RackPanel.Visibility == Visibility.Visible)
  405. {
  406. var row = DeliveryItems.Rows.FirstOrDefault(r => r.Get<DeliveryItem, string>(c => c.Barcode).Equals(code));
  407. if (row != null)
  408. {
  409. var delitem = rackcontents.FirstOrDefault(x => string.Equals(x.Barcode, code));
  410. if (delitem != null)
  411. {
  412. rackcontents.Remove(delitem);
  413. delitem.ShipmentLink.ID = Guid.Empty;
  414. new Client<DeliveryItem>().Save(delitem, "Item Removed From Rack", (o, e) => { });
  415. row.Set<DeliveryItem, Guid>(x => x.ShipmentLink.ID, Guid.Empty);
  416. scanner?.Actions.SoundBeeper(BeepPattern.HighLow);
  417. }
  418. else
  419. {
  420. delitem = row.ToObject<DeliveryItem>();
  421. delitem.ShipmentLink.ID = rackid;
  422. rackcontents.Add(delitem);
  423. new Client<DeliveryItem>().Save(delitem, "Item Added to " + RackName.Content, (o, e) => { });
  424. row.Set<DeliveryItem, Guid>(x => x.ShipmentLink.ID, rackid);
  425. if (Kanbans.Any(x => string.Equals(x.ID, delitem.ManufacturingPacketLink.ID.ToString())))
  426. ReloadPackets(true);
  427. scanner?.Actions.SoundBeeper(BeepPattern.LowHigh);
  428. }
  429. RackContents.ItemsSource = null;
  430. RackContents.ItemsSource = rackcontents;
  431. RackCount.Content = rackcontents.Count.ToString();
  432. }
  433. }
  434. else
  435. {
  436. var id = new Client<DeliveryItem>().Query(
  437. new Filter<DeliveryItem>(x => x.Barcode).IsEqualTo(code),
  438. new Columns<DeliveryItem>(x => x.ManufacturingPacketLink.ID)
  439. ).Rows.FirstOrDefault()?.Get<DeliveryItem, Guid>(x => x.ManufacturingPacketLink.ID);
  440. if (!id.HasValue)
  441. {
  442. scanner?.Actions.SoundBeeper(BeepPattern.FourLowShort);
  443. return;
  444. }
  445. var kanban = Kanbans.FirstOrDefault(x => string.Equals(x.ID, id.Value.ToString()));
  446. if (kanban == null)
  447. {
  448. // Error - packet not visible from this station
  449. scanner?.Actions.SoundBeeper(BeepPattern.FourLowShort);
  450. return;
  451. }
  452. var stage = Stages.Rows.FirstOrDefault(r => r.Get<ManufacturingPacketStage, Guid>(c => c.Parent.ID).Equals(id)
  453. && r.Get<ManufacturingPacketStage, Guid>(c => c.ManufacturingSectionLink.ID)
  454. .Equals(_settings.Section))?.ToObject<ManufacturingPacketStage>();
  455. if (stage == null)
  456. scanner?.Actions.SoundBeeper(BeepPattern.FourHighShort);
  457. if (stage.Station == 0) AddPacketToCurrentWorkload(stage);
  458. if (kanban != CurrentKanban)
  459. {
  460. CurrentKanban = kanban;
  461. UpdateSelectedKanban(false);
  462. }
  463. scanner?.Actions.SoundBeeper(BeepPattern.LowHigh);
  464. }
  465. }
  466. }
  467. }
  468. catch (Exception)
  469. {
  470. scanner?.Actions.SoundBeeper(BeepPattern.FourLowShort);
  471. }
  472. }
  473. private void LoadDrawing(Guid? id)
  474. {
  475. if (PDFEditor != null)
  476. {
  477. PDFEditor.Document = null;
  478. // Unload PDF Annotations
  479. PDFEditor = null;
  480. }
  481. else if (QAGrid != null)
  482. {
  483. Editor.Content = null;
  484. // Unload QA Answers
  485. QAGrid = null;
  486. }
  487. if (id.HasValue)
  488. {
  489. var pktid = CurrentKanban != null ? Guid.Parse(CurrentKanban.ID) : Guid.Empty;
  490. var row = Packets.Rows.FirstOrDefault(r => r.Get<ManufacturingPacket, Guid>(c => c.ID).Equals(pktid));
  491. var stagerow = Stages.Rows.FirstOrDefault(r => r.Get<ManufacturingPacketStage, Guid>(c => c.Parent.ID).Equals(pktid)
  492. && r.Get<ManufacturingPacketStage, Guid>(c => c.ManufacturingSectionLink.ID)
  493. .Equals(_settings.Section));
  494. var packet = row.ToObject<ManufacturingPacket>();
  495. if (id.Value == Guid.Empty)
  496. {
  497. QAGrid = new QAGrid();
  498. var qadata = stagerow != null ? stagerow.Get<ManufacturingPacketStage, string>(c => c.FormData) : "";
  499. var values = string.IsNullOrWhiteSpace(qadata)
  500. ? new Dictionary<Guid, object>()
  501. : Serialization.Deserialize<Dictionary<Guid, object>>(qadata);
  502. if (CurrentSection != null && row != null)
  503. {
  504. var genquestions = LoadQAQuestions(packet, true, false);
  505. QAGrid.LoadChecks("Global Checks for " + CurrentSection.Name, genquestions, values);
  506. //var specquestions = LoadQAQuestions(packet, false, true);
  507. //QAGrid.LoadChecks(String.Format("Specific Checks for {0} [{1}] template", packet.ManufacturingTemplateLink.Name, packet.ManufacturingTemplateLink.Code), specquestions, values);
  508. }
  509. QAGrid.OnChanged += QAGridChanged;
  510. Editor.Content = QAGrid;
  511. }
  512. else
  513. {
  514. PDFEditor = new PDFEditorControl();
  515. PDFEditor.LineColor = _settings.LineColor;
  516. PDFEditor.TextSize = _settings.FontSize;
  517. //PDFEditor.PrintAllowed = Security.IsAllowed<CanPrintFactoryFloorDrawings>();
  518. PDFEditor.SaveAllowed = Security.IsAllowed<CanSaveFactoryFloorDrawings>();
  519. var document = documents.FirstOrDefault(x => x.DocumentLink.ID.Equals(id));
  520. PDFEditor.Watermark = packet.WaterMark;
  521. PDFEditor.Document = document;
  522. PDFEditor.PDFSettingsChanged += PDFEditorSettingsChanged;
  523. Editor.Content = PDFEditor;
  524. }
  525. }
  526. }
  527. private void DoSelectRack(PanelAction obj)
  528. {
  529. var dlg = new MultiSelectDialog<Shipment>(
  530. null,
  531. new Columns<Shipment>(x => x.ID, x => x.Code, x => x.Description, x => x.BarCode),
  532. false
  533. );
  534. if (dlg.ShowDialog())
  535. {
  536. var id = dlg.IDs().FirstOrDefault();
  537. var barcode = dlg.Data().Rows.FirstOrDefault(r => r.Get<Shipment, Guid>(c => c.ID).Equals(id))?.Get<Shipment, string>(x => x.BarCode);
  538. ProcessCode(_scanners.FirstOrDefault(), barcode);
  539. }
  540. }
  541. private void DoCloseRack(PanelAction obj)
  542. {
  543. if (!string.IsNullOrWhiteSpace(rackbarcode))
  544. ProcessCode(_scanners.FirstOrDefault(), rackbarcode);
  545. }
  546. private void DoScanBarcode(PanelAction obj)
  547. {
  548. var dlg = new MultiSelectDialog<DeliveryItem>(
  549. new Filter<DeliveryItem>(x => x.DeliveredDate).IsEqualTo(DateTime.MinValue)
  550. .And(x => x.ManufacturingPacketLink).LinkValid(),
  551. new Columns<DeliveryItem>(x => x.ID, x => x.Barcode, x => x.Description),
  552. false
  553. );
  554. if (dlg.ShowDialog())
  555. {
  556. var id = dlg.IDs().FirstOrDefault();
  557. var barcode = dlg.Data().Rows.FirstOrDefault(r => r.Get<DeliveryItem, Guid>(c => c.ID).Equals(id))
  558. ?.Get<DeliveryItem, string>(x => x.Barcode);
  559. ProcessCode(_scanners.FirstOrDefault(), barcode);
  560. }
  561. }
  562. private void DoScanDeliveryItems(PanelAction obj)
  563. {
  564. new DeliveryBuilder(Guid.Empty, Guid.Empty).ShowDialog();
  565. }
  566. private void DoCreatePurchaseOrder(PanelAction obj)
  567. {
  568. //Guid section = CurrentSection != null ? CurrentSection.ID : CoreUtils.FullGuid;
  569. //var stages = Stages.Rows.Where(row => row.Get<ManufacturingPacketStage, Guid>(col => col.ManufacturingSectionLink.ID).Equals(section) && row.Get<ManufacturingPacketStage, int>(col => col.Station).Equals(CurrentStation));
  570. //var ids = stages.Select(row => row.Get<ManufacturingPacketStage, Guid>(col => col.ManufacturingPacketLink.ID)).ToArray();
  571. var ids = Kanbans.Where(x => !x.ColorKey.Equals(QA_COLOR)).Select(x => Guid.Parse(x.ID)).ToArray();
  572. var treatments = new Client<ManufacturingTreatment>().Query(new Filter<ManufacturingTreatment>(x => x.Packet.ID).InList(ids));
  573. var window = new ManufacturingTreatmentWindow(treatments);
  574. if (window.ShowDialog() != true)
  575. return;
  576. Progress.Show("Creating Purchase Order");
  577. var order = new PurchaseOrder();
  578. //Supplier supplier = new Client<Supplier>().Query(
  579. // new Filter<Supplier>(x => x.ID).IsEqualTo(window.SupplierID),
  580. // new Columns<Supplier>(x=>x.ID
  581. //).Rows.FirstOrDefault()?.ToObject<Supplier>());
  582. order.SupplierLink.ID = window.SupplierID;
  583. order.SupplierLink.Name = window.SupplierName; //supplier != null ? supplier.Name : "Unknown Supplier";
  584. order.Description = string.Format("Materials Processing Request raised by {0} from Factory Floor", Employees[myID]);
  585. order.RaisedBy.ID = myID;
  586. order.IssuedBy.ID = myID;
  587. order.IssuedDate = DateTime.Today;
  588. order.DueDate = DateTime.Today.AddDays(7);
  589. new Client<PurchaseOrder>().Save(order, "Created Treatment Purchase Order");
  590. Progress.SetMessage("Processing Order");
  591. var orderitems = new List<PurchaseOrderItem>();
  592. var packetupdates = new List<ManufacturingPacket>();
  593. var query = new MultiQuery();
  594. query.Add(
  595. new Filter<SupplierProduct>(x => x.Product.ID).IsEqualTo(window.ProductID).And(x => x.SupplierLink.ID)
  596. .IsEqualTo(window.SupplierID),
  597. new Columns<SupplierProduct>(x => x.Job.ID).Add(x => x.CostPrice).Add(x => x.Product.NettCost)
  598. );
  599. query.Add(
  600. new Filter<Product>(x => x.ID).IsEqualTo(window.ProductID),
  601. LookupFactory.DefineLookupColumns<PurchaseOrderItem, Product, ProductLink>(x => x.Product).Add(x => x.NettCost)
  602. );
  603. query.Query();
  604. var supprods = query.Get<SupplierProduct>().Rows.Select(x => x.ToObject<SupplierProduct>()).ToArray();
  605. var supprice = supprods.FirstOrDefault(x => Equals(x.Job.ID, Guid.Empty));
  606. var product = query.Get<Product>().Rows.FirstOrDefault()?.ToObject<Product>();
  607. var stdcost = supprice != null
  608. ? supprice.CostPrice
  609. : product != null
  610. ? product.NettCost
  611. : 0.0F;
  612. foreach (var row in window.Selected)
  613. {
  614. var treatment = row.ToObject<ManufacturingTreatment>();
  615. var packet = Packets.Rows.First(p => p.Get<ManufacturingPacket, Guid>(c => c.ID).Equals(treatment.Packet.ID))
  616. .ToObject<ManufacturingPacket>();
  617. packetupdates.Add(packet);
  618. var item = new PurchaseOrderItem();
  619. item.PurchaseOrderLink.ID = order.ID;
  620. item.Job.ID = treatment.Packet.SetoutLink.JobLink.ID;
  621. item.Packet.ID = packet.ID;
  622. item.Product.ID = window.ProductID;
  623. if(product is not null)
  624. {
  625. item.Product.Synchronise(product);
  626. }
  627. item.Qty = packet.BarcodeQty;
  628. item.Dimensions.Length = treatment.Parameter == 0.0F ? 1.0F : treatment.Parameter;
  629. var jobprice = supprods.FirstOrDefault(x => x.Job.ID.Equals(item.Job.ID));
  630. item.Cost = (jobprice != null ? jobprice.CostPrice : stdcost) * treatment.Parameter;
  631. var description = new List<string>();
  632. description.Add(string.Format("{0} x {1} - {2}", packet.BarcodeQty, packet.Serial, packet.Title));
  633. var dimensions = new List<string>();
  634. if (packet.Height > 0.0F)
  635. dimensions.Add(string.Format("H:{0:F2}mm", packet.Height));
  636. if (packet.Width > 0.0F)
  637. dimensions.Add(string.Format("W:{0:F2}mm", packet.Width));
  638. if (packet.Length > 0.0F)
  639. dimensions.Add(string.Format("L:{0:F2}mm", packet.Length));
  640. dimensions.Add(string.Format("Param:{0:F4}", treatment.Parameter));
  641. if (dimensions.Any())
  642. description.Add(string.Format("Dimensions: {0}", string.Join(" ", dimensions)));
  643. item.Description = string.Join("\n", description);
  644. orderitems.Add(item);
  645. }
  646. new Client<PurchaseOrderItem>().Save(orderitems, "Created by Factory Floor Purchase");
  647. Progress.SetMessage("Updating Packets");
  648. foreach (var orderitem in orderitems)
  649. {
  650. var packet = packetupdates.FirstOrDefault(x => x.ID.Equals(orderitem.Packet.ID));
  651. if (packet != null)
  652. packet.OrderItem.ID = orderitem.ID;
  653. }
  654. new Client<ManufacturingPacket>().Save(packetupdates.Where(x => x.IsChanged()), "");
  655. Progress.SetMessage("Creating Delivery");
  656. var delivery = new Delivery();
  657. delivery.Date = DateTime.Today;
  658. delivery.Due = DateTime.Today;
  659. delivery.Employee.ID = myID;
  660. var sb = new StringBuilder();
  661. sb.Append("Serial # ");
  662. sb.AppendLine();
  663. if (Employees.ContainsKey(myID))
  664. sb.AppendLine();
  665. delivery.Notes = string.Format("Delivery of Items for processing to {0}\nOrder #{1} (raised on {2:dd MMM yy} by {3})\nItems: {4}",
  666. order.SupplierLink.Name,
  667. order.PONumber,
  668. delivery.Date,
  669. myName,
  670. string.Join(", ",
  671. orderitems.Select(x =>
  672. string.Format("{0}{1}", x.Description.Split('\n').FirstOrDefault(), x.Qty > 1 ? " (x" + x.Qty.ToString("F0") + ")" : "")))
  673. );
  674. new Client<Delivery>().Save(delivery, "Created by Factory Floor Purchase");
  675. Progress.Close();
  676. PrintDeliveryBarcode(delivery, order);
  677. PrintOrderItemBarcodes(delivery, order);
  678. SendPurchaseNotification(order.PONumber);
  679. MessageBox.Show("All Done");
  680. new DeliveryBuilder(delivery.ID, order.ID).ShowDialog();
  681. Refresh();
  682. }
  683. private void SendPurchaseNotification(string PONumber)
  684. {
  685. var updates = new List<Notification>();
  686. var roles = new Client<EmployeeRole>().Query(new Filter<EmployeeRole>(x => x.RoleLink.Code).IsEqualTo("PURCHASES"));
  687. foreach (var role in roles.Rows)
  688. {
  689. var notification = new Notification
  690. {
  691. Title = string.Format("Treatment PO #{0} has been raised", PONumber),
  692. Description = "The above Purchase Order has been created, and is ready to be checked and issued to the relevant supplier."
  693. };
  694. notification.Sender.ID = myID;
  695. notification.Employee.ID = role.Get<EmployeeRole, Guid>(x => x.EmployeeLink.ID);
  696. updates.Add(notification);
  697. }
  698. new Client<Notification>().Save(updates, "Sent Notification");
  699. }
  700. private void PrintDeliveryBarcode(Delivery delivery, PurchaseOrder order)
  701. {
  702. var model = new ManufacturingTreatmentDataModel(order, delivery);
  703. var templatename = "Print Treatment Delivery Bar Code";
  704. var sectionName = "Treatment Delivery Bar Code";
  705. var template = new Client<ReportTemplate>()
  706. .Load(
  707. new Filter<ReportTemplate>(x => x.Name).IsEqualTo(templatename)
  708. .And(x => x.DataModel).IsEqualTo(model.Name)
  709. .And(x => x.Section).IsEqualTo(sectionName)
  710. ).FirstOrDefault();
  711. if (template == null)
  712. {
  713. template = new ReportTemplate
  714. {
  715. DataModel = model.Name,
  716. Section = sectionName,
  717. Name = templatename
  718. };
  719. new Client<ReportTemplate>().Save(template, "Auto Created Report Template");
  720. }
  721. ReportUtils.PreviewReport(template, model, !Security.IsAllowed<CanDesignReports>(), Security.IsAllowed<CanDesignReports>());
  722. }
  723. private void PrintOrderItemBarcodes(Delivery delivery, PurchaseOrder order)
  724. {
  725. var model = new ManufacturingTreatmentDataModel(order, delivery);
  726. var templatename = "Print Treatment Item Bar Codes";
  727. var sectionName = "Treatment Item Bar Code";
  728. var template = new Client<ReportTemplate>()
  729. .Load(
  730. new Filter<ReportTemplate>(x => x.Name).IsEqualTo(templatename)
  731. .And(x => x.DataModel).IsEqualTo(model.Name)
  732. .And(x => x.Section).IsEqualTo(sectionName)
  733. ).FirstOrDefault();
  734. if (template == null)
  735. {
  736. template = new ReportTemplate
  737. {
  738. DataModel = model.Name,
  739. Section = sectionName,
  740. Name = templatename
  741. };
  742. new Client<ReportTemplate>().Save(template, "Auto Created Report Template");
  743. }
  744. ReportUtils.PreviewReport(template, model, !Security.IsAllowed<CanDesignReports>(), Security.IsAllowed<CanDesignReports>());
  745. }
  746. private CoreTable POItemTable(IEnumerable<PurchaseOrderItem> items)
  747. {
  748. var result = new CoreTable();
  749. result.LoadColumns(typeof(PurchaseOrderItem));
  750. result.LoadRows(items);
  751. return result;
  752. }
  753. private void DoSelectLostTime(PanelAction obj)
  754. {
  755. var chooser = new FactoryLostTimeChooser();
  756. if (chooser.ShowDialog() == true)
  757. {
  758. LostTime = chooser.SelectedLostTime;
  759. LostTimeDescription.Content = LostTime.Description;
  760. LostTimeActive.Visibility = Visibility.Visible;
  761. }
  762. }
  763. private void CancelLostTime_Click(object sender, RoutedEventArgs e)
  764. {
  765. LostTime = null;
  766. LostTimeActive.Visibility = Visibility.Collapsed;
  767. }
  768. //private void Current_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
  769. //{
  770. // MessageBox.Show("Exception!\n\n" + e.Exception.Message + "\n\n" + e.Exception.StackTrace);
  771. // e.Handled = true;
  772. //}
  773. private void Section_SelectionChanged(object sender, SelectionChangedEventArgs e)
  774. {
  775. if (!IsReady)
  776. return;
  777. CurrentSection = Sections[Section.SelectedIndex];
  778. //Kanban.Columns.Clear();
  779. //Kanban.Columns.Add(new KanbanColumn() { Title = CurrentSection, Categories = CurrentSection.ID.ToString() });
  780. //Kanban.Columns[0].AllowDrag = false;
  781. //Kanban.Columns[0].PreviewMouseWheel += CardBorder_PreviewMouseWheel;
  782. IsReady = false;
  783. Station.Items.Clear();
  784. for (var i = 1; i <= CurrentSection.Stations; i++)
  785. Station.Items.Add(string.Format("Station #{0}", i));
  786. IsReady = true;
  787. Station.SelectedIndex = 0;
  788. }
  789. private void Station_SelectionChanged(object sender, SelectionChangedEventArgs e)
  790. {
  791. if (!IsReady)
  792. return;
  793. SelectSectionAndStation(CurrentSection.ID, Station.SelectedIndex + 1);
  794. }
  795. private void SelectSectionAndStation(Guid section, int station)
  796. {
  797. CurrentKanban = null;
  798. CurrentStation = station;
  799. _settings.Section = section;
  800. _settings.Station = CurrentStation - 1;
  801. new LocalConfiguration<FactoryFloorLocalSettings>().Save(_settings);
  802. DoRefresh(true);
  803. }
  804. private void LoadKanban()
  805. {
  806. using (new WaitCursor())
  807. {
  808. if (CurrentKanban == null)
  809. {
  810. ButtonStack.Children.Clear();
  811. LoadDrawing(null);
  812. _packGrid.CurrentPacket = null;
  813. }
  814. else if (true) // Kanban has changed - how do we figure this out
  815. {
  816. var packet = KanbanToPacket(CurrentKanban);
  817. _packGrid.CurrentPacket = packet;
  818. //SetoutStage stage = packet.GetCurrentStage();
  819. var row = Stages.Rows.FirstOrDefault(r => r.Get<ManufacturingPacketStage, Guid>(c => c.Parent.ID).Equals(packet.ID)
  820. && r.Get<ManufacturingPacketStage, Guid>(c => c.ManufacturingSectionLink.ID)
  821. .Equals(_settings.Section));
  822. var station = row != null ? row.Get<ManufacturingPacketStage, int>(c => c.Station) : 0;
  823. var quality = row != null ? row.Get<ManufacturingPacketStage, QualityStatus>(c => c.QualityStatus) : QualityStatus.NotChecked;
  824. var percentage = row != null ? row.Get<ManufacturingPacketStage, double>(c => c.PercentageComplete) : 0.00F;
  825. var Pending = station == 0; //packet.StageLink.Station == 0;
  826. // Set the Proper Button Set for this type of Packet
  827. MfgRow.Height = Pending ? new GridLength(00) : new GridLength(50);
  828. foreach (var btn in ButtonGrid.FindVisualChildren<Button>())
  829. btn.IsEnabled = CurrentKanban != null;
  830. var idle = CompleteButton.Background;
  831. var current = new SolidColorBrush(Colors.SteelBlue);
  832. Update100Button.Background = percentage >= 100.0F ? current : idle;
  833. Update075Button.Background = percentage >= 75.0F ? current : idle;
  834. Update050Button.Background = percentage >= 50.0F ? current : idle;
  835. Update025Button.Background = percentage >= 25.0F ? current : idle;
  836. Update000Button.Background = percentage >= 00.0F ? current : idle;
  837. Button firstbutton = null;
  838. //LoadDrawing(Guid.Empty);
  839. ButtonStack.Children.Clear();
  840. // If we are quality checking, add the QA Check button
  841. if (!Pending)
  842. {
  843. var qabtn = new Button();
  844. qabtn.Content = "Quality Checks";
  845. qabtn.Tag = null;
  846. qabtn.Style = Resources["UnselectedButton"] as Style;
  847. qabtn.Click += ViewQualityChecks;
  848. ButtonStack.Children.Add(qabtn);
  849. if (packet.Drawing.IsValid())
  850. {
  851. var pdfbtn = new Button();
  852. pdfbtn.Content = packet.Drawing.FileName.ToLower();
  853. pdfbtn.Tag = packet.Drawing;
  854. pdfbtn.Style = Resources["UnselectedButton"] as Style;
  855. pdfbtn.Click += ViewDrawing;
  856. ButtonStack.Children.Add(pdfbtn);
  857. firstbutton = pdfbtn;
  858. }
  859. // List all available PDFs for this Setout
  860. documents = new Client<SetoutDocument>().Load(
  861. new Filter<SetoutDocument>(x => x.EntityLink.ID).IsEqualTo(CurrentKanban.SetoutID));
  862. foreach (var document in documents)
  863. {
  864. // If this document is actually the cutting group document,
  865. // redirect any annotations to the cutting group id rather than the setout
  866. if (document.DocumentLink.ID == packet.SetoutLink.Group.OptimizationDocument.ID)
  867. document.ID = packet.SetoutLink.Group.ID;
  868. if (document.DocumentLink != null && document.DocumentLink.FileName != null)
  869. if (document.DocumentLink.FileName.ToLower().EndsWith(".pdf") ||
  870. document.DocumentLink.FileName.ToLower().EndsWith(".png") ||
  871. document.DocumentLink.FileName.ToLower().EndsWith(".bmp") ||
  872. document.DocumentLink.FileName.ToLower().EndsWith(".jpg"))
  873. {
  874. var pdfbtn = new Button();
  875. pdfbtn.Content = document.DocumentLink.FileName.ToLower() +
  876. (!document.Superceded.IsEmpty() ? " (SUPERCEDED)" : "");
  877. pdfbtn.Tag = document.DocumentLink;
  878. pdfbtn.Style = Resources["UnselectedButton"] as Style;
  879. pdfbtn.Click += ViewDrawing;
  880. ButtonStack.Children.Add(pdfbtn);
  881. if (document.Superceded.IsEmpty())
  882. if ((PDFEditor != null && PDFEditor.Document.ID.Equals(document.ID)) ||
  883. firstbutton == null)
  884. firstbutton = pdfbtn;
  885. }
  886. }
  887. if (firstbutton == null)
  888. firstbutton = qabtn;
  889. }
  890. if (firstbutton != null)
  891. //SetCurrentButton(firstbutton);
  892. firstbutton.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));
  893. else
  894. LoadDrawing(null);
  895. } // Kanban has not changed - do nothing
  896. if (_packLinked.IsChecked == true)
  897. _packGrid.Refresh(false,false);
  898. }
  899. }
  900. private void SetCurrentButton(Button button)
  901. {
  902. if (_currentButton != null)
  903. _currentButton.Style = Resources["UnselectedButton"] as Style;
  904. _currentButton = button;
  905. button.Style = Resources["SelectedButton"] as Style;
  906. }
  907. private void SwimLaneSelected(object sender, MouseButtonEventArgs e)
  908. {
  909. }
  910. private void CardSelected(object sender, MouseButtonEventArgs e)
  911. {
  912. var border = (Border)sender;
  913. CurrentKanban = (ManufacturingKanban)border.Tag;
  914. UpdateSelectedKanban();
  915. }
  916. private bool CheckedPacketsChanged(Dictionary<Guid, Tuple<DateTime, DateTime>> lastCheckedPackets,
  917. Dictionary<Guid, Tuple<DateTime, DateTime>> newCheckedPackets)
  918. {
  919. if (lastCheckedPackets.Count != newCheckedPackets.Count)
  920. return true;
  921. foreach (var key in lastCheckedPackets.Keys)
  922. {
  923. if (!newCheckedPackets.ContainsKey(key))
  924. return true;
  925. if (!newCheckedPackets[key].Item1.Equals(lastCheckedPackets[key].Item1))
  926. return true;
  927. if (!newCheckedPackets[key].Item2.Equals(lastCheckedPackets[key].Item2))
  928. return true;
  929. }
  930. return false;
  931. }
  932. private void UpdateSelectedKanban(bool uncheckothers = true)
  933. {
  934. if (CurrentKanban != null)
  935. {
  936. var others = Kanbans.Where(x => x.Checked && x.Assignee != CurrentKanban.Assignee).ToArray();
  937. foreach (var other in others)
  938. other.Checked = false;
  939. others = Kanbans.Where(x => x.Checked).ToArray();
  940. if (others.Length == 1)
  941. others[0].Checked = false;
  942. others = Kanbans.Where(x => x.IsSelected).ToArray();
  943. foreach (var other in others)
  944. {
  945. other.IsSelected = false;
  946. var pkt = KanbanToPacket(other);
  947. if (pkt != null)
  948. //var stg = Stages.FirstOrDefault(x => x.ManufacturingPacketLink.ID.Equals(pkt.ID));
  949. other.SelectedColor = other.ColorKey;
  950. else
  951. other.SelectedColor = other.ColorKey;
  952. }
  953. CurrentKanban.Checked = true;
  954. CurrentKanban.IsSelected = true;
  955. CurrentKanban.SelectedColor = SELECTED_COLOR;
  956. }
  957. //UpdateTimeTracking();
  958. Kanban.ItemsSource = null;
  959. Kanban.ItemsSource = Kanbans.OrderBy(x => x.Assignee).ThenByDescending(x => x.Tags.Length).ThenBy(x => x.DueDate).ThenBy(x => x.JobName);
  960. LoadKanban();
  961. }
  962. private void CardChecked(object sender, RoutedEventArgs e)
  963. {
  964. //UpdateTimeTracking();
  965. try
  966. {
  967. var chk = sender as CheckBox;
  968. var border = (chk.Parent as Grid).Parent as Border;
  969. var kanban = border.Tag as ManufacturingKanban;
  970. kanban.Checked = chk.IsChecked == true;
  971. if (kanban.Checked)
  972. foreach (var other in Kanbans.Where(x => x.Assignee != kanban.Assignee))
  973. other.Checked = false;
  974. }
  975. catch (Exception err)
  976. {
  977. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", err.Message, err.StackTrace));
  978. }
  979. //Kanban.ItemsSource = null;
  980. //Kanban.ItemsSource = Kanbans.OrderBy(x => x.Assignee).ThenByDescending(x => x.Tags.Length).ThenBy(x => x.DueDate).ThenBy(x => x.JobName);
  981. }
  982. private void CompleteButton_Click(object sender, RoutedEventArgs e)
  983. {
  984. var packets = new List<ManufacturingPacket>();
  985. foreach (var kanban in Kanbans.Where(x => x.Checked || x.IsSelected))
  986. {
  987. var packet = KanbanToPacket(kanban);
  988. if (packet.StageLink.SectionID != CurrentSection.ID)
  989. {
  990. MessageBox.Show("You cannot complete a distributed packet that is not yet progressed to your station!");
  991. return;
  992. }
  993. var qacomplete = true;
  994. var stage = Stages.Rows.FirstOrDefault(r => r.Get<ManufacturingPacketStage, Guid>(c => c.Parent.ID).Equals(packet.ID)
  995. && r.Get<ManufacturingPacketStage, Guid>(c => c.ManufacturingSectionLink.ID)
  996. .Equals(_settings.Section));
  997. if (stage != null)
  998. {
  999. var qadata = stage.Get<ManufacturingPacketStage, string>(c => c.FormData);
  1000. var questions = LoadQAQuestions(packet, true, true);
  1001. if (questions != null)
  1002. {
  1003. var answers = string.IsNullOrWhiteSpace(qadata)
  1004. ? new Dictionary<Guid, object>()
  1005. : Serialization.Deserialize<Dictionary<Guid, object>>(qadata);
  1006. foreach (var question in questions)
  1007. {
  1008. var parameters = question.ParseParameters();
  1009. var bAnswerRequired = question.Answer != QAAnswer.Comment &&
  1010. (!parameters.ContainsKey("Default") || string.IsNullOrWhiteSpace(parameters["Default"]));
  1011. if (bAnswerRequired && (!answers.ContainsKey(question.ID) || answers[question.ID] == null))
  1012. {
  1013. qacomplete = false;
  1014. break;
  1015. }
  1016. }
  1017. }
  1018. }
  1019. if (!qacomplete)
  1020. {
  1021. MessageBox.Show("You must complete the required QA checks before completing these items!");
  1022. return;
  1023. }
  1024. packets.Add(packet);
  1025. }
  1026. Progress.Show("Scanning Packets");
  1027. //Filter<ManufacturingPacketStage> stgflt = new Filter<ManufacturingPacketStage>(x => x.ID).IsEqualTo(CoreUtils.FullGuid);
  1028. //foreach (var pkt in packets)
  1029. // stgflt = stgflt.Or(x => x.ManufacturingPacketLink.ID).IsEqualTo(pkt.ID);
  1030. //ManufacturingPacketStage[] stgs = new Client<ManufacturingPacketStage>().Load(stgflt, new SortOrder<ManufacturingPacketStage>(x => x.Sequence));
  1031. var stage_updates = new List<ManufacturingPacketStage>();
  1032. for (var i = 0; i < packets.Count; i++)
  1033. {
  1034. var packet = packets[i];
  1035. var stagerows = Stages.Rows.Where(r => r.Get<ManufacturingPacketStage, Guid>(c => c.Parent.ID).Equals(packet.ID));
  1036. var stages = stagerows.Select(r => r.ToObject<ManufacturingPacketStage>());
  1037. //var stages = stgs.Where(x => x.ManufacturingPacketLink.ID.Equals(packet.ID));
  1038. long sequence = 0;
  1039. // Send the update to the server
  1040. var stage = stages.FirstOrDefault(x => x.ID.Equals(packet.StageLink.ID));
  1041. if (stage != null)
  1042. {
  1043. stage.Completed = DateTime.Now;
  1044. if(stage.Form.ID == Guid.Empty)
  1045. {
  1046. stage.Form.ID = CurrentSection.QAForm.ID;
  1047. }
  1048. if(stage.Form.ID != Guid.Empty)
  1049. {
  1050. stage.FormCompleted = DateTime.Now;
  1051. stage.FormCompletedBy.ID = ClientFactory.UserGuid;
  1052. }
  1053. stage.PercentageComplete = 100.0F;
  1054. if (!stage_updates.Contains(stage))
  1055. stage_updates.Add(stage);
  1056. sequence = stage.Sequence;
  1057. }
  1058. // Also update the local copy (hacky hacky)
  1059. var stagerow = Stages.Rows.FirstOrDefault(r => r.Get<ManufacturingPacketStage, Guid>(c => c.ID).Equals(packet.StageLink.ID));
  1060. if (stagerow != null)
  1061. {
  1062. stagerow.Set<ManufacturingPacketStage, DateTime>(x => x.Completed, DateTime.Now);
  1063. stagerow.Set<ManufacturingPacketStage, DateTime>(x => x.FormCompleted, DateTime.Now);
  1064. stagerow.Set<ManufacturingPacketStage, Guid>(x => x.FormCompletedBy.ID, ClientFactory.UserGuid);
  1065. stagerow.Set<ManufacturingPacketStage, double>(x => x.PercentageComplete, 100.0F);
  1066. }
  1067. // Update the pointer to the next stage
  1068. // But only if it's at your station already
  1069. // This takes into account distributed packets that may not be completed elsewhere
  1070. if (packet.StageLink.SectionID == CurrentSection.ID)
  1071. {
  1072. stage = stages.Where(x => x.Sequence > sequence).FirstOrDefault();
  1073. // If this is a distributed packet, then it may already have data allocated to it
  1074. // We on;y want to reset the next stage if it's not distributed
  1075. if (!packet.Distributed)
  1076. if (stage != null)
  1077. {
  1078. stage.QualityStatus = QualityStatus.NotChecked;
  1079. stage.QualityNotes = "";
  1080. stage.Station = 0;
  1081. stage.Started = DateTime.MinValue;
  1082. stage.Completed = DateTime.MinValue;
  1083. stage.PercentageComplete = 0.0F;
  1084. if (!stage_updates.Contains(stage))
  1085. stage_updates.Add(stage);
  1086. }
  1087. }
  1088. packet.StageLink.ID = stage == null ? CoreUtils.FullGuid : stage.ID;
  1089. packet.Issued = !packet.StageLink.IsValid() ? DateTime.MinValue : packet.Issued.IsEmpty() ? DateTime.Now : packet.Issued;
  1090. packet.Completed = packet.StageLink.ID.Equals(CoreUtils.FullGuid)
  1091. ? packet.Completed.IsEmpty() ? DateTime.Now : packet.Completed
  1092. : DateTime.MinValue;
  1093. }
  1094. Progress.SetMessage("Progressing Items");
  1095. new Client<ManufacturingPacketStage>().Save(stage_updates, "ManufacturingPacket Progressed from Factory Floor");
  1096. new Client<ManufacturingPacket>().Save(packets, "ManufacturingPacket Progressed From Factory Floor");
  1097. //UpdateTimeTracking();
  1098. Heartbeat(new TimeSpan(0L));
  1099. CurrentKanban = null;
  1100. Refresh();
  1101. Progress.Close();
  1102. }
  1103. private void UpdateButtonClick(object sender, RoutedEventArgs e)
  1104. {
  1105. Progress.Show("");
  1106. double percent = 0.0F;
  1107. if (double.TryParse(((Button)sender).Tag.ToString(), out percent))
  1108. {
  1109. var selected = new List<ManufacturingPacket>();
  1110. var stages = new List<ManufacturingPacketStage>();
  1111. foreach (var kanban in Kanbans.Where(x => x.Checked || x.IsSelected))
  1112. {
  1113. selected.Add(KanbanToPacket(kanban));
  1114. var pktid = Guid.Parse(kanban.ID);
  1115. var stagerows = Stages.Rows.Where(r =>
  1116. r.Get<ManufacturingPacketStage, Guid>(c => c.SectionID).Equals(CurrentSection.ID) &&
  1117. r.Get<ManufacturingPacketStage, Guid>(c => c.Parent.ID).Equals(pktid));
  1118. stages.AddRange(stagerows.Select(r => r.ToObject<ManufacturingPacketStage>()));
  1119. }
  1120. var updates = new List<ManufacturingPacketStage>();
  1121. foreach (var stage in stages)
  1122. {
  1123. var bChanged = false;
  1124. if (stage.Started == DateTime.MinValue)
  1125. {
  1126. stage.Started = DateTime.Now;
  1127. bChanged = true;
  1128. }
  1129. if (stage.PercentageComplete != percent)
  1130. {
  1131. stage.PercentageComplete = percent;
  1132. bChanged = true;
  1133. }
  1134. if (stage.Station != -1 && stage.Station != CurrentStation)
  1135. {
  1136. stage.Station = CurrentStation;
  1137. bChanged = true;
  1138. }
  1139. if (bChanged)
  1140. updates.Add(stage);
  1141. }
  1142. new Client<ManufacturingPacketStage>().Save(updates, "Progress Updated from Factory Floor");
  1143. DoRefresh(true);
  1144. }
  1145. Progress.Close();
  1146. }
  1147. private void TearOffButton_Click(object sender, RoutedEventArgs e)
  1148. {
  1149. var doc = PDFEditor.Document;
  1150. var window = new ThemableWindow();
  1151. var editor = new PDFEditorControl();
  1152. editor.SaveAllowed = Security.IsAllowed<CanSaveFactoryFloorDrawings>();
  1153. editor.Document = doc;
  1154. window.Content = editor;
  1155. window.Show();
  1156. }
  1157. private void BarcodesButton_Click(object sender, RoutedEventArgs e)
  1158. {
  1159. //List<ManufacturingPacket> updates = new List<ManufacturingPacket>();
  1160. var checkedpackets =
  1161. Packets.Rows.Where(p => Kanbans.Any(k => k.Checked && p.Get<ManufacturingPacket, Guid>(c => c.ID).ToString().Equals(k.ID)));
  1162. if (!checkedpackets.Any())
  1163. {
  1164. MessageBox.Show("Please select a packet before continuing");
  1165. return;
  1166. }
  1167. Progress.Show("");
  1168. Filter<ManufacturingPacket> pktflt = null;
  1169. foreach (var row in checkedpackets)
  1170. pktflt = pktflt == null
  1171. ? new Filter<ManufacturingPacket>(x => x.ID).IsEqualTo(row.Get<ManufacturingPacket, Guid>(c => c.ID))
  1172. : pktflt.Or(x => x.ID).IsEqualTo(row.Get<ManufacturingPacket, Guid>(c => c.ID));
  1173. var pkts = new Client<ManufacturingPacket>().Load(pktflt);
  1174. foreach (var pkt in pkts)
  1175. //var pkt = row.ToObject<ManufacturingPacket>();
  1176. if (pkt.BarcodePrinted == DateTime.MinValue)
  1177. pkt.BarcodePrinted = DateTime.Now;
  1178. //updates.Add(pkt);
  1179. //if (updates.Any())
  1180. //{
  1181. Progress.SetMessage("Creating Barcodes");
  1182. new Client<ManufacturingPacket>().Save(pkts, "Delivery Barcodes created");
  1183. //}
  1184. Filter<DeliveryItem> filter = null;
  1185. foreach (var row in checkedpackets)
  1186. {
  1187. var pktid = row.Get<ManufacturingPacket, Guid>(c => c.ID);
  1188. if (filter == null)
  1189. filter = new Filter<DeliveryItem>(x => x.ManufacturingPacketLink.ID).IsEqualTo(pktid);
  1190. else
  1191. filter = filter.Or(x => x.ManufacturingPacketLink.ID).IsEqualTo(pktid);
  1192. }
  1193. var dataenvironment = new Dictionary<Type, CoreTable>();
  1194. var model = new DeliveryItemDataModel(filter);
  1195. var Group = Packets.Rows.Select(r => r.Get<ManufacturingPacket, string>(c => c.Group)).FirstOrDefault();
  1196. var BaseReportName = "Print Bar Codes";
  1197. var sectionName = "Delivery Items";
  1198. var repflt = new Filter<ReportTemplate>(x => x.Name).IsEqualTo(BaseReportName);
  1199. var DesiredReportName = BaseReportName + (!string.IsNullOrWhiteSpace(Group) ? " - " + Group : "");
  1200. if (DesiredReportName != BaseReportName)
  1201. repflt = repflt.Or(x => x.Name).IsEqualTo(DesiredReportName);
  1202. var repflt2 = new Filter<ReportTemplate>(x => x.DataModel).IsEqualTo(model.Name).And(x => x.Section).IsEqualTo(sectionName);
  1203. repflt2.Ands.Add(repflt);
  1204. var templates = new Client<ReportTemplate>().Load(repflt2);
  1205. var report = templates.FirstOrDefault(x => x.Name == DesiredReportName);
  1206. if (report == null)
  1207. report = templates.FirstOrDefault(x => x.Name == BaseReportName);
  1208. if (report == null)
  1209. {
  1210. Progress.Close();
  1211. MessageBox.Show("Ready To Go -> [Print Bar Codes] report does not exist!");
  1212. Refresh();
  1213. }
  1214. Progress.Close();
  1215. ReportUtils.PreviewReport(report, model, false, Security.IsAllowed<CanDesignReports>());
  1216. Refresh();
  1217. }
  1218. private void ViewDrawing(object sender, RoutedEventArgs e)
  1219. {
  1220. var button = (Button)sender;
  1221. SetCurrentButton(button);
  1222. var doc = button.Tag as IEntityLink;
  1223. LoadDrawing(doc.ID);
  1224. }
  1225. private void Search_KeyUp(object sender, KeyEventArgs e)
  1226. {
  1227. SearchFilter = Search.Text;
  1228. if (e.Key == Key.Enter || string.IsNullOrEmpty(Search.Text))
  1229. {
  1230. ClearAllSelections();
  1231. ReloadPackets(true);
  1232. }
  1233. }
  1234. //private void SwimlaneCheckBox_Checked(object sender, RoutedEventArgs e)
  1235. //{
  1236. // CheckBox chk = sender as CheckBox;
  1237. // String tag = chk.Tag as String;
  1238. // foreach (var packet in Kanbans)
  1239. // packet.Checked = (packet.Assignee == tag) ? !packet.Checked : false;
  1240. // Kanban.ItemsSource = null;
  1241. // Kanban.ItemsSource = Kanbans.OrderBy(x => x.Assignee).ThenByDescending(x => x.Tags.Length).ThenBy(x => x.DueDate).ThenBy(x => x.JobName);
  1242. //}
  1243. //private void CardBorder_PreviewMouseWheel(object sender, MouseWheelEventArgs e)
  1244. //{
  1245. // e.Handled = true;
  1246. // var eventArg = new MouseWheelEventArgs(e.MouseDevice, e.Timestamp, e.Delta);
  1247. // eventArg.RoutedEvent = UIElement.MouseWheelEvent;
  1248. // eventArg.Source = sender;
  1249. // var tgts = FindVisualChildren<UIElement>(Kanban.Columns[0]);
  1250. // foreach (var tgt in tgts)
  1251. // tgt.RaiseEvent(eventArg);
  1252. //}
  1253. private void PacketMenu_Opened(object sender, RoutedEventArgs e)
  1254. {
  1255. var menu = sender as ContextMenu;
  1256. var setcurrent = menu.Items[0] as MenuItem;
  1257. var setpending = menu.Items[1] as MenuItem;
  1258. var actionseparator = menu.Items[2] as Separator;
  1259. var settrolley = menu.Items[3] as MenuItem;
  1260. var cleartrolley = menu.Items[4] as MenuItem;
  1261. var trolleyseparator = menu.Items[5] as Separator;
  1262. var setpriority = menu.Items[6] as MenuItem;
  1263. var clearpriority = menu.Items[7] as MenuItem;
  1264. var editissues = menu.Items[8] as MenuItem;
  1265. var sethold = menu.Items[9] as MenuItem;
  1266. var clearhold = menu.Items[10] as MenuItem;
  1267. var setdistributed = menu.Items[11] as MenuItem;
  1268. var cleardistributed = menu.Items[12] as MenuItem;
  1269. var distseparator = menu.Items[13] as Separator;
  1270. var setshared = menu.Items[14] as MenuItem;
  1271. var clearshared = menu.Items[15] as MenuItem;
  1272. var movepacket = menu.Items[16] as MenuItem;
  1273. var requestMaterials = menu.Items[18] as MenuItem;
  1274. var model = menu.Tag as ManufacturingKanban;
  1275. if (!model.Checked)
  1276. {
  1277. foreach (var kanban in Kanbans.Where(x => x.Checked).ToArray())
  1278. kanban.Checked = false;
  1279. model.Checked = true;
  1280. //Kanban.ItemsSource = null;
  1281. //Kanban.ItemsSource = Kanbans.OrderBy(x => x.Assignee).ThenByDescending(x => x.Tags.Length).ThenBy(x => x.DueDate).ThenBy(x => x.JobName);
  1282. }
  1283. var checkedkanbans = Kanbans.Where(k => k.Checked).Select(x => Guid.Parse(x.ID));
  1284. var checkedpackets = Packets.Rows.Where(r => checkedkanbans.Contains(r.Get<ManufacturingPacket, Guid>(c => c.ID)));
  1285. var checkedstages = Stages.Rows.Where(r => checkedkanbans.Contains(r.Get<ManufacturingPacketStage, Guid>(c => c.Parent.ID))
  1286. && r.Get<ManufacturingPacketStage, Guid>(c => c.ManufacturingSectionLink.ID)
  1287. .Equals(_settings.Section));
  1288. // Only if we right-click on a checked packet??
  1289. if (checkedpackets.Any() && checkedstages.Any())
  1290. {
  1291. var iStation = checkedstages.First().Get<ManufacturingPacketStage, int>(c => c.Station);
  1292. setcurrent.Visibility = iStation == 0 ? Visibility.Visible : Visibility.Collapsed;
  1293. setpending.Visibility = iStation > 0 ? Visibility.Visible : Visibility.Collapsed;
  1294. actionseparator.Visibility = Visibility.Collapsed;
  1295. settrolley.Visibility = Visibility.Visible;
  1296. cleartrolley.Visibility =
  1297. checkedpackets.Select(r => r.Get<ManufacturingPacket, string>(x => x.Trolleys)).Any(x => !string.IsNullOrWhiteSpace(x))
  1298. ? Visibility.Visible
  1299. : Visibility.Collapsed;
  1300. setpriority.Visibility = Visibility.Collapsed; // (packet != null) && packet.Priority ? Visibility.Collapsed : Visibility.Visible;
  1301. clearpriority.Visibility = Visibility.Collapsed; // (packet != null) && packet.Priority ? Visibility.Visible : Visibility.Collapsed;
  1302. editissues.Visibility = Visibility.Visible;
  1303. sethold.Visibility =
  1304. false //Security.IsAllowed<CanManagePacketHolds>() && checkedpackets.Any(r => !r.Get<ManufacturingPacket, bool>(c => c.OnHold))
  1305. ? Visibility.Visible
  1306. : Visibility.Collapsed;
  1307. clearhold.Visibility =
  1308. false //Security.IsAllowed<CanManagePacketHolds>() && checkedpackets.Any(r => r.Get<ManufacturingPacket, bool>(c => c.OnHold))
  1309. ? Visibility.Visible
  1310. : Visibility.Collapsed;
  1311. setdistributed.Visibility = Security.IsAllowed<CanDistributePackets>() &&
  1312. checkedpackets.Any(r => r.Get<ManufacturingPacket, bool>(c => c.Distributed) == false)
  1313. ? Visibility.Visible
  1314. : Visibility.Collapsed;
  1315. cleardistributed.Visibility = Security.IsAllowed<CanDistributePackets>() &&
  1316. checkedpackets.Any(r => r.Get<ManufacturingPacket, bool>(c => c.Distributed))
  1317. ? Visibility.Visible
  1318. : Visibility.Collapsed;
  1319. distseparator.Visibility = setdistributed.Visibility == Visibility.Visible || cleardistributed.Visibility == Visibility.Visible
  1320. ? Visibility.Visible
  1321. : Visibility.Collapsed;
  1322. setshared.Visibility = iStation > 0 ? Visibility.Visible : Visibility.Collapsed;
  1323. clearshared.Visibility = iStation < 0 ? Visibility.Visible : Visibility.Collapsed;
  1324. movepacket.Visibility = iStation > 0 ? Visibility.Visible : Visibility.Collapsed;
  1325. setcurrent.Tag = checkedstages;
  1326. setpending.Tag = checkedstages;
  1327. setpriority.Tag = checkedpackets;
  1328. clearpriority.Tag = checkedpackets;
  1329. editissues.Tag = checkedpackets;
  1330. sethold.Tag = checkedpackets;
  1331. clearhold.Tag = checkedpackets;
  1332. setdistributed.Tag = checkedpackets;
  1333. cleardistributed.Tag = checkedpackets;
  1334. setshared.Tag = checkedstages;
  1335. clearshared.Tag = checkedstages;
  1336. movepacket.Tag = checkedstages;
  1337. requestMaterials.Tag = checkedpackets;
  1338. if (movepacket.Visibility == Visibility.Visible)
  1339. {
  1340. movepacket.Items.Clear();
  1341. foreach (var station in Station.Items)
  1342. {
  1343. var sub = new MenuItem { Header = station, Tag = checkedstages };
  1344. sub.Click += MovePacketClick;
  1345. movepacket.Items.Add(sub);
  1346. sub.Visibility = movepacket.Items.Count == CurrentStation ? Visibility.Collapsed : Visibility.Visible;
  1347. }
  1348. }
  1349. settrolley.Tag = Kanbans.Where(k => k.Checked);
  1350. cleartrolley.Tag = Kanbans.Where(k => k.Checked);
  1351. //if (Trolleys == null)
  1352. //{
  1353. // Trolleys = new Client<ManufacturingTrolley>().Query(
  1354. // LookupFactory.DefineFilter<ManufacturingTrolley>(),
  1355. // LookupFactory.DefineColumns<ManufacturingTrolley>(),
  1356. // LookupFactory.DefineSort<ManufacturingTrolley>()
  1357. // );
  1358. //}
  1359. //if (Trolleys.Rows.Any())
  1360. //{
  1361. // settrolley.Visibility = Visibility.Visible;
  1362. // settrolley.Items.Clear();
  1363. // foreach (var row in Trolleys.Rows)
  1364. // {
  1365. // MenuItem sub = new MenuItem() { Header = row.Get<ManufacturingTrolley,String>(x=>x.Code) + ": "+ row.Get<ManufacturingTrolley, String>(x => x.Description), Tag = row.Get<ManufacturingTrolley,Guid>(x=>x.ID) };
  1366. // sub.Click += SetTrolleyClick;
  1367. // settrolley.Items.Add(sub);
  1368. // }
  1369. //}
  1370. //else
  1371. // settrolley.Visibility = Visibility.Collapsed;
  1372. }
  1373. // Disable everything
  1374. }
  1375. private void SetPacketToTrolley(string trolley, params ManufacturingPacket[] packets)
  1376. {
  1377. var updates = new List<ManufacturingPacket>();
  1378. foreach (var packet in packets)
  1379. if (string.Equals(packet.Trolleys, trolley))
  1380. {
  1381. packet.Trolleys = trolley;
  1382. updates.Add(packet);
  1383. }
  1384. if (updates.Any())
  1385. using (new WaitCursor())
  1386. {
  1387. new Client<ManufacturingPacket>().Save(updates, string.Format("Moved Packet to Trolley {0}", trolley), (o, e) => { });
  1388. foreach (var update in updates)
  1389. {
  1390. var pktrow = Packets.Rows.FirstOrDefault(r => r.Get<ManufacturingPacket, Guid>(c => c.ID).Equals(update.ID));
  1391. var stagerow = Stages.Rows.FirstOrDefault(r => r.Get<ManufacturingPacketStage, Guid>(c => c.Parent.ID).Equals(update.ID)
  1392. && r.Get<ManufacturingPacketStage, Guid>(c => c.ManufacturingSectionLink.ID)
  1393. .Equals(_settings.Section));
  1394. //ManufacturingPacketStage stage = Stages.Rows.FirstOrDefault(r => r.Get<ManufacturingPacketStage, Guid>(x => x.Parent.ID).Equals(update.ID))?.ToObject<ManufacturingPacketStage>();
  1395. var kanban = Kanbans.FirstOrDefault(x => x.ID.Equals(update.ID.ToString()));
  1396. LoadModel(kanban, pktrow, stagerow, true);
  1397. }
  1398. }
  1399. }
  1400. private void SetTrolleyClick(object sender, RoutedEventArgs e)
  1401. {
  1402. var kanbans = (sender as MenuItem).Tag as IEnumerable<ManufacturingKanban>;
  1403. List<string> trolleyPrePopulate = new List<string>();
  1404. foreach (ManufacturingKanban kanban in kanbans)
  1405. {
  1406. if (!string.IsNullOrWhiteSpace(kanban.Trolleys))
  1407. {
  1408. if (kanban.Trolleys.Contains(','))
  1409. {
  1410. var splitTrolleys = kanban.Trolleys.Split(',');
  1411. foreach (string s in splitTrolleys)
  1412. {
  1413. if (!trolleyPrePopulate.Contains(s))
  1414. {
  1415. trolleyPrePopulate.Add(s);
  1416. }
  1417. }
  1418. }
  1419. else
  1420. {
  1421. if (!trolleyPrePopulate.Contains(kanban.Trolleys))
  1422. {
  1423. trolleyPrePopulate.Add(kanban.Trolleys);
  1424. }
  1425. }
  1426. }
  1427. }
  1428. var dlg = new MultiSelectWindow(typeof(ManufacturingTrolley), new Guid[] { }, trolleyPrePopulate);
  1429. if (dlg.ShowDialog() == true)
  1430. using (new WaitCursor())
  1431. {
  1432. var trolleys = new List<string>();
  1433. foreach (ManufacturingTrolley value in dlg.Values)
  1434. trolleys.Add(value.Code);
  1435. var updates = new List<ManufacturingPacket>();
  1436. foreach (var kanban in kanbans)
  1437. {
  1438. var pktrow = Packets.Rows.FirstOrDefault(r => r.Get<ManufacturingPacket, Guid>(c => c.ID).Equals(Guid.Parse(kanban.ID)));
  1439. var stagerow = Stages.Rows.FirstOrDefault(r =>
  1440. r.Get<ManufacturingPacketStage, Guid>(c => c.Parent.ID).Equals(Guid.Parse(kanban.ID))
  1441. && r.Get<ManufacturingPacketStage, Guid>(c => c.ManufacturingSectionLink.ID).Equals(_settings.Section));
  1442. var packet = pktrow.ToObject<ManufacturingPacket>();
  1443. packet.Trolleys = string.Join(",", trolleys);
  1444. updates.Add(packet);
  1445. pktrow.Set<ManufacturingPacket, string>(x => x.Trolleys, packet.Trolleys);
  1446. LoadModel(kanban, pktrow, stagerow, true);
  1447. }
  1448. if (updates.Any())
  1449. {
  1450. new Client<ManufacturingPacket>().Save(updates, "Set Trolley to " + (sender as MenuItem).Header, (objects, error) => { });
  1451. var src = Kanban.ItemsSource;
  1452. Kanban.ItemsSource = null;
  1453. Kanban.ItemsSource = src;
  1454. }
  1455. }
  1456. //Refresh();
  1457. }
  1458. private void ClearTrolleyClick(object sender, RoutedEventArgs e)
  1459. {
  1460. var kanbans = (sender as MenuItem).Tag as IEnumerable<ManufacturingKanban>;
  1461. using (new WaitCursor())
  1462. {
  1463. var updates = new List<ManufacturingPacket>();
  1464. foreach (var kanban in kanbans)
  1465. {
  1466. var pktrow = Packets.Rows.FirstOrDefault(r => r.Get<ManufacturingPacket, Guid>(c => c.ID).Equals(Guid.Parse(kanban.ID)));
  1467. var stagerow = Stages.Rows.FirstOrDefault(r =>
  1468. r.Get<ManufacturingPacketStage, Guid>(c => c.Parent.ID).Equals(Guid.Parse(kanban.ID))
  1469. && r.Get<ManufacturingPacketStage, Guid>(c => c.ManufacturingSectionLink.ID)
  1470. .Equals(_settings.Section));
  1471. var packet = pktrow.ToObject<ManufacturingPacket>();
  1472. packet.Trolleys = "";
  1473. updates.Add(packet);
  1474. pktrow.Set<ManufacturingPacket, string>(x => x.Trolleys, packet.Trolleys);
  1475. LoadModel(kanban, pktrow, stagerow, true);
  1476. }
  1477. if (updates.Any())
  1478. {
  1479. new Client<ManufacturingPacket>().Save(updates, "Removed From Trolley", (objects, error) => { });
  1480. var src = Kanban.ItemsSource;
  1481. Kanban.ItemsSource = null;
  1482. Kanban.ItemsSource = src;
  1483. }
  1484. }
  1485. }
  1486. private void SetCurrent_Click(object sender, RoutedEventArgs e)
  1487. {
  1488. var rows = (sender as MenuItem).Tag as IEnumerable<CoreRow>;
  1489. var stages = rows.Select(x => x.ToObject<ManufacturingPacketStage>()).ToArray();
  1490. AddPacketToCurrentWorkload(stages);
  1491. CurrentKanban = Kanbans.FirstOrDefault(x => x.ID.Equals(stages.First().Parent.ID.ToString()));
  1492. UpdateSelectedKanban(false);
  1493. }
  1494. private void AddPacketToCurrentWorkload(params ManufacturingPacketStage[] stages)
  1495. {
  1496. var updates = new List<ManufacturingPacketStage>();
  1497. foreach (var stage in stages)
  1498. if (stage.Station == 0)
  1499. {
  1500. stage.Station = CurrentStation;
  1501. stage.Started = DateTime.Now;
  1502. updates.Add(stage);
  1503. }
  1504. if (updates.Any())
  1505. using (new WaitCursor())
  1506. {
  1507. new Client<ManufacturingPacketStage>().Save(updates, string.Format("Moved Packet to Station {0}", CurrentStation), (o, e) => { });
  1508. foreach (var update in updates)
  1509. {
  1510. var pktrow = Packets.Rows.FirstOrDefault(r => r.Get<ManufacturingPacket, Guid>(c => c.ID).Equals(update.Parent.ID));
  1511. var stagerow = Stages.Rows.FirstOrDefault(r => r.Get<ManufacturingPacketStage, Guid>(x => x.ID).Equals(update.ID));
  1512. Stages.LoadRow(stagerow, update);
  1513. var kanban = Kanbans.FirstOrDefault(x => x.ID.Equals(update.Parent.ID.ToString()));
  1514. LoadModel(kanban, pktrow, stagerow, true);
  1515. }
  1516. }
  1517. }
  1518. private void SetPending_Click(object sender, RoutedEventArgs e)
  1519. {
  1520. var updates = new List<ManufacturingPacketStage>();
  1521. var rows = (sender as MenuItem).Tag as IEnumerable<CoreRow>;
  1522. foreach (var row in rows)
  1523. {
  1524. var stage = row.ToObject<ManufacturingPacketStage>();
  1525. if (stage.Station != 0)
  1526. {
  1527. stage.Station = 0;
  1528. stage.Started = DateTime.MinValue;
  1529. updates.Add(stage);
  1530. }
  1531. }
  1532. if (updates.Any())
  1533. using (new WaitCursor())
  1534. {
  1535. new Client<ManufacturingPacketStage>().Save(updates, string.Format("Removed Packet from Station {0}", CurrentStation));
  1536. foreach (var update in updates)
  1537. {
  1538. var pktrow = Packets.Rows.FirstOrDefault(r => r.Get<ManufacturingPacket, Guid>(c => c.ID).Equals(update.Parent.ID));
  1539. var stagerow = Stages.Rows.FirstOrDefault(r => r.Get<ManufacturingPacketStage, Guid>(x => x.ID).Equals(update.ID));
  1540. Stages.LoadRow(stagerow, update);
  1541. var kanban = Kanbans.FirstOrDefault(x => x.ID.Equals(update.Parent.ID.ToString()));
  1542. LoadModel(kanban, pktrow, stagerow, true);
  1543. }
  1544. CurrentKanban = Kanbans.FirstOrDefault(x => x.ID.Equals(updates.First().Parent.ID.ToString()));
  1545. UpdateSelectedKanban();
  1546. }
  1547. }
  1548. private void UpdateFlag(object sender, string property, bool value)
  1549. {
  1550. var updates = new List<ManufacturingPacket>();
  1551. var rows = (sender as MenuItem)!.Tag as IEnumerable<CoreRow>;
  1552. foreach (var row in rows)
  1553. {
  1554. var packet = row.ToObject<ManufacturingPacket>();
  1555. CoreUtils.SetPropertyValue(packet, property, value);
  1556. updates.Add(packet);
  1557. }
  1558. if (updates.Any())
  1559. using (new WaitCursor())
  1560. {
  1561. new Client<ManufacturingPacket>().Save(updates, property + " Flag " + (value ? "Set" : "Cleared"));
  1562. Refresh();
  1563. }
  1564. }
  1565. private void SetPriority_Click(object sender, RoutedEventArgs e)
  1566. {
  1567. UpdateFlag(sender, "Priority", true);
  1568. }
  1569. private void ClearPriority_Click(object sender, RoutedEventArgs e)
  1570. {
  1571. UpdateFlag(sender, "Priority", false);
  1572. }
  1573. private void EditIssues_Click(object sender, RoutedEventArgs e)
  1574. {
  1575. var updates = new List<ManufacturingPacket>();
  1576. var rows = (sender as MenuItem).Tag as IEnumerable<CoreRow>;
  1577. var pkts = rows.Select(x => x.ToObject<ManufacturingPacket>()).ToArray();
  1578. if (new DynamicIssuesEditor(pkts, true).ShowDialog() == true)
  1579. {
  1580. Progress.ShowModal("Updating Issues", progress => { new Client<ManufacturingPacket>().Save(pkts, "Updated Issues"); });
  1581. Refresh();
  1582. }
  1583. // String[] issues = rows.Select(r => r.Get<ManufacturingPacket, String>(c => c.Issues)).Distinct().ToArray();
  1584. // if (issues.Length > 1)
  1585. // {
  1586. // if (MessageBox.Show(
  1587. // "Multiple Issues found! If you continue, these may be lost.\n\nAre you sure you wish to continue?",
  1588. // "Multiple Issues",
  1589. // MessageBoxButton.YesNo) != MessageBoxResult.Yes)
  1590. // return;
  1591. // }
  1592. //
  1593. // string issue = issues.Length > 0 ? issues.First() : "";
  1594. // if (!TextBoxDialog.Execute("Edit Issues", ref issue))
  1595. // return;
  1596. //
  1597. // foreach (var row in rows)
  1598. // {
  1599. // ManufacturingPacket packet = row.ToObject<ManufacturingPacket>();
  1600. // packet.Issues = issue;
  1601. // updates.Add(packet);
  1602. // }
  1603. // if (updates.Any())
  1604. // {
  1605. // using (new WaitCursor())
  1606. // {
  1607. // new Client<ManufacturingPacket>().Save(updates, "Updated Issues");
  1608. // Refresh();
  1609. // }
  1610. // }
  1611. }
  1612. private void SetHold_Click(object sender, RoutedEventArgs e)
  1613. {
  1614. if (MessageBox.Show(
  1615. "Are you sure you wish to set this packet on hold?",
  1616. "Set Hold",
  1617. MessageBoxButton.YesNo) != MessageBoxResult.Yes)
  1618. return;
  1619. UpdateFlag(sender, "OnHold", true);
  1620. }
  1621. private void ClearHold_Click(object sender, RoutedEventArgs e)
  1622. {
  1623. if (MessageBox.Show(
  1624. "Are you sure you wish to release this packet from hold?",
  1625. "Set Hold",
  1626. MessageBoxButton.YesNo) != MessageBoxResult.Yes)
  1627. return;
  1628. UpdateFlag(sender, "OnHold", false);
  1629. }
  1630. private void SetDistributed_Click(object sender, RoutedEventArgs e)
  1631. {
  1632. UpdateFlag(sender, "Distributed", true);
  1633. }
  1634. private void ClearDistributed_Click(object sender, RoutedEventArgs e)
  1635. {
  1636. UpdateFlag(sender, "Distributed", false);
  1637. }
  1638. private void SetShared_Click(object sender, RoutedEventArgs e)
  1639. {
  1640. var updates = new List<ManufacturingPacketStage>();
  1641. var rows = (sender as MenuItem).Tag as IEnumerable<CoreRow>;
  1642. foreach (var row in rows)
  1643. {
  1644. var stage = row.ToObject<ManufacturingPacketStage>();
  1645. if (stage.Station > 0)
  1646. {
  1647. stage.Station = -1;
  1648. updates.Add(stage);
  1649. }
  1650. }
  1651. if (updates.Any())
  1652. using (new WaitCursor())
  1653. {
  1654. new Client<ManufacturingPacketStage>().Save(updates, "Set Packet as Shared");
  1655. Refresh();
  1656. }
  1657. }
  1658. private void ClearShared_Click(object sender, RoutedEventArgs e)
  1659. {
  1660. var updates = new List<ManufacturingPacketStage>();
  1661. var rows = (sender as MenuItem).Tag as IEnumerable<CoreRow>;
  1662. foreach (var row in rows)
  1663. {
  1664. var stage = row.ToObject<ManufacturingPacketStage>();
  1665. if (stage.Station == -1)
  1666. {
  1667. stage.Station = CurrentStation;
  1668. updates.Add(stage);
  1669. }
  1670. }
  1671. if (updates.Any())
  1672. using (new WaitCursor())
  1673. {
  1674. new Client<ManufacturingPacketStage>().Save(updates, "Cleared Shared flag from Packet");
  1675. Refresh();
  1676. }
  1677. }
  1678. private void MovePacketClick(object sender, RoutedEventArgs e)
  1679. {
  1680. var item = sender as MenuItem;
  1681. var station = (item.Parent as MenuItem).Items.IndexOf(item) + 1;
  1682. var updates = new List<ManufacturingPacketStage>();
  1683. var rows = (sender as MenuItem).Tag as IEnumerable<CoreRow>;
  1684. foreach (var row in rows)
  1685. {
  1686. var stage = row.ToObject<ManufacturingPacketStage>();
  1687. stage.Station = station;
  1688. updates.Add(stage);
  1689. }
  1690. if (updates.Any())
  1691. using (new WaitCursor())
  1692. {
  1693. new Client<ManufacturingPacketStage>().Save(updates, "Moved Packet to " + item.Header);
  1694. Refresh();
  1695. }
  1696. }
  1697. public void PDFEditorSettingsChanged(object sender, string linecolor, int fontsize)
  1698. {
  1699. _settings.LineColor = linecolor;
  1700. _settings.FontSize = fontsize;
  1701. new LocalConfiguration<FactoryFloorLocalSettings>().Save(_settings);
  1702. }
  1703. #region Employee Stuff
  1704. private Dictionary<Guid, string> Employees = new() { { Guid.Empty, "" } };
  1705. private Guid myID = Guid.Empty;
  1706. private string myName = "";
  1707. #endregion
  1708. #region ManufacturingPacket Stuff
  1709. //FactorySetup settings = new GlobalConfiguration<FactorySetup>().Load();
  1710. //private Dictionary<Guid, Tuple<String,int>> Sections = new Dictionary<Guid, Tuple<String,int>>();
  1711. private ManufacturingFactory[] Factories; // new ManufacturingFactory[] { };
  1712. private ManufacturingSection[] Sections; // new ManufacturingSection[] { };
  1713. private ManufacturingTrolley[] Trolleys; // new ManufacturingTrolley[] { };
  1714. private CoreTable TemplateStages;
  1715. //private ManufacturingTemplateStage[] TemplateStages = null;
  1716. private CoreTable Questions;
  1717. //private IList<CoreRow> AllStages = new CoreRow[] { };
  1718. private CoreTable Packets;
  1719. private CoreTable Stages;
  1720. /// <remarks>
  1721. /// <see langword="null"/> if there are no <see cref="ManufacturingSection"/>s in the system.
  1722. /// </remarks>
  1723. private ManufacturingSection? CurrentSection;
  1724. private int CurrentStation;
  1725. private readonly bool PendingVisible = true;
  1726. private ManufacturingLostTime LostTime;
  1727. #endregion
  1728. #region Stuff to Do with Kanbans
  1729. public ObservableCollection<ManufacturingKanban> Kanbans { get; set; }
  1730. private string CurrentKanbanID = "";
  1731. private ManufacturingKanban CurrentKanban
  1732. {
  1733. get { return Kanbans.FirstOrDefault(x => x.ID == CurrentKanbanID); }
  1734. set => CurrentKanbanID = value != null ? value.ID : "";
  1735. }
  1736. private string SearchFilter = "";
  1737. //Border LastCard = null;
  1738. //Border[] CheckedPackets
  1739. //{
  1740. // get {
  1741. // List<Border> packets = new List<Border>();
  1742. // var cards = Kanban.Columns[0].Cards.Where(x => ((ManufacturingKanban)x.Content).Checked == true);
  1743. // foreach (var card in cards)
  1744. // {
  1745. // var prop = card.GetType().GetProperty("TemplateChild", BindingFlags.NonPublic | BindingFlags.Instance);
  1746. // var val = prop.GetValue(card) as DependencyObject;
  1747. // var border = FindVisualChildren<Border>(val).FirstOrDefault();
  1748. // packets.Add(border);
  1749. // }
  1750. // return packets.ToArray();
  1751. // }
  1752. //}
  1753. private void ClearAllSelections()
  1754. {
  1755. foreach (var kanban in Kanbans.Where(x => x.Checked))
  1756. kanban.Checked = false;
  1757. CurrentKanban = null;
  1758. //var cards = Kanban.Columns[0].Cards.Where(x => ((ManufacturingKanban)x.Content).Checked == true).ToArray();
  1759. //foreach (var card in cards)
  1760. // ((ManufacturingKanban)card.Content).Checked = false;
  1761. //CurrentKanban = null;
  1762. UpdateSelectedKanban();
  1763. }
  1764. private ManufacturingKanban GetKanban(Border border)
  1765. {
  1766. return border.Tag as ManufacturingKanban;
  1767. }
  1768. //private Border GetBorder(ManufacturingKanban kanban)
  1769. //{
  1770. // var card = Kanban.Columns[0].Cards.FirstOrDefault(x => ((ManufacturingKanban)x.Content) == kanban);
  1771. // var prop = card.GetType().GetProperty("TemplateChild", BindingFlags.NonPublic | BindingFlags.Instance);
  1772. // var val = prop.GetValue(card) as DependencyObject;
  1773. // return FindVisualChildren<Border>(val).FirstOrDefault();
  1774. //}
  1775. //private void CheckKanban(Border card, bool ischecked)
  1776. //{
  1777. // var chk = card.FindName("IsChecked") as CheckBox;
  1778. // chk.IsChecked = ischecked;
  1779. // card.ApplyTemplate();
  1780. //}
  1781. private void SelectKanban(Border card, bool isselected)
  1782. {
  1783. var img = card.FindName("IsCurrent") as Image;
  1784. img.Source = isselected ? starred : null;
  1785. }
  1786. private ManufacturingPacket KanbanToPacket(ManufacturingKanban kanban)
  1787. {
  1788. if (Packets == null)
  1789. return null;
  1790. var row = Packets.Rows.FirstOrDefault(r => r.Get<ManufacturingPacket, Guid>(c => c.ID).Equals(Guid.Parse(kanban.ID)));
  1791. if (row == null)
  1792. return null;
  1793. return row.ToObject<ManufacturingPacket>();
  1794. }
  1795. #endregion
  1796. #region Shipping Rack Stuff
  1797. private CoreTable Shipments;
  1798. private CoreTable DeliveryItems;
  1799. private readonly ObservableList<DeliveryItem> rackcontents = new();
  1800. private Guid rackid = Guid.Empty;
  1801. private string rackbarcode = "";
  1802. #endregion
  1803. #region Refresh / Reload
  1804. private string GetQualityStatus(QualityStatus status)
  1805. {
  1806. if (status == QualityStatus.Passed)
  1807. return "PASSED";
  1808. if (status == QualityStatus.Skipped)
  1809. return "SKIPPED";
  1810. if (status == QualityStatus.PassedWithIssues)
  1811. return "ISSUES";
  1812. if (status == QualityStatus.Failed)
  1813. return "FAILED";
  1814. return "QA";
  1815. }
  1816. private BitmapImage GetBarCode(CoreRow row)
  1817. {
  1818. var type = row.Get<ManufacturingPacket, BarcodeType>(c => c.BarcodeType);
  1819. if (!row.Get<ManufacturingPacket, DateTime>(c => c.BarcodePrinted).IsEmpty())
  1820. return type == BarcodeType.Grouped ? grouped : barcode;
  1821. if (type == BarcodeType.None)
  1822. return disabled;
  1823. return null;
  1824. }
  1825. private void CreateKanban(CoreRow pktrow, CoreRow stagerow, bool IsChecked)
  1826. {
  1827. var id = pktrow.Get<ManufacturingPacket, Guid>(c => c.ID);
  1828. //var stagerow = Stages.Rows.FirstOrDefault(r=>r.Get<ManufacturingPacketStage,Guid>(c=>c.Parent.ID).Equals(id));
  1829. if (stagerow == null)
  1830. return;
  1831. var station = stagerow.Get<ManufacturingPacketStage, int>(c => c.Station);
  1832. //var stage = stagerow.ToObject<ManufacturingPacketStage>();
  1833. if ((PendingVisible && station.Equals(0)) || station.Equals(-1) || station.Equals(CurrentStation))
  1834. {
  1835. var model = new ManufacturingKanban();
  1836. LoadModel(model, pktrow, stagerow, IsChecked);
  1837. Kanbans.Add(model);
  1838. }
  1839. }
  1840. private void LoadModel(ManufacturingKanban model, CoreRow packet, CoreRow stage, bool IsChecked)
  1841. {
  1842. var station = stage.Get<ManufacturingPacketStage, int>(c => c.Station);
  1843. var Pending = station == 0;
  1844. var quality = stage.Get<ManufacturingPacketStage, QualityStatus>(c => c.QualityStatus);
  1845. var percentage = stage.Get<ManufacturingPacketStage, double>(c => c.PercentageComplete);
  1846. var packetid = packet.Get<ManufacturingPacket, Guid>(c => c.ID);
  1847. var title = packet.Get<ManufacturingPacket, string>(c => c.Title);
  1848. var watermark = packet.Get<ManufacturingPacket, string>(c => c.WaterMark);
  1849. var issues = packet.Get<ManufacturingPacket, string>(c => c.Issues);
  1850. var trolleys = packet.Get<ManufacturingPacket, string>(c => c.Trolleys);
  1851. var serial = packet.Get<ManufacturingPacket, string>(c => c.Serial);
  1852. var quantity = packet.Get<ManufacturingPacket, int>(c => c.Quantity);
  1853. var barcodes = packet.Get<ManufacturingPacket, int>(c => c.BarcodeQty);
  1854. var setoutnumber = packet.Get<ManufacturingPacket, string>(c => c.SetoutLink.Number);
  1855. var jobname = packet.Get<ManufacturingPacket, string>(c => c.SetoutLink.JobLink.Name);
  1856. var duedate = packet.Get<ManufacturingPacket, DateTime>(c => c.DueDate);
  1857. var location = packet.Get<ManufacturingPacket, string>(c => c.Location);
  1858. var setoutlocation = packet.Get<ManufacturingPacket, string>(c => c.SetoutLink.Location);
  1859. var suppliercode = packet.Get<ManufacturingPacket, string>(c => c.OrderItem.PurchaseOrderLink.SupplierLink.Code);
  1860. var ponumber = packet.Get<ManufacturingPacket, string>(c => c.OrderItem.PurchaseOrderLink.PONumber);
  1861. var receiveddate = packet.Get<ManufacturingPacket, DateTime>(c => c.OrderItem.ReceivedDate);
  1862. var receivedreference = packet.Get<ManufacturingPacket, string>(c => c.OrderItem.ReceivedReference);
  1863. var priority = packet.Get<ManufacturingPacket, bool>(c => c.Priority);
  1864. var estimateddate = packet.Get<ManufacturingPacket, DateTime>(c => c.EstimatedDate);
  1865. var distributed = packet.Get<ManufacturingPacket, bool>(c => c.Distributed);
  1866. var packetsection = packet.Get<ManufacturingPacket, string>(c => c.StageLink.Section);
  1867. var groupid = packet.Get<ManufacturingPacket, Guid>(c => c.SetoutLink.Group.ID);
  1868. var groupname = packet.Get<ManufacturingPacket, string>(c => c.SetoutLink.Group.Name);
  1869. model.TemplateID = packet.Get<ManufacturingPacket, Guid>(c => c.ManufacturingTemplateLink.ID);
  1870. model.ID = packetid.ToString();
  1871. model.Title = string.Format(
  1872. "{0}: {1}{2}",
  1873. serial,
  1874. quantity != barcodes ? string.Format("{0} x ", quantity) : "",
  1875. title
  1876. );
  1877. if (!string.IsNullOrWhiteSpace(watermark))
  1878. model.Title = "[" + watermark + "] " + model.Title;
  1879. model.Quantity = barcodes;
  1880. model.JobName = string.Format("{0}: {1}", setoutnumber, jobname);
  1881. model.DueDate = duedate;
  1882. model.GroupID = groupid;
  1883. var descrip = new List<string>
  1884. {
  1885. string.IsNullOrEmpty(location) ? setoutlocation : location
  1886. };
  1887. if (packet.IsEntityLinkValid<ManufacturingPacket, PurchaseOrderItemLink>(x => x.OrderItem))
  1888. descrip.Add(string.Format("{0} ({1}) RCVD {2:dd MMM yy} {3}",
  1889. suppliercode,
  1890. ponumber,
  1891. receiveddate,
  1892. string.IsNullOrWhiteSpace(receivedreference) ? "" : ": " + receivedreference
  1893. ));
  1894. model.Description = string.Join("\n", descrip);
  1895. model.Image = GetBarCode(packet);
  1896. //model.IsCurrent = packet.ID.ToString() == CurrentKanbanID ? starred : null;
  1897. model.IsSelected = packet.Get<ManufacturingPacket, Guid>(c => c.ID).ToString() == CurrentKanbanID;
  1898. model.Tags = priority
  1899. ? new[] { "PRIORITY" }
  1900. : new string[] { };
  1901. model.Category = CurrentSection != null
  1902. ? CurrentSection.ID.ToString()
  1903. : ""; // packet.StageLink.SectionID.ToString();
  1904. model.ColorKey = packet.IsEntityLinkValid<ManufacturingPacket, PurchaseOrderItemLink>(x => x.OrderItem)
  1905. ? TREATED_COLOR
  1906. : priority
  1907. ? PRIORITY_COLOR
  1908. : !Pending
  1909. ? GetColor(duedate.IsEmpty()
  1910. ? DateTime.Today
  1911. : duedate, estimateddate.IsEmpty()
  1912. ? DateTime.Today
  1913. : estimateddate)
  1914. : QA_COLOR;
  1915. model.SelectedColor = packet.Get<ManufacturingPacket, Guid>(c => c.ID).ToString() == CurrentKanbanID
  1916. ? SELECTED_COLOR
  1917. : model.ColorKey;
  1918. model.SharedColor = station.Equals(-1)
  1919. ? SHARED_COLOR
  1920. : model.ColorKey;
  1921. model.Checked = IsChecked;
  1922. model.SetoutID = packet.Get<ManufacturingPacket, Guid>(c => c.SetoutLink.ID);
  1923. model.Assignee = Pending
  1924. ? "Not Yet Started"
  1925. : "Current Workload";
  1926. model.Status = !Entity.IsEntityLinkValid<ManufacturingPacket, ManufacturingPacketStageLink>(x => x.StageLink, packet)
  1927. ? " "
  1928. : Pending
  1929. ? "PENDING"
  1930. : string.Format("{0:F0}%", percentage);
  1931. try
  1932. {
  1933. model.Flags = distributed
  1934. ? !packet.Get<ManufacturingPacket, Guid>(c => c.StageLink.SectionID).Equals(CurrentSection.ID)
  1935. ? string.IsNullOrEmpty(packetsection)
  1936. ? ""
  1937. : packetsection.ToUpper().Trim()
  1938. : "DISTRIB"
  1939. : "";
  1940. }
  1941. catch (Exception e)
  1942. {
  1943. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  1944. }
  1945. model.Issues = issues;
  1946. model.IssuesImage = string.IsNullOrWhiteSpace(issues)
  1947. ? null
  1948. : speechbubble;
  1949. model.Trolleys = trolleys;
  1950. }
  1951. private string GetColor(DateTime duedate, DateTime estdate)
  1952. {
  1953. var color = NOTYETDUE_COLOR;
  1954. if (duedate < estdate)
  1955. color = OVERDUE_COLOR;
  1956. else if (duedate < estdate.AddDays(7))
  1957. color = NEARLYDUE_COLOR;
  1958. return color;
  1959. }
  1960. private void ReloadPackets(bool reloaddata)
  1961. {
  1962. using var profiler = new Profiler(true);
  1963. using (new WaitCursor())
  1964. {
  1965. if (reloaddata)
  1966. {
  1967. var sectionid = CurrentSection != null ? CurrentSection.ID : CoreUtils.FullGuid;
  1968. var stageflt = new Filter<ManufacturingPacketStage>(x => x.Completed).IsEqualTo(DateTime.MinValue)
  1969. .Or(x => x.ManufacturingSectionLink.ID).IsEqualTo(CurrentSection.ID);
  1970. stageflt.Ands.Add(
  1971. new Filter<ManufacturingPacketStage>(x => x.Parent.StageLink.SectionID).IsEqualTo(sectionid)
  1972. .Or(x => x.Parent.Distributed).IsEqualTo(true)
  1973. );
  1974. var stageQuery = new KeyedQueryDef<ManufacturingPacketStage>(
  1975. stageflt,
  1976. new Columns<ManufacturingPacketStage>(x => x.ID)
  1977. .Add(x => x.Parent.ID)
  1978. .Add(x => x.Station)
  1979. .Add(x => x.QualityStatus)
  1980. .Add(x => x.PercentageComplete)
  1981. .Add(x => x.Time)
  1982. .Add(x => x.Started)
  1983. .Add(x => x.FormData)
  1984. .Add(x => x.Completed)
  1985. .Add(x => x.FormCompleted)
  1986. .Add(x => x.FormCompletedBy.ID)
  1987. .Add(x => x.Sequence)
  1988. .Add(x => x.QualityNotes)
  1989. .Add(x => x.SectionID)
  1990. .Add(x => x.ManufacturingSectionLink.ID));
  1991. var pktfilter = new Filter<ManufacturingPacket>(x => x.Completed).IsEqualTo(DateTime.MinValue)
  1992. .And(x => x.Archived).IsEqualTo(DateTime.MinValue)
  1993. .And(x => x.OnHold).IsEqualTo(false)
  1994. .And(new Filter<ManufacturingPacket>(x => x.OrderItem).NotLinkValid().Or(x => x.OrderItem.ReceivedDate)
  1995. .IsNotEqualTo(DateTime.MinValue))
  1996. .And(new Filter<ManufacturingPacket>(x => x.StageLink.SectionID).IsEqualTo(sectionid).Or(x => x.Distributed).IsEqualTo(true));
  1997. if (!string.IsNullOrWhiteSpace(SearchFilter))
  1998. pktfilter = pktfilter.TextSearch(
  1999. SearchFilter,
  2000. x => x.SetoutLink.JobLink.JobNumber,
  2001. x => x.SetoutLink.JobLink.Name,
  2002. x => x.SetoutLink.Number,
  2003. x => x.SetoutLink.Location,
  2004. //x => x.SetoutLink.Reference,
  2005. x => x.Title,
  2006. x => x.Serial,
  2007. x => x.Trolleys,
  2008. x => x.Location
  2009. );
  2010. var pktcolumns = new Columns<ManufacturingPacket>(x => x.ID)
  2011. .Add(x => x.Serial)
  2012. .Add(x => x.Title)
  2013. .Add(x => x.Quantity)
  2014. .Add(x => x.BarcodeQty)
  2015. .Add(x => x.SetoutLink.ID)
  2016. .Add(x => x.SetoutLink.Number)
  2017. .Add(x => x.SetoutLink.JobLink.ID)
  2018. .Add(x => x.SetoutLink.JobLink.JobNumber)
  2019. .Add(x => x.SetoutLink.JobLink.Name)
  2020. .Add(x => x.SetoutLink.Group.ID)
  2021. .Add(x => x.SetoutLink.Group.Name)
  2022. .Add(x => x.SetoutLink.Group.Job.JobNumber)
  2023. .Add(x => x.SetoutLink.Group.OptimizationDocument.ID)
  2024. .Add(x => x.DueDate)
  2025. .Add(x => x.SetoutLink.Location)
  2026. //.Add(x => x.SetoutLink.Reference)
  2027. .Add(x => x.Priority)
  2028. .Add(x => x.EstimatedDate)
  2029. .Add(x => x.Distributed)
  2030. .Add(x => x.StageLink.ID)
  2031. .Add(x => x.StageLink.SectionID)
  2032. .Add(x => x.StageLink.Section)
  2033. .Add(x => x.StageLink.Deleted)
  2034. .Add(x => x.BarcodePrinted)
  2035. .Add(x => x.BarcodeType)
  2036. .Add(x => x.ManufacturingTemplateLink.ID)
  2037. .Add(x => x.ManufacturingTemplateLink.Name)
  2038. .Add(x => x.ManufacturingTemplateLink.Code)
  2039. //.Add(x => x.CustomAttributes)
  2040. .Add(x => x.Trolleys)
  2041. .Add(x => x.Location)
  2042. .Add(x => x.Group)
  2043. .Add(x => x.Height)
  2044. .Add(x => x.Width)
  2045. .Add(x => x.Length)
  2046. .Add(x => x.OrderItem.ID)
  2047. .Add(x => x.OrderItem.Deleted)
  2048. .Add(x => x.OrderItem.PurchaseOrderLink.SupplierLink.Code)
  2049. .Add(x => x.OrderItem.PurchaseOrderLink.PONumber)
  2050. .Add(x => x.OrderItem.Consignment.EstimatedWarehouseArrival)
  2051. .Add(x => x.OrderItem.ReceivedReference)
  2052. //.Add(x => x.Zone.Code)
  2053. //.Add(x => x.Level.Code)
  2054. .Add(x => x.OrderItem.ReceivedDate)
  2055. .Add(x => x.WaterMark)
  2056. .Add(x => x.Issues)
  2057. .Add(x => x.OnHold)
  2058. .Add(DatabaseSchema.Properties(typeof(ManufacturingPacket))
  2059. .Where(x => x is CustomProperty)
  2060. .Select(x => x.Name).ToArray()
  2061. );
  2062. var pktQuery = new KeyedQueryDef<ManufacturingPacket>(
  2063. pktfilter,
  2064. pktcolumns,
  2065. new SortOrder<ManufacturingPacket>(x => x.Priority, SortDirection.Descending)
  2066. .ThenBy(x => x.SetoutLink.Number));
  2067. var results = Client.QueryMultiple(
  2068. stageQuery,
  2069. pktQuery,
  2070. new KeyedQueryDef<DeliveryItem>(
  2071. new Filter<DeliveryItem>(x => x.DeliveredDate).IsEqualTo(DateTime.MinValue)
  2072. .And(x => x.ManufacturingPacketLink).LinkValid(),
  2073. new Columns<DeliveryItem>(
  2074. x => x.ID,
  2075. x => x.Barcode,
  2076. x => x.ManufacturingPacketLink.ID,
  2077. x => x.ManufacturingPacketLink.Serial,
  2078. x => x.Description,
  2079. x => x.ShipmentLink.ID)));
  2080. Stages = results.Get<ManufacturingPacketStage>();
  2081. Packets = results.Get<ManufacturingPacket>();
  2082. DeliveryItems = results.Get<DeliveryItem>();
  2083. }
  2084. var checks = Kanbans.Where(x => x.Checked).Select(x => x.ID).ToArray();
  2085. Kanbans.Clear();
  2086. var stages = Stages.Rows
  2087. .Select(x => new Tuple<Guid, Guid>(
  2088. x.Get<ManufacturingPacketStage, Guid>(x => x.Parent.ID),
  2089. x.Get<ManufacturingPacketStage, Guid>(x => x.ManufacturingSectionLink.ID)
  2090. )).ToList();
  2091. foreach (var pktrow in Packets.Rows)
  2092. {
  2093. var id = pktrow.Get<ManufacturingPacket, Guid>(c => c.ID);
  2094. var distributed = pktrow.Get<ManufacturingPacket, bool>(c => c.Distributed);
  2095. var stageIndex = stages.FindIndex(x => x.Item1 == id && x.Item2 == _settings.Section);
  2096. var stageRow = stageIndex >= 0 ? Stages.Rows[stageIndex] : null;
  2097. //this was commented out previously - leading to the distributed packet issue. Uncommented and tested to work by Nick. Was there a reason for commenting this out?
  2098. bool bOK = true;
  2099. if (distributed)
  2100. bOK = stageRow?.Get<ManufacturingPacketStage, DateTime>(c => c.Completed).IsEmpty() == true;
  2101. if (bOK)
  2102. {
  2103. CreateKanban(pktrow, stageRow!, checks.Contains(id.ToString()));
  2104. }
  2105. }
  2106. var sorted = Kanbans.OrderBy(x => x.Assignee).ThenByDescending(x => x.Tags.Length).ThenBy(x => x.DueDate).ThenBy(x => x.JobName);
  2107. if (CurrentKanban != null && !Kanbans.Contains(CurrentKanban))
  2108. CurrentKanban = sorted.FirstOrDefault();
  2109. Kanban.ItemsSource = null;
  2110. Kanban.ItemsSource =
  2111. sorted; //Kanbans.OrderBy(x => x.Assignee).ThenByDescending(x => x.Tags.Length).ThenBy(x => x.DueDate).ThenBy(x => x.JobName);
  2112. UpdateSelectedKanban();
  2113. }
  2114. }
  2115. private void DoRefresh(bool reloaddata)
  2116. {
  2117. if (!IsReady || Sections == null || !Sections.Any())
  2118. return;
  2119. ReloadPackets(reloaddata);
  2120. //LoadKanban();
  2121. }
  2122. public void Refresh()
  2123. {
  2124. DoRefresh(true);
  2125. }
  2126. #endregion
  2127. #region QAChecks
  2128. private IEnumerable<QAQuestion> LoadQAQuestions(ManufacturingPacket packet, bool section, bool template)
  2129. {
  2130. if (Questions == null)
  2131. Questions = new Client<QAQuestion>().Query();
  2132. if (TemplateStages == null)
  2133. TemplateStages = new Client<ManufacturingTemplateStage>().Query();
  2134. var tstage = TemplateStages.Rows.FirstOrDefault(r =>
  2135. r.Get<ManufacturingTemplateStage, Guid>(c => c.Template.ID).Equals(packet.ManufacturingTemplateLink.ID) &&
  2136. r.Get<ManufacturingTemplateStage, Guid>(c => c.Section.ID).Equals(CurrentSection.ID));
  2137. if (tstage == null)
  2138. return null;
  2139. IEnumerable<CoreRow> rows = null;
  2140. if (section && !template)
  2141. rows = Questions.Rows.Where(r => r.Get<QAQuestion, Guid>(c => c.QAForm.ID).Equals(CurrentSection.QAForm.ID));
  2142. if (!section && template)
  2143. rows = Questions.Rows.Where(r =>
  2144. r.Get<QAQuestion, Guid>(c => c.QAForm.ID).Equals(tstage.Get<ManufacturingTemplateStage, Guid>(x => x.QAForm.ID)));
  2145. if (section && template)
  2146. rows = Questions.Rows.Where(r =>
  2147. r.Get<QAQuestion, Guid>(c => c.QAForm.ID).Equals(CurrentSection.QAForm.ID) || r.Get<QAQuestion, Guid>(c => c.QAForm.ID)
  2148. .Equals(tstage.Get<ManufacturingTemplateStage, Guid>(x => x.QAForm.ID)));
  2149. var result = rows.Where(r => r.Get<QAQuestion, bool>(c => c.QAForm.Active).Equals(true)).Select(r => r.ToObject<QAQuestion>());
  2150. return result;
  2151. }
  2152. private void ViewQualityChecks(object sender, RoutedEventArgs e)
  2153. {
  2154. SetCurrentButton(sender as Button);
  2155. LoadDrawing(Guid.Empty);
  2156. }
  2157. private void QAGridChanged(object sender, Dictionary<Guid, object> values)
  2158. {
  2159. SaveQAData(values);
  2160. }
  2161. private void SaveQAData(Dictionary<Guid, object> values)
  2162. {
  2163. var updates = new List<ManufacturingPacketStage>();
  2164. var cks = Kanbans.Where(x => x.Checked);
  2165. foreach (var ck in cks)
  2166. {
  2167. //var row = Packets.Rows.FirstOrDefault(r => r.Get<ManufacturingPacket, Guid>(c => c.ID).Equals(ck.ID));
  2168. var stagerow = Stages.Rows.FirstOrDefault(r => r.Get<ManufacturingPacketStage, Guid>(c => c.Parent.ID).Equals(Guid.Parse(ck.ID))
  2169. && r.Get<ManufacturingPacketStage, Guid>(c => c.ManufacturingSectionLink.ID)
  2170. .Equals(_settings.Section));
  2171. if (stagerow != null)
  2172. {
  2173. var stage = stagerow.ToObject<ManufacturingPacketStage>();
  2174. stage.Form.ID = CurrentSection.QAForm.ID;
  2175. stage.FormData = Serialization.Serialize(values);
  2176. stagerow.Set<ManufacturingPacketStage, string>(x => x.FormData, stage.FormData);
  2177. updates.Add(stage);
  2178. }
  2179. }
  2180. if (updates.Any())
  2181. Task.Run(() => { new Client<ManufacturingPacketStage>().Save(updates, "", (o, e) => { }); });
  2182. }
  2183. private void UpdateQuality(QualityStatus status, string note = null)
  2184. {
  2185. var selected = new List<ManufacturingPacket>();
  2186. var stages = new List<ManufacturingPacketStage>();
  2187. foreach (var kanban in Kanbans.Where(x => x.Checked || x.IsSelected))
  2188. {
  2189. selected.Add(KanbanToPacket(kanban));
  2190. var pktid = Guid.Parse(kanban.ID);
  2191. var stagerows = Stages.Rows.Where(r =>
  2192. r.Get<ManufacturingPacketStage, Guid>(c => c.SectionID).Equals(CurrentSection.ID) &&
  2193. r.Get<ManufacturingPacketStage, Guid>(c => c.Parent.ID).Equals(pktid));
  2194. stages.AddRange(stagerows.Select(r => r.ToObject<ManufacturingPacketStage>()));
  2195. }
  2196. if (note == null)
  2197. {
  2198. var form = new NotesForm(Employees) { Caption = "Please detail the quality issues identified with these item(s)" };
  2199. if (form.ShowDialog() != true) return;
  2200. note = form.Text;
  2201. if (form.EmployeeID != Guid.Empty)
  2202. {
  2203. var task = new Kanban();
  2204. task.DueDate = DateTime.Today;
  2205. task.Status = KanbanStatus.Open;
  2206. task.EmployeeLink.ID = form.EmployeeID;
  2207. task.ManagerLink.ID = myID;
  2208. task.Title = "QA Issues : " + CurrentSection.Factory.Name + ": " + CurrentSection.Name;
  2209. //task.JobLink.ID = packet.JobLink.ID;
  2210. var details = new List<string>();
  2211. details.Add(form.Text);
  2212. details.Add("");
  2213. details.Add("The following packets are affected by this issue:");
  2214. foreach (var sel in selected)
  2215. details.Add(string.Format("- {0}: {1} ({2})", sel.SetoutLink.Number, sel.Title,
  2216. string.IsNullOrEmpty(sel.Location) ? sel.SetoutLink.Location : sel.Location));
  2217. task.Notes = new[] { string.Join("\n", details) };
  2218. new Client<Kanban>().Save(task, "Created task from Factory Floor");
  2219. note = note + "\n" + "** Task Created for " + task.EmployeeLink.Name;
  2220. }
  2221. }
  2222. foreach (var stage in stages)
  2223. {
  2224. stage.Station = 0;
  2225. stage.QualityStatus = status;
  2226. if (!string.IsNullOrWhiteSpace(note))
  2227. {
  2228. if (!string.IsNullOrWhiteSpace(stage.QualityNotes))
  2229. stage.QualityNotes = string.Format("{0}\n\n{1}", stage.QualityNotes, note);
  2230. else
  2231. stage.QualityNotes = note;
  2232. }
  2233. }
  2234. Progress.Show("");
  2235. new Client<ManufacturingPacketStage>().Save(stages, note);
  2236. DoRefresh(true);
  2237. Progress.Close();
  2238. }
  2239. #endregion
  2240. private void RequestMaterials_Click(object sender, RoutedEventArgs e)
  2241. {
  2242. var updates = new List<ManufacturingPacket>();
  2243. var rows = (sender as MenuItem)!.Tag as IEnumerable<CoreRow>;
  2244. ManufacturingPanelColumn.CreatePickingList(rows!.Select(x => x.ToObject<ManufacturingPacket>()).ToList(), true,
  2245. () => new GlobalConfiguration<ManufacturingPanelProperties>().Load());
  2246. }
  2247. private void _selectPackArea_OnClick(object sender, RoutedEventArgs e)
  2248. {
  2249. var dlg = new MultiSelectDialog<StockArea>(
  2250. new Filter<StockArea>(x => x.Active).IsEqualTo(true),
  2251. new Columns<StockArea>(x => x.ID).Add(x => x.Warehouse.Code).Add(x => x.Code).Add(x => x.Description),
  2252. false);
  2253. if (dlg.ShowDialog("Select Area"))
  2254. {
  2255. _settings.AreaID = dlg.IDs().First();
  2256. var area = dlg.Items().First();
  2257. new LocalConfiguration<FactoryFloorLocalSettings>().Save(_settings);
  2258. _areaDescription.Text = $"{area.Code}";
  2259. _packGrid.Area = area;
  2260. _packGrid.Refresh(false,true);
  2261. }
  2262. }
  2263. private void _addPack_OnClick(object sender, RoutedEventArgs e)
  2264. {
  2265. var dlg = new MultiSelectDialog<StockLocation>(
  2266. new Filter<StockLocation>(x => x.Area.ID).IsNotEqualTo(_settings.AreaID),
  2267. new Columns<StockLocation>(x => x.ID).Add(x => x.Warehouse.Code).Add(x => x.Area.Code).Add(x => x.Code).Add(x => x.Description),
  2268. false);
  2269. if (dlg.ShowDialog("Select Location"))
  2270. {
  2271. var location = dlg.Items().FirstOrDefault();
  2272. if (location != null)
  2273. {
  2274. location.Area.ID = _settings.AreaID;
  2275. new Client<StockLocation>().Save(location,$"Moved To Manufacturing ({_packGrid.Area?.Code})");
  2276. _packGrid.Refresh(false,true);
  2277. }
  2278. }
  2279. }
  2280. private string _packFilter = "";
  2281. private void _packSearch_OnTextChanged(object sender, TextChangedEventArgs e)
  2282. {
  2283. _packGrid.Refresh(false, false);
  2284. }
  2285. private bool _packGrid_OnOnFilterRecord(CoreRow row)
  2286. {
  2287. var result = true;
  2288. if (_packLinked.IsChecked == true)
  2289. {
  2290. Guid jobid = row.Get<StockHolding, Guid>(x => x.Job.ID);
  2291. if (_packGrid.CurrentPacket != null)
  2292. result = jobid == Guid.Empty || jobid == _packGrid.CurrentPacket.SetoutLink.JobLink.ID;
  2293. }
  2294. result = result && (String.IsNullOrWhiteSpace(_packSearch.Text)
  2295. || row.Get<StockHolding, String>(x => x.Product.Code).ToUpper().Contains(_packSearch.Text.ToUpper())
  2296. || row.Get<StockHolding, String>(x => x.Product.Name).ToUpper().Contains(_packSearch.Text.ToUpper())
  2297. || row.Get<StockHolding, String>(x => x.Location.Code).ToUpper().Contains(_packSearch.Text.ToUpper())
  2298. || row.Get<StockHolding, String>(x => x.Style.Code).ToUpper().Contains(_packSearch.Text.ToUpper())
  2299. || row.Get<StockHolding, String>(x => x.Style.Description).ToUpper()
  2300. .Contains(_packSearch.Text.ToUpper())
  2301. || row.Get<StockHolding, String>(x => x.Dimensions.UnitSize).ToUpper()
  2302. .Contains(_packSearch.Text.ToUpper())
  2303. || row.Get<StockHolding, String>(x => x.Job.JobNumber).ToUpper().Contains(_packSearch.Text.ToUpper())
  2304. || row.Get<StockHolding, String>(x => x.Job.Name).ToUpper().Contains(_packSearch.Text.ToUpper()));
  2305. return result;
  2306. }
  2307. private void _packLinked_OnChecked(object sender, RoutedEventArgs e)
  2308. {
  2309. _packGrid?.Refresh(false, false);
  2310. }
  2311. private void _returnPack_OnClick(object sender, RoutedEventArgs e)
  2312. {
  2313. ContextMenu _menu = new ContextMenu();
  2314. var dict = _packGrid.Data
  2315. .ToDictionary<StockHolding, Guid, String>(
  2316. x => x.Location.ID,
  2317. (row) =>
  2318. $"{row.Get<StockHolding, String>(c => c.Location.Code)}: {row.Get<StockHolding, String>(c => c.Location.Description)}"
  2319. );
  2320. if (!dict.Any())
  2321. return;
  2322. foreach (var key in dict.Keys)
  2323. {
  2324. MenuItem item = new MenuItem() { Header = dict[key], DataContext = key };
  2325. item.Click += (o, args) =>
  2326. {
  2327. var dlg = new MultiSelectDialog<StockArea>(
  2328. new Filter<StockArea>(x => x.Active).IsEqualTo(true).And(x => x.ID).IsNotEqualTo(_settings.AreaID),
  2329. new Columns<StockArea>(x => x.ID).Add(x => x.Warehouse.Code).Add(x => x.Code)
  2330. .Add(x => x.Description),
  2331. false);
  2332. if (dlg.ShowDialog("Select Area"))
  2333. {
  2334. var location = new StockLocation() { ID = key };
  2335. location.CommitChanges();
  2336. location.Area.ID = dlg.IDs().First();
  2337. new Client<StockLocation>().Save(location,
  2338. $"Returned From Manufacturing ({_packGrid.Area?.Code})");
  2339. _packGrid.Refresh(false, true);
  2340. }
  2341. };
  2342. _menu.Items.Add(item);
  2343. }
  2344. _menu.IsOpen = true;
  2345. }
  2346. private void _replaceStock_OnClick(object sender, RoutedEventArgs e)
  2347. {
  2348. _packGrid.ReplaceStock();
  2349. }
  2350. private void _packGrid_OnOnSelectItem(object sender, DynamicGridSelectionEventArgs e)
  2351. {
  2352. _replaceStock.IsEnabled = e.Rows?.Any() == true;
  2353. }
  2354. }
  2355. }