FactoryPanel.xaml.cs 121 KB

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