FactoryFloorAnalysis.xaml.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Diagnostics;
  5. using System.Linq;
  6. using System.Text.RegularExpressions;
  7. using System.Windows;
  8. using System.Windows.Controls;
  9. using System.Windows.Data;
  10. using System.Windows.Input;
  11. using Comal.Classes;
  12. using InABox.Clients;
  13. using InABox.Core;
  14. using InABox.WPF;
  15. using PRSDesktop.WidgetGroups;
  16. using Syncfusion.UI.Xaml.Grid;
  17. using Syncfusion.UI.Xaml.Grid.Cells;
  18. using Syncfusion.UI.Xaml.Grid.Converter;
  19. using Syncfusion.XlsIO;
  20. using DataRow = System.Data.DataRow;
  21. using SelectionChangedEventArgs = System.Windows.Controls.SelectionChangedEventArgs;
  22. namespace PRSDesktop
  23. {
  24. public class FactoryFloorAnalysisDashboardProperties : IDashboardProperties { }
  25. public class FactoryFloorAnalysisDashboardElement : DashboardElement<FactoryFloorAnalysis, Manufacturing, FactoryFloorAnalysisDashboardProperties> { }
  26. /// <summary>
  27. /// Interaction logic for FactoryFloorAnalysis.xaml
  28. /// </summary>
  29. public partial class FactoryFloorAnalysis : UserControl, IPanel<ManufacturingPacket>, IDashboardWidget<Manufacturing, FactoryFloorAnalysisDashboardProperties>
  30. {
  31. private bool _changing;
  32. private DateTime _from;
  33. private string _search = "";
  34. private DateTime _to;
  35. private readonly Dictionary<string, string> SectionDisplayNames = new() { { "Total", "Total" } };
  36. private CoreTable sections;
  37. private CoreTable templatestages;
  38. public FactoryFloorAnalysis()
  39. {
  40. _from = DateTime.Today.AddDays(0 - WeekDay(DateTime.Today));
  41. _to = DateTime.Today;
  42. InitializeComponent();
  43. dataGrid.CellRenderers.Remove("StackedHeader");
  44. dataGrid.CellRenderers.Add("StackedHeader", new GridCustomStackedRenderer(Resources));
  45. }
  46. public event DataModelUpdateEvent OnUpdateDataModel;
  47. public bool IsReady { get; set; }
  48. public void CreateToolbarButtons(IPanelHost host)
  49. {
  50. }
  51. public void Setup()
  52. {
  53. FromDate.SelectedDate = _from;
  54. ToDate.SelectedDate = _to;
  55. var employees = new Dictionary<Guid, string> { { Guid.Empty, "All Employees" } };
  56. var emps = new Client<Employee>().Query(
  57. LookupFactory.DefineFilter<Employee>(),
  58. LookupFactory.DefineColumns<Employee>(),
  59. LookupFactory.DefineSort<Employee>()
  60. );
  61. foreach (var row in emps.Rows)
  62. //if (row.Get<Employee, String>(x => x.Group.Description).Equals("FACTORY"))
  63. employees[row.Get<Employee, Guid>(x => x.ID)] = row.Get<Employee, string>(x => x.Name);
  64. Employees.ItemsSource = employees;
  65. var joblist = new Dictionary<Guid, string> { { Guid.Empty, "All Jobs" } };
  66. var jobs = new Client<Job>().Query(
  67. LookupFactory.DefineFilter<Job>(),
  68. LookupFactory.DefineColumns<Job>(),
  69. LookupFactory.DefineSort<Job>()
  70. );
  71. foreach (var row in jobs.Rows)
  72. //if (row.Get<Employee, String>(x => x.Group.Description).Equals("FACTORY"))
  73. joblist[row.Get<Job, Guid>(x => x.ID)] =
  74. string.Format("{0} - {1}", row.Get<Job, string>(x => x.JobNumber), row.Get<Job, string>(x => x.Name));
  75. Jobs.ItemsSource = joblist;
  76. sections = new Client<ManufacturingSection>().Query(
  77. new Filter<ManufacturingSection>(x => x.Hidden).IsEqualTo(false),
  78. null,
  79. new SortOrder<ManufacturingSection>(x => x.Factory.Sequence).ThenBy(x => x.Sequence));
  80. var templates = new Dictionary<Guid, string> { { Guid.Empty, "All Templates" } };
  81. templatestages = new Client<ManufacturingTemplateStage>().Query();
  82. foreach (var row in templatestages.Rows)
  83. templates[row.Get<ManufacturingTemplateStage, Guid>(x => x.Template.ID)] = string.Format("{0} - {1}",
  84. row.Get<ManufacturingTemplateStage, string>(x => x.Template.Code),
  85. row.Get<ManufacturingTemplateStage, string>(x => x.Template.Name));
  86. Templates.ItemsSource = templates;
  87. dataGrid.ScrollMode = ScrollMode.Async;
  88. var columns = new Dictionary<string, List<string>>();
  89. var factories = new Dictionary<Guid, string> { { Guid.Empty, "All Factories" } };
  90. foreach (var row in sections.Rows)
  91. {
  92. var factoryid = row.Get<ManufacturingSection, Guid>(x => x.Factory.ID);
  93. var factoryname = row.Get<ManufacturingSection, string>(x => x.Factory.Name);
  94. factories[factoryid] = factoryname;
  95. if (!columns.ContainsKey(factoryname))
  96. columns[factoryname] = new List<string>();
  97. }
  98. Factories.ItemsSource = factories;
  99. ReloadHeaders(columns);
  100. }
  101. public void Shutdown()
  102. {
  103. }
  104. public void Refresh()
  105. {
  106. var data = new DataTable();
  107. data.Columns.Add("Template", typeof(string));
  108. data.Columns.Add("Job", typeof(string));
  109. data.Columns.Add("Setout", typeof(string));
  110. data.Columns.Add("Serial", typeof(string));
  111. data.Columns.Add("Description", typeof(string));
  112. data.Columns.Add("Qty", typeof(int));
  113. var columns = new Dictionary<string, List<string>>();
  114. foreach (var row in sections.Rows)
  115. if (Factories.SelectedValue.Equals(Guid.Empty) ||
  116. row.Get<ManufacturingSection, Guid>(x => x.Factory.ID).Equals(Factories.SelectedValue))
  117. {
  118. var factory = row.Get<ManufacturingSection, string>(x => x.Factory.Name);
  119. if (!columns.ContainsKey(factory))
  120. columns[factory] = new List<string>();
  121. CreateColumn(data, columns, row, "Est");
  122. CreateColumn(data, columns, row, "Act");
  123. CreateColumn(data, columns, row, "Var");
  124. }
  125. ReloadHeaders(columns);
  126. //dataGrid.CoveredCells.Clear();
  127. dataGrid.ItemsSource = data;
  128. Progress.Show("Retrieving Completed Work (0%) ...");
  129. data.Rows.Clear();
  130. var empid = Employees.SelectedValue != null ? (Guid)Employees.SelectedValue : Guid.Empty;
  131. var jobid = Jobs.SelectedValue != null ? (Guid)Jobs.SelectedValue : Guid.Empty;
  132. var stgfilter = new Filter<ManufacturingPacketStage>(x => x.Completed).IsGreaterThanOrEqualTo(_from).And(x => x.Completed)
  133. .IsLessThan(_to.AddDays(1));
  134. if (jobid != Guid.Empty)
  135. stgfilter = stgfilter.And(x => x.Parent.SetoutLink.JobLink.ID).IsEqualTo(jobid);
  136. var completedstages = new Client<ManufacturingPacketStage>().Query(stgfilter,
  137. new Columns<ManufacturingPacketStage>(
  138. x => x.Parent.ID,
  139. x => x.Parent.ManufacturingTemplateLink.ID,
  140. x => x.Parent.ManufacturingTemplateLink.Code,
  141. x => x.Parent.SetoutLink.JobLink.JobNumber,
  142. x => x.Parent.SetoutLink.Number,
  143. x => x.Parent.Serial,
  144. x => x.Parent.Title,
  145. x => x.Parent.Quantity
  146. )
  147. );
  148. var pktids = new List<Guid> { Guid.Empty };
  149. foreach (var stagerow in completedstages.Rows)
  150. {
  151. var id = stagerow.Get<ManufacturingPacketStage, Guid>(c => c.Parent.ID);
  152. if (!pktids.Contains(id))
  153. pktids.Add(id);
  154. }
  155. Progress.SetMessage("Retrieving History (10%) ...");
  156. var filter = new Filter<ManufacturingHistory>(x => x.Employee).LinkValid(empid);
  157. if (jobid != Guid.Empty)
  158. filter = filter.And(x => x.Packet.SetoutLink.JobLink.ID).IsEqualTo(jobid);
  159. filter = filter.And(x => x.Packet.ID).InList(pktids.ToArray());
  160. var history = new Client<ManufacturingHistory>().Query(
  161. filter,
  162. new Columns<ManufacturingHistory>(
  163. x => x.Packet.ID,
  164. x => x.Section.ID,
  165. x => x.WorkDuration,
  166. x => x.QADuration
  167. )
  168. );
  169. var totals = new Dictionary<string, double>();
  170. var qtytotal = 0;
  171. for (var i = 0; i < pktids.Count; i++)
  172. {
  173. var bHasData = false;
  174. Progress.SetMessage(string.Format("Calculating ({0:F2}%) ...", 20.0F + i * 80.0F / (double)pktids.Count));
  175. //var packet = packets.Rows[i];
  176. var pktid = pktids[i];
  177. if (pktid != Guid.Empty)
  178. {
  179. var row = data.NewRow();
  180. // Get the First completed stage, so that we can extract the info from the packetlink
  181. var srow = completedstages.Rows.FirstOrDefault(r => r.Get<ManufacturingPacketStage, Guid>(x => x.Parent.ID).Equals(pktid));
  182. var stage = srow.ToObject<ManufacturingPacketStage>();
  183. row["Template"] = stage.Parent.ManufacturingTemplateLink.Code;
  184. row["Job"] = stage.Parent.SetoutLink.JobLink.JobNumber;
  185. row["Setout"] = stage.Parent.SetoutLink.Number;
  186. row["Serial"] = stage.Parent.Serial;
  187. row["Description"] = stage.Parent.Title;
  188. row["Qty"] = stage.Parent.Quantity;
  189. var pktstages = templatestages.Rows.Where(r =>
  190. r.Get<ManufacturingTemplateStage, Guid>(c => c.Template.ID).Equals(stage.Parent.ManufacturingTemplateLink.ID));
  191. foreach (var stagerow in pktstages)
  192. {
  193. var sectionid = stagerow.Get<ManufacturingTemplateStage, Guid>(c => c.Section.ID);
  194. var section = sections.Rows.FirstOrDefault(r => r.Get<ManufacturingSection, Guid>(c => c.ID).Equals(sectionid));
  195. var prefix = string.Format("{0}:{1}:", section.Get<ManufacturingSection, string>(x => x.Factory.Name),
  196. Regex.Replace(section.Get<ManufacturingSection, string>(x => x.Name), "[^a-zA-Z0-9]", string.Empty));
  197. var estimated = stagerow.Get<ManufacturingTemplateStage, TimeSpan>(x => x.Time).TotalHours * stage.Parent.Quantity;
  198. var histrecords = history.Rows.Where(r =>
  199. r.Get<ManufacturingHistory, Guid>(c => c.Packet.ID).Equals(stage.Parent.ID) &&
  200. r.Get<ManufacturingHistory, Guid>(c => c.Section.ID).Equals(sectionid));
  201. var actual = new TimeSpan(histrecords.Sum(r =>
  202. r.Get<ManufacturingHistory, TimeSpan>(c => c.WorkDuration).Ticks +
  203. r.Get<ManufacturingHistory, TimeSpan>(c => c.QADuration).Ticks)).TotalHours;
  204. if (actual > 0.0F)
  205. {
  206. if (data.Columns.Contains(prefix + "Est"))
  207. {
  208. UpdateColumn(totals, row, prefix + "Est", estimated);
  209. UpdateColumn(totals, row, prefix + "Act", actual);
  210. UpdateColumn(totals, row, prefix + "Var", actual - estimated);
  211. }
  212. bHasData = true;
  213. }
  214. }
  215. if (bHasData)
  216. {
  217. qtytotal += (int)row["Qty"];
  218. data.Rows.Add(row);
  219. }
  220. }
  221. }
  222. var total = data.NewRow();
  223. total["Template"] = "Totals";
  224. total["qty"] = qtytotal;
  225. foreach (var key in totals.Keys)
  226. total[key] = totals[key];
  227. data.Rows.Add(total);
  228. //dataGrid.CoveredCells.Add(new CoveredCellInfo(1, 5, data.Rows.Count, data.Rows.Count));
  229. Progress.Close();
  230. }
  231. public string SectionName => "Factory Floor Analysis";
  232. public FactoryFloorAnalysisDashboardProperties Properties { get; set; }
  233. public DataModel DataModel(Selection selection)
  234. {
  235. Filter<ManufacturingPacket>? filter = null;
  236. if(selection == Selection.None)
  237. {
  238. filter = new Filter<ManufacturingPacket>();
  239. }
  240. return new AutoDataModel<ManufacturingPacket>(filter);
  241. }
  242. public Dictionary<string, object[]> Selected()
  243. {
  244. return new Dictionary<string, object[]>();
  245. }
  246. public void Heartbeat(TimeSpan time)
  247. {
  248. }
  249. private void ReloadHeaders(Dictionary<string, List<string>> columns)
  250. {
  251. dataGrid.StackedHeaderRows.Clear();
  252. //dataGrid.TableSummaryRows.Clear();
  253. var FactoryRow = new StackedHeaderRow();
  254. var SectionRow = new StackedHeaderRow();
  255. //var summaryRow = new GridTableSummaryRow();
  256. //summaryRow.ShowSummaryInRow = false;
  257. //var summaries = new ObservableCollection<ISummaryColumn>();
  258. //summaryRow.SummaryColumns = summaries;
  259. // fab / prs / glz
  260. foreach (var factory in columns.Keys)
  261. {
  262. FactoryRow.StackedColumns.Add(new StackedColumn
  263. { ChildColumns = string.Join(",", columns[factory]), HeaderText = factory, MappingName = factory });
  264. var sections = new Dictionary<string, List<string>>();
  265. foreach (var col in columns[factory])
  266. {
  267. var bits = col.Split(':');
  268. if (!sections.ContainsKey(bits[1]))
  269. sections[bits[1]] = new List<string>();
  270. sections[bits[1]].Add(col);
  271. //var summary = new GridSummaryColumn()
  272. //{
  273. // Name = col,
  274. // MappingName = col,
  275. // SummaryType = SummaryType.DoubleAggregate,
  276. // Format = "{Sum:F2}"
  277. //};
  278. //summaries.Add(summary);
  279. }
  280. // cut / mach / ass
  281. foreach (var sect in sections.Keys)
  282. SectionRow.StackedColumns.Add(new StackedColumn
  283. { ChildColumns = string.Join(",", sections[sect]), HeaderText = sect, MappingName = sect });
  284. }
  285. dataGrid.StackedHeaderRows.Add(FactoryRow);
  286. dataGrid.StackedHeaderRows.Add(SectionRow);
  287. //dataGrid.TableSummaryRows.Add(summaryRow);
  288. }
  289. private void CreateColumn(DataTable data, Dictionary<string, List<string>> columns, CoreRow row, string subcolumn)
  290. {
  291. var factory = row.Get<ManufacturingSection, string>(x => x.Factory.Name);
  292. var section = row.Get<ManufacturingSection, string>(x => x.Name);
  293. var columnname = string.Format("{0}:{1}:{2}", factory, Regex.Replace(section, "[^a-zA-Z0-9]", string.Empty), subcolumn);
  294. columns[factory].Add(columnname);
  295. data.Columns.Add(columnname, typeof(double));
  296. SectionDisplayNames[columnname] = section;
  297. }
  298. private static void UpdateColumn(Dictionary<string, double> totals, DataRow row, string fieldname, double value)
  299. {
  300. row[fieldname] = value;
  301. if (!totals.ContainsKey(fieldname))
  302. totals[fieldname] = 0.00F;
  303. totals[fieldname] = totals[fieldname] + value;
  304. }
  305. private void Employees_SelectionChanged(object sender, SelectionChangedEventArgs e)
  306. {
  307. if (IsReady && !_changing)
  308. Refresh();
  309. }
  310. private void Jobs_SelectionChanged(object sender, SelectionChangedEventArgs e)
  311. {
  312. if (IsReady && !_changing)
  313. Refresh();
  314. }
  315. private void Factories_SelectionChanged(object sender, SelectionChangedEventArgs e)
  316. {
  317. if (IsReady && !_changing)
  318. Refresh();
  319. }
  320. private void Templates_SelectionChanged(object sender, SelectionChangedEventArgs e)
  321. {
  322. if (IsReady && !_changing)
  323. Refresh();
  324. }
  325. private void Export_Click(object sender, RoutedEventArgs e)
  326. {
  327. var emp = (KeyValuePair<Guid, string>)Employees.SelectedItem;
  328. var fact = (KeyValuePair<Guid, string>)Factories.SelectedItem;
  329. var temp = (KeyValuePair<Guid, string>)Templates.SelectedItem;
  330. var filename = string.Format("{0} - {1} - {2} - {3:yyyy-MM-dd} - {4:yyyy-MM-dd}.xlsx", emp.Value, fact.Value, temp.Value,
  331. FromDate.SelectedDate, ToDate.SelectedDate);
  332. var options = new ExcelExportingOptions();
  333. options.ExcelVersion = ExcelVersion.Excel2013;
  334. options.ExportStackedHeaders = true;
  335. var excelEngine = dataGrid.ExportToExcel(dataGrid.View, options);
  336. var workBook = excelEngine.Excel.Workbooks[0];
  337. workBook.SaveAs(filename);
  338. var startInfo = new ProcessStartInfo(filename);
  339. startInfo.Verb = "open";
  340. startInfo.UseShellExecute = true;
  341. Process.Start(startInfo);
  342. }
  343. private void Search_KeyUp(object sender, KeyEventArgs e)
  344. {
  345. if (string.IsNullOrWhiteSpace(Search.Text) || e.Key == Key.Return)
  346. {
  347. _search = Search.Text;
  348. Refresh();
  349. }
  350. }
  351. private void DataGrid_AutoGeneratingColumn(object sender, AutoGeneratingColumnArgs e)
  352. {
  353. e.Column.TextAlignment = TextAlignment.Center;
  354. e.Column.HorizontalHeaderContentAlignment = HorizontalAlignment.Center;
  355. e.Column.ColumnSizer = GridLengthUnitType.None;
  356. var value = e.Column.ValueBinding as Binding;
  357. if (value.Path.Path.Equals("Serial"))
  358. {
  359. e.Column.Width = 150;
  360. e.Column.HeaderStyle = Resources["TemplateHeaderStyle"] as Style;
  361. }
  362. else if (value.Path.Path.Equals("Job"))
  363. {
  364. e.Column.Width = 60;
  365. e.Column.HeaderStyle = Resources["TemplateHeaderStyle"] as Style;
  366. }
  367. else if (value.Path.Path.Equals("Setout"))
  368. {
  369. e.Column.Width = 120;
  370. e.Column.HeaderStyle = Resources["TemplateHeaderStyle"] as Style;
  371. }
  372. else if (value.Path.Path.Equals("Description"))
  373. {
  374. e.Column.Width = 350;
  375. e.Column.HeaderStyle = Resources["TemplateHeaderStyle"] as Style;
  376. }
  377. else if (value.Path.Path.Equals("Template"))
  378. {
  379. e.Column.Width = 80;
  380. e.Column.HeaderStyle = Resources["TemplateHeaderStyle"] as Style;
  381. }
  382. else
  383. {
  384. var style = new Style(typeof(GridCell));
  385. e.Column.CellStyle = style;
  386. e.Column.Width = 50;
  387. e.Column.HeaderStyle = Resources["TemplateHeaderStyle"] as Style;
  388. e.Column.HeaderText = e.Column.HeaderText.Split(':').Last(); //SectionDisplayNames[value.Path.Path];
  389. }
  390. }
  391. private class GridCustomStackedRenderer : GridStackedHeaderCellRenderer
  392. {
  393. private readonly ResourceDictionary _resources;
  394. public GridCustomStackedRenderer(ResourceDictionary resources)
  395. {
  396. _resources = resources;
  397. }
  398. public override void OnInitializeEditElement(DataColumnBase dataColumn, GridStackedHeaderCellControl uiElement, object dataContext)
  399. {
  400. uiElement.Style = _resources["GroupHeaderStyle"] as Style;
  401. base.OnInitializeEditElement(dataColumn, uiElement, dataContext);
  402. }
  403. }
  404. #region Date Handling
  405. private int WeekDay(DateTime date)
  406. {
  407. if (date.DayOfWeek == DayOfWeek.Sunday)
  408. return 7;
  409. return (int)date.DayOfWeek - 1;
  410. }
  411. private void SetDates(DateTime from, DateTime to, bool enable)
  412. {
  413. if (_changing)
  414. return;
  415. _changing = true;
  416. _from = from;
  417. FromDate.SelectedDate = from;
  418. FromDate.IsEnabled = enable;
  419. _to = to;
  420. ToDate.SelectedDate = to;
  421. ToDate.IsEnabled = enable;
  422. _changing = false;
  423. if (!enable)
  424. Refresh();
  425. }
  426. private void DateRange_SelectionChanged(object sender, SelectionChangedEventArgs e)
  427. {
  428. if (!IsReady)
  429. return;
  430. if (DateRange.SelectedIndex == 0) // Week To Date
  431. SetDates(DateTime.Today.AddDays(0 - WeekDay(DateTime.Today)), DateTime.Today, false);
  432. else if (DateRange.SelectedIndex == 1) // Last 7 Days
  433. SetDates(DateTime.Today.AddDays(-6), DateTime.Today, false);
  434. else if (DateRange.SelectedIndex == 2) // Month To Date
  435. SetDates(new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1), DateTime.Today, false);
  436. else if (DateRange.SelectedIndex == 3) // Last 30 days
  437. SetDates(DateTime.Today.AddDays(-29), DateTime.Today, false);
  438. else if (DateRange.SelectedIndex == 4) // Year To Date
  439. SetDates(new DateTime(DateTime.Today.Year, 1, 1), DateTime.Today, false);
  440. else if (DateRange.SelectedIndex == 5) // Last 12 Months
  441. SetDates(DateTime.Today.AddYears(-1).AddDays(1), DateTime.Today, false);
  442. else if (DateRange.SelectedIndex == 6) // Custom
  443. SetDates(FromDate.SelectedDate.Value, ToDate.SelectedDate.Value, true);
  444. }
  445. private void FromDate_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
  446. {
  447. if (IsReady && !_changing)
  448. {
  449. _from = FromDate.SelectedDate.Value.Date;
  450. Refresh();
  451. }
  452. }
  453. private void ToDate_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
  454. {
  455. if (IsReady && !_changing)
  456. {
  457. _to = ToDate.SelectedDate.Value.Date;
  458. Refresh();
  459. }
  460. }
  461. #endregion
  462. }
  463. }