ソースを参照

wpf: improvements to FactoryFloorAnalysis

Kenric Nugteren 1 週間 前
コミット
569477c174
1 ファイル変更158 行追加152 行削除
  1. 158 152
      prs.desktop/Dashboards/Manufacturing/FactoryFloorAnalysis.xaml.cs

+ 158 - 152
prs.desktop/Dashboards/Manufacturing/FactoryFloorAnalysis.xaml.cs

@@ -45,8 +45,13 @@ namespace PRSDesktop
         private readonly Dictionary<string, string> SectionDisplayNames = new() { { "Total", "Total" } };
 
 
-        private CoreTable sections;
-        private CoreTable templatestages;
+        private Dictionary<Guid, ManufacturingSection> _sections;
+        private Dictionary<Guid, List<ManufacturingTemplateStage>> _templateStages;
+
+        private Guid _selectedFactory;
+        private Guid _selectedEmployee;
+        private Guid _selectedJob;
+        private Guid _selectedTemplate;
 
         public FactoryFloorAnalysis()
         {
@@ -73,39 +78,56 @@ namespace PRSDesktop
             ToDate.SelectedDate = _to;
 
             var employees = new Dictionary<Guid, string> { { Guid.Empty, "All Employees" } };
-            var emps = new Client<Employee>().Query(
+            var emps = Client.Query(
                 LookupFactory.DefineFilter<Employee>(),
-                LookupFactory.DefineColumns<Employee>(),
-                LookupFactory.DefineSort<Employee>()
-            );
-            foreach (var row in emps.Rows)
-                //if (row.Get<Employee, String>(x => x.Group.Description).Equals("FACTORY"))
-                employees[row.Get<Employee, Guid>(x => x.ID)] = row.Get<Employee, string>(x => x.Name);
+                Columns.None<Employee>()
+                    .Add(x => x.ID)
+                    .Add(x => x.Name),
+                LookupFactory.DefineSort<Employee>())
+                .ToObjects<Employee>();
+            foreach (var employee in emps)
+                employees[employee.ID] = employee.Name;
             Employees.ItemsSource = employees;
 
             var joblist = new Dictionary<Guid, string> { { Guid.Empty, "All Jobs" } };
-            var jobs = new Client<Job>().Query(
+            var jobs = Client.Query(
                 LookupFactory.DefineFilter<Job>(),
-                LookupFactory.DefineColumns<Job>(),
-                LookupFactory.DefineSort<Job>()
-            );
-            foreach (var row in jobs.Rows)
-                //if (row.Get<Employee, String>(x => x.Group.Description).Equals("FACTORY"))
-                joblist[row.Get<Job, Guid>(x => x.ID)] =
-                    string.Format("{0} - {1}", row.Get<Job, string>(x => x.JobNumber), row.Get<Job, string>(x => x.Name));
+                Columns.None<Job>()
+                    .Add(x => x.ID)
+                    .Add(x => x.JobNumber)
+                    .Add(x => x.Name),
+                LookupFactory.DefineSort<Job>())
+                .ToObjects<Job>();
+            foreach (var job in jobs)
+                joblist[job.ID] = $"{job.JobNumber} - {job.Name}";
             Jobs.ItemsSource = joblist;
 
-            sections = new Client<ManufacturingSection>().Query(
+            _sections = Client.Query(
                 new Filter<ManufacturingSection>(x => x.Hidden).IsEqualTo(false),
-                null,
-                new SortOrder<ManufacturingSection>(x => x.Factory.Sequence).ThenBy(x => x.Sequence));
+                Columns.None<ManufacturingSection>()
+                    .Add(x => x.ID)
+                    .Add(x => x.Name)
+                    .Add(x => x.Factory.ID)
+                    .Add(x => x.Factory.Name),
+                new SortOrder<ManufacturingSection>(x => x.Factory.Sequence).ThenBy(x => x.Sequence))
+                .ToObjects<ManufacturingSection>()
+                .ToDictionary(x => x.ID);
 
             var templates = new Dictionary<Guid, string> { { Guid.Empty, "All Templates" } };
-            templatestages = new Client<ManufacturingTemplateStage>().Query();
-            foreach (var row in templatestages.Rows)
-                templates[row.Get<ManufacturingTemplateStage, Guid>(x => x.Template.ID)] = string.Format("{0} - {1}",
-                    row.Get<ManufacturingTemplateStage, string>(x => x.Template.Code),
-                    row.Get<ManufacturingTemplateStage, string>(x => x.Template.Name));
+            _templateStages = Client.Query(
+                columns: Columns.None<ManufacturingTemplateStage>()
+                    .Add(x => x.Template.ID)
+                    .Add(x => x.Template.Code)
+                    .Add(x => x.Template.Name)
+                    .Add(x => x.Section.ID)
+                    .Add(x => x.Time))
+                .ToObjects<ManufacturingTemplateStage>()
+                .GroupByDictionary(x => x.Template.ID);
+            foreach (var (templateID, stages) in _templateStages)
+            {
+                var stage = stages[0];
+                templates[templateID] = $"{stage.Template.Code} - {stage.Template.Name}";
+            }
             Templates.ItemsSource = templates;
 
             dataGrid.ScrollMode = ScrollMode.Async;
@@ -113,14 +135,11 @@ namespace PRSDesktop
             var columns = new Dictionary<string, List<string>>();
 
             var factories = new Dictionary<Guid, string> { { Guid.Empty, "All Factories" } };
-            foreach (var row in sections.Rows)
+            foreach (var section in _sections.Values)
             {
-                var factoryid = row.Get<ManufacturingSection, Guid>(x => x.Factory.ID);
-                var factoryname = row.Get<ManufacturingSection, string>(x => x.Factory.Name);
-                factories[factoryid] = factoryname;
-
-                if (!columns.ContainsKey(factoryname))
-                    columns[factoryname] = new List<string>();
+                factories[section.Factory.ID] = section.Factory.Name;
+                if (!columns.ContainsKey(section.Factory.Name))
+                    columns[section.Factory.Name] = new List<string>();
             }
 
             Factories.ItemsSource = factories;
@@ -144,115 +163,110 @@ namespace PRSDesktop
 
             var columns = new Dictionary<string, List<string>>();
 
-            foreach (var row in sections.Rows)
-                if (Factories.SelectedValue.Equals(Guid.Empty) ||
-                    row.Get<ManufacturingSection, Guid>(x => x.Factory.ID).Equals(Factories.SelectedValue))
+            foreach (var section in _sections.Values)
+                if (_selectedFactory == Guid.Empty || section.Factory.ID == _selectedFactory)
                 {
-                    var factory = row.Get<ManufacturingSection, string>(x => x.Factory.Name);
-                    if (!columns.ContainsKey(factory))
-                        columns[factory] = new List<string>();
+                    var factoryColumns = columns.GetValueOrAdd(section.Factory.Name);
 
-                    CreateColumn(data, columns, row, "Est");
-                    CreateColumn(data, columns, row, "Act");
-                    CreateColumn(data, columns, row, "Var");
+                    CreateColumn(data, factoryColumns, section, "Est");
+                    CreateColumn(data, factoryColumns, section, "Act");
+                    CreateColumn(data, factoryColumns, section, "Var");
                 }
 
             ReloadHeaders(columns);
 
-            //dataGrid.CoveredCells.Clear();
             dataGrid.ItemsSource = data;
 
             Progress.Show("Retrieving Completed Work (0%) ...");
             data.Rows.Clear();
-            var empid = Employees.SelectedValue != null ? (Guid)Employees.SelectedValue : Guid.Empty;
-            var jobid = Jobs.SelectedValue != null ? (Guid)Jobs.SelectedValue : Guid.Empty;
-
-
-            var stgfilter = new Filter<ManufacturingPacketStage>(x => x.Completed).IsGreaterThanOrEqualTo(_from).And(x => x.Completed)
-                .IsLessThan(_to.AddDays(1));
-            if (jobid != Guid.Empty)
-                stgfilter = stgfilter.And(x => x.Parent.SetoutLink.JobLink.ID).IsEqualTo(jobid);
-            var completedstages = new Client<ManufacturingPacketStage>().Query(stgfilter,
-                Columns.None<ManufacturingPacketStage>().Add(
-                    x => x.Parent.ID,
-                    x => x.Parent.ManufacturingTemplateLink.ID,
-                    x => x.Parent.ManufacturingTemplateLink.Code,
-                    x => x.Parent.SetoutLink.JobLink.JobNumber,
-                    x => x.Parent.SetoutLink.Number,
-                    x => x.Parent.Serial,
-                    x => x.Parent.Title,
-                    x => x.Parent.Quantity
-                )
-            );
-
-            var pktids = new List<Guid> { Guid.Empty };
-            foreach (var stagerow in completedstages.Rows)
-            {
-                var id = stagerow.Get<ManufacturingPacketStage, Guid>(c => c.Parent.ID);
-                if (!pktids.Contains(id))
-                    pktids.Add(id);
-            }
-
-            Progress.SetMessage("Retrieving History (10%) ...");
-            var filter = new Filter<ManufacturingHistory>(x => x.Employee).LinkValid(empid);
 
-            if (jobid != Guid.Empty)
-                filter = filter.And(x => x.Packet.SetoutLink.JobLink.ID).IsEqualTo(jobid);
-            filter = filter.And(x => x.Packet.ID).InList(pktids.ToArray());
+            var stgfilter = new Filter<ManufacturingPacketStage>(x => x.Completed).IsGreaterThanOrEqualTo(_from)
+                .And(x => x.Completed).IsLessThan(_to.AddDays(1));
+            if (_selectedJob != Guid.Empty)
+                stgfilter = stgfilter.And(x => x.Parent.SetoutLink.JobLink.ID).IsEqualTo(_selectedJob);
 
+            Progress.SetMessage("Retrieving History (10%) ...");
+            var filter = new Filter<ManufacturingHistory>(x => x.Employee).LinkValid(_selectedEmployee);
+
+            if (_selectedJob != Guid.Empty)
+                filter = filter.And(x => x.Packet.SetoutLink.JobLink.ID).IsEqualTo(_selectedJob);
+            filter = filter.And(x => x.Packet.ID)
+                .InQuery(stgfilter, x => x.Parent.ID);
+
+            var results = Client.QueryMultiple(
+                new KeyedQueryDef<ManufacturingPacketStage>(
+                    stgfilter,
+                    Columns.None<ManufacturingPacketStage>()
+                        .Add(x => x.Parent.ID)
+                        .Add(x => x.Parent.ManufacturingTemplateLink.ID)
+                        .Add(x => x.Parent.ManufacturingTemplateLink.Code)
+                        .Add(x => x.Parent.SetoutLink.JobLink.JobNumber)
+                        .Add(x => x.Parent.SetoutLink.Number)
+                        .Add(x => x.Parent.Serial)
+                        .Add(x => x.Parent.Title)
+                        .Add(x => x.Parent.Quantity)),
+                new KeyedQueryDef<ManufacturingHistory>(
+                    filter,
+                    Columns.None<ManufacturingHistory>()
+                        .Add(x => x.Packet.ID)
+                        .Add(x => x.Section.ID)
+                        .Add(x => x.WorkDuration)
+                        .Add(x => x.QADuration)));
+
+            var completedstages = results.Get<ManufacturingPacketStage>()
+                .ToObjects<ManufacturingPacketStage>()
+                .GroupByDictionary(x => x.Parent.ID);
+
+            var history = results.Get<ManufacturingHistory>()
+                .Rows.Select(x =>
+                new
+                {
+                    PacketID = (Guid)x.Values[0],
+                    SectionID = (Guid)x.Values[1],
+                    WorkDuration = (TimeSpan)x.Values[2],
+                    QADuration = (TimeSpan)x.Values[3],
+                })
+                .GroupByDictionary(x => (packetID: x.PacketID, sectionID: x.SectionID));
 
-            var history = new Client<ManufacturingHistory>().Query(
-                filter,
-                Columns.None<ManufacturingHistory>().Add(
-                    x => x.Packet.ID,
-                    x => x.Section.ID,
-                    x => x.WorkDuration,
-                    x => x.QADuration
-                )
-            );
+            var packetIDs = completedstages.Keys.ToArray();
 
             var totals = new Dictionary<string, double>();
             var qtytotal = 0;
-            for (var i = 0; i < pktids.Count; i++)
-
+            for(var i = 0; i < packetIDs.Length; ++i)
             {
                 var bHasData = false;
 
-                Progress.SetMessage(string.Format("Calculating ({0:F2}%) ...", 20.0F + i * 80.0F / (double)pktids.Count));
+                Progress.SetMessage(string.Format("Calculating ({0:F2}%) ...", 20.0F + i * 80.0F / (double)packetIDs.Length));
 
-                //var packet = packets.Rows[i];
-                var pktid = pktids[i];
-                if (pktid != Guid.Empty)
+                var packetID = packetIDs[i];
+                if (packetID != Guid.Empty)
                 {
                     var row = data.NewRow();
 
                     // Get the First completed stage, so that we can extract the info from the packetlink
-                    var srow = completedstages.Rows.FirstOrDefault(r => r.Get<ManufacturingPacketStage, Guid>(x => x.Parent.ID).Equals(pktid));
-                    var stage = srow.ToObject<ManufacturingPacketStage>();
-
-                    row["Template"] = stage.Parent.ManufacturingTemplateLink.Code;
-                    row["Job"] = stage.Parent.SetoutLink.JobLink.JobNumber;
-                    row["Setout"] = stage.Parent.SetoutLink.Number;
-                    row["Serial"] = stage.Parent.Serial;
-                    row["Description"] = stage.Parent.Title;
-                    row["Qty"] = stage.Parent.Quantity;
-
-                    var pktstages = templatestages.Rows.Where(r =>
-                        r.Get<ManufacturingTemplateStage, Guid>(c => c.Template.ID).Equals(stage.Parent.ManufacturingTemplateLink.ID));
-                    foreach (var stagerow in pktstages)
+                    var firstStage = completedstages[packetID].First();
+
+                    row["Template"] = firstStage.Parent.ManufacturingTemplateLink.Code;
+                    row["Job"] = firstStage.Parent.SetoutLink.JobLink.JobNumber;
+                    row["Setout"] = firstStage.Parent.SetoutLink.Number;
+                    row["Serial"] = firstStage.Parent.Serial;
+                    row["Description"] = firstStage.Parent.Title;
+                    row["Qty"] = firstStage.Parent.Quantity;
+
+                    var packetStages = _templateStages.GetValueOrDefault(firstStage.Parent.ManufacturingTemplateLink.ID) ?? [];
+                    foreach (var stage in packetStages)
                     {
-                        var sectionid = stagerow.Get<ManufacturingTemplateStage, Guid>(c => c.Section.ID);
-                        var section = sections.Rows.FirstOrDefault(r => r.Get<ManufacturingSection, Guid>(c => c.ID).Equals(sectionid));
-                        var prefix = string.Format("{0}:{1}:", section.Get<ManufacturingSection, string>(x => x.Factory.Name),
-                            Regex.Replace(section.Get<ManufacturingSection, string>(x => x.Name), "[^a-zA-Z0-9]", ""));
-
-                        var estimated = stagerow.Get<ManufacturingTemplateStage, TimeSpan>(x => x.Time).TotalHours * stage.Parent.Quantity;
-                        var histrecords = history.Rows.Where(r =>
-                            r.Get<ManufacturingHistory, Guid>(c => c.Packet.ID).Equals(stage.Parent.ID) &&
-                            r.Get<ManufacturingHistory, Guid>(c => c.Section.ID).Equals(sectionid));
-                        var actual = new TimeSpan(histrecords.Sum(r =>
-                            r.Get<ManufacturingHistory, TimeSpan>(c => c.WorkDuration).Ticks +
-                            r.Get<ManufacturingHistory, TimeSpan>(c => c.QADuration).Ticks)).TotalHours;
+                        var sectionid = stage.Section.ID;
+                        var section = _sections.GetValueOrDefault(stage.Section.ID);
+                        if(section is null)
+                        {
+                            continue;
+                        }
+
+                        var prefix = string.Format("{0}:{1}:", section.Factory.Name, NotAlphaNumeric().Replace(section.Name, ""));
+                        var estimated = stage.Time.TotalHours * firstStage.Parent.Quantity;
+                        var histrecords = history.GetValueOrDefault((firstStage.Parent.ID, stage.Section.ID)) ?? [];
+                        var actual = new TimeSpan(histrecords.Sum(x => x.WorkDuration.Ticks + x.QADuration.Ticks)).TotalHours;
 
                         if (actual > 0.0F)
                         {
@@ -313,77 +327,64 @@ namespace PRSDesktop
         private void ReloadHeaders(Dictionary<string, List<string>> columns)
         {
             dataGrid.StackedHeaderRows.Clear();
-            //dataGrid.TableSummaryRows.Clear();
 
             var FactoryRow = new StackedHeaderRow();
             var SectionRow = new StackedHeaderRow();
 
-            //var summaryRow = new GridTableSummaryRow();
-            //summaryRow.ShowSummaryInRow = false;
-            //var summaries = new ObservableCollection<ISummaryColumn>();
-            //summaryRow.SummaryColumns = summaries;
-
             // fab / prs / glz
-            foreach (var factory in columns.Keys)
+            foreach (var (factory, factoryColumns) in columns)
             {
                 FactoryRow.StackedColumns.Add(new StackedColumn
-                    { ChildColumns = string.Join(",", columns[factory]), HeaderText = factory, MappingName = factory });
+                    { ChildColumns = string.Join(",", factoryColumns), HeaderText = factory, MappingName = factory });
 
                 var sections = new Dictionary<string, List<string>>();
-                foreach (var col in columns[factory])
+                foreach (var col in factoryColumns)
                 {
                     var bits = col.Split(':');
-                    if (!sections.ContainsKey(bits[1]))
-                        sections[bits[1]] = new List<string>();
-                    sections[bits[1]].Add(col);
-
-                    //var summary = new GridSummaryColumn()
-                    //{
-                    //    Name = col,
-                    //    MappingName = col,
-                    //    SummaryType = SummaryType.DoubleAggregate,
-                    //    Format = "{Sum:F2}"
-                    //};
-                    //summaries.Add(summary);
+                    sections.GetValueOrAdd(bits[1]).Add(col);
                 }
 
                 // cut / mach / ass
-                foreach (var sect in sections.Keys)
+                foreach (var (sect, sectionColumns) in sections)
                     SectionRow.StackedColumns.Add(new StackedColumn
-                        { ChildColumns = string.Join(",", sections[sect]), HeaderText = sect, MappingName = sect });
+                        { ChildColumns = string.Join(",", sectionColumns), HeaderText = sect, MappingName = sect });
             }
 
             dataGrid.StackedHeaderRows.Add(FactoryRow);
             dataGrid.StackedHeaderRows.Add(SectionRow);
-            //dataGrid.TableSummaryRows.Add(summaryRow);
         }
 
-        private void CreateColumn(DataTable data, Dictionary<string, List<string>> columns, CoreRow row, string subcolumn)
+        private void CreateColumn(DataTable data, List<string> columns, ManufacturingSection section, string subcolumn)
         {
-            var factory = row.Get<ManufacturingSection, string>(x => x.Factory.Name);
-            var section = row.Get<ManufacturingSection, string>(x => x.Name);
-            var columnname = string.Format("{0}:{1}:{2}", factory, Regex.Replace(section, "[^a-zA-Z0-9]", ""), subcolumn);
-            columns[factory].Add(columnname);
+            var factory = section.Factory.Name;
+            var sectionName = section.Name;
+            var columnname = string.Format("{0}:{1}:{2}", factory, NotAlphaNumeric().Replace(sectionName, ""), subcolumn);
+            columns.Add(columnname);
             data.Columns.Add(columnname, typeof(double));
-            SectionDisplayNames[columnname] = section;
+            SectionDisplayNames[columnname] = sectionName;
         }
 
         private static void UpdateColumn(Dictionary<string, double> totals, DataRow row, string fieldname, double value)
         {
             row[fieldname] = value;
-            if (!totals.ContainsKey(fieldname))
-                totals[fieldname] = 0.00F;
-            totals[fieldname] = totals[fieldname] + value;
+            if (!totals.TryGetValue(fieldname, out var total))
+            {
+                total = 0;
+                totals[fieldname] = total;
+            }
+            totals[fieldname] = total + value;
         }
 
         private void Employees_SelectionChanged(object sender, SelectionChangedEventArgs e)
         {
+            _selectedEmployee = (Guid)Employees.SelectedValue;
             if (IsReady && !_changing)
                 Refresh();
         }
 
         private void Jobs_SelectionChanged(object sender, SelectionChangedEventArgs e)
         {
+            _selectedJob = (Guid)Jobs.SelectedValue;
             if (IsReady && !_changing)
                 Refresh();
         }
@@ -391,6 +392,7 @@ namespace PRSDesktop
 
         private void Factories_SelectionChanged(object sender, SelectionChangedEventArgs e)
         {
+            _selectedFactory = (Guid)Factories.SelectedValue;
             if (IsReady && !_changing)
                 Refresh();
         }
@@ -398,6 +400,7 @@ namespace PRSDesktop
 
         private void Templates_SelectionChanged(object sender, SelectionChangedEventArgs e)
         {
+            _selectedTemplate = (Guid)Templates.SelectedValue;
             if (IsReady && !_changing)
                 Refresh();
         }
@@ -538,14 +541,14 @@ namespace PRSDesktop
             else if (DateRange.SelectedIndex == 5) // Last 12 Months
                 SetDates(DateTime.Today.AddYears(-1).AddDays(1), DateTime.Today, false);
             else if (DateRange.SelectedIndex == 6) // Custom
-                SetDates(FromDate.SelectedDate.Value, ToDate.SelectedDate.Value, true);
+                SetDates(FromDate.SelectedDate ?? DateTime.MinValue, ToDate.SelectedDate ?? DateTime.MaxValue, true);
         }
 
         private void FromDate_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
         {
             if (IsReady && !_changing)
             {
-                _from = FromDate.SelectedDate.Value.Date;
+                _from = FromDate.SelectedDate?.Date ?? DateTime.MinValue;
                 Refresh();
             }
         }
@@ -554,11 +557,14 @@ namespace PRSDesktop
         {
             if (IsReady && !_changing)
             {
-                _to = ToDate.SelectedDate.Value.Date;
+                _to = ToDate.SelectedDate?.Date ?? DateTime.MaxValue;
                 Refresh();
             }
         }
 
+        [GeneratedRegex("[^a-zA-Z0-9]")]
+        private static partial Regex NotAlphaNumeric();
+
         #endregion
     }
 }