예제 #1
0
 private void UpdateDocumentation()
 {
     foreach (Document document in _aircraftDocuments)
     {
         AutoCompleteStringCollection parameters = new AutoCompleteStringCollection
         {
             document.Description,
             document.ContractNumber,
             document.NextPerformanceDate != null
                                         ? UsefulMethods.NormalizeDate(document.IssueDateValidFrom)
                                         : "",
             document.IssueValidTo
                                         ? UsefulMethods.NormalizeDate(document.IssueDateValidTo)
                                         : "",
             document.Remains.ToString()
         };
         Action <AutoCompleteStringCollection> addLast = AddCertificateItem;
         if (InvokeRequired)
         {
             Invoke(addLast, parameters);
         }
         else
         {
             addLast.Invoke(parameters);
         }
     }
 }
        /// <summary>
        /// Добавляется элемент в таблицу данных
        /// </summary>
        /// <param name="componentобавляемый агрегат</param>
        /// <param name="previousNumber">Порядковый номер агрегата</param>
        /// <param name="destinationDataSet">Таблица, в которую добавляется элемент</param>
        protected override void AddDetailToDataset(Component component, ref int previousNumber, DetailListDataSet destinationDataSet)
        {
            var ata                    = component.ATAChapter;
            var atachapter             = ata.ShortName;
            var componentNumber        = (previousNumber++).ToString();
            var atachapterfull         = ata.FullName;
            var partNumber             = component.PartNumber;
            var description            = component.Description;
            var serialNumber           = component.SerialNumber;
            var lastTransferRecord     = component.TransferRecords.GetLast();
            var positionNumber         = lastTransferRecord.Position;
            var instalationDate        = UsefulMethods.NormalizeDate(lastTransferRecord.TransferDate);
            var installationLifelength = lastTransferRecord.OnLifelength;
            var remarks                = component.Remarks;

            GlobalObjects.PerformanceCalculator.GetNextPerformance(component);
            var current            = GlobalObjects.CasEnvironment.Calculator.GetCurrentFlightLifelength(component);
            var installationTsncsn = LifelengthFormatter.GetHoursData(installationLifelength, " hrs\r\n") +
                                     LifelengthFormatter.GetCyclesData(installationLifelength, " cyc\r\n");
            var currentTsncsn = LifelengthFormatter.GetHoursData(current, " hrs\r\n") +
                                LifelengthFormatter.GetCyclesData(current, " cyc\r\n");
            var condition = component.Condition.GetHashCode().ToString();
            var lifelengthAircraftTime = current;

            lifelengthAircraftTime.Substract(installationLifelength);
            var aircraftTime = LifelengthFormatter.GetHoursData(lifelengthAircraftTime, " hrs\r\n") +
                               LifelengthFormatter.GetCyclesData(lifelengthAircraftTime, " cyc\r\n");

            destinationDataSet.ItemsTable.AddItemsTableRow(componentNumber, atachapter, atachapterfull, partNumber, description, serialNumber, positionNumber, "",
                                                           instalationDate, "", "", "", "", "",
                                                           "", "", condition, aircraftTime, "", "", "", "", "", "",
                                                           installationTsncsn, remarks, currentTsncsn);
        }
예제 #3
0
        /// <summary>
        /// Проверяет введенные данные.
        /// Если какое-либо поле не подходит по формату, следует сразу кидать MessageBox, ставить курсор в необходимое поле и возвращать false в качестве результата метода
        /// </summary>
        /// <returns></returns>
        public override bool CheckData()
        {
            // Правильность ввода даты
            if (!ValidateEventDate())
            {
                MessageBox.Show("Event Date must be between 1 Jan 1950 and " + UsefulMethods.NormalizeDate(DateTime.Now),
                                (string)new GlobalTermsProvider()["SystemName"],
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Warning);
                return(false);
            }

            if (flowLayoutPanelConditions.Controls.OfType <SmsConditionControl>().Any(scc => !scc.CheckData()))
            {
                MessageBox.Show("Not specified event condition or " +
                                "\nthe selected item is not the end node of the tree",
                                (string)new GlobalTermsProvider()["SystemName"],
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Warning);

                return(false);
            }

            return(true);
        }
예제 #4
0
        protected override List <CustomCell> GetListViewSubItems(ATLB item)
        {
            AircraftFlightCollection flights;
            AircraftFlight           first;
            AircraftFlight           last;

            if (_parentAircraft != null)
            {
                flights = GlobalObjects.AircraftFlightsCore.GetAircraftFlightsByAircraftId(_parentAircraft.ItemId);
                first   = flights.GetFirstFlightInAtlb(item.ItemId);
                last    = flights.GetLastFlightInAtlb(item.ItemId);
            }
            else
            {
                first = GlobalObjects.AircraftFlightsCore.GetFirstFlight(item.ItemId);
                last  = GlobalObjects.AircraftFlightsCore.GetLastFlight(item.ItemId);
            }

            var pages = (first != null && first.PageNo != "" ? first.PageNo : "XXX") + " - " +
                        (last != null && last.PageNo != "" ? last.PageNo : "XXX");
            var dates = (first != null ? UsefulMethods.NormalizeDate(first.FlightDate.Date) : "YY:MM:DD") + " - " +
                        (last != null ? UsefulMethods.NormalizeDate(last.FlightDate.Date) : "YY:MM:DD");

            var author = GlobalObjects.CasEnvironment.GetCorrector(item);

            return(new List <CustomCell>()
            {
                CreateRow(item.AtlbStatus.ToString(), item.AtlbStatus),
                CreateRow(item.ATLBNo, item.ATLBNo),
                CreateRow(pages, pages),
                CreateRow(dates, last != null ? last.FlightDate : DateTimeExtend.GetCASMinDateTime()),
                CreateRow(author, author)
            });
        }
예제 #5
0
        /// <summary>
        /// Обновляет информацию в данном элементе управления
        /// </summary>
        /// <param name="reloadReport">Синхронизировать ли с базой данных</param>
        private void UpdateInformation(bool reloadReport)
        {
            if (reloadReport)
            {
#if RELEASE
                try
                {
#endif
                report.Reload();
                RemoveTempFile();
#if RELEASE
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error while loading data" + Environment.NewLine + ex.Message, (string)new StaticProjectTermsProvider()["SystemName"], MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
#endif
            }
            textBoxShortName.Text   = report.ShortName;
            textBoxReportName.Text  = report.RealName;
            textBoxDescription.Text = report.FullName;
            if (mode == ScreenMode.Edit)
            {
                labelDownloadDateValue.Text = UsefulMethods.NormalizeDate(report.RecievedDate);
            }
            else
            {
                labelDownloadDateValue.Text = UsefulMethods.NormalizeDate(DateTime.Now);
            }



            tempReport = new BiWeekly(report.RealName, report.Report);
            if (tempReport.Report != null)
            {
                tempReport.SaveReportToFile(out tempFilePath);
            }

            bool permission = report.HasPermission(Users.CurrentUser, DataEvent.Update);



            if (mode == ScreenMode.Edit)
            {
                headerControl.ButtonEdit.Enabled = permission;
            }
            buttonLoad.Enabled          = permission;
            buttonSaveToFile.Enabled    = !(tempReport.Report == null);
            textBoxShortName.ReadOnly   = !permission;
            textBoxReportName.ReadOnly  = !permission;
            textBoxDescription.ReadOnly = !permission;

            buttonDeleteReport.Visible = (mode == ScreenMode.Edit);
            buttonDeleteReport.Enabled = report.HasPermission(Users.CurrentUser, DataEvent.Remove);
        }
예제 #6
0
        /// <summary>
        /// Заполняет краткую информацию о директиве
        /// </summary>
        public void UpdateInformation()
        {
            if ((currentDirective == null) || !(currentDirective.Parent is BaseDetail))
            {
                return;
            }
            BaseDetail inspectedDetail = (BaseDetail)currentDirective.Parent;

            labelDateAsOfValue.Text       = DateTime.Today.ToString(new TermsProvider()["DateFormat"].ToString());
            labelDirectiveValue.Text      = currentDirective.Title + " for";
            labelDescriptionValue.Text    = currentDirective.Description;
            labelRepeatIntervalValue.Text = currentDirective.Closed ? "" : (currentDirective.RepeatPerform != null ? (currentDirective.RepeatedlyPerform ? currentDirective.RepeatPerform.ToRepeatIntervalsFormat() : "") : "");

            linkDetailInfoFirst.Text  = inspectedDetail.ToString();
            linkDetailInfoSecond.Text = inspectedDetail.ToString();

            labelDateLast.Text     = "";
            labelTsnCsnLast.Text   = "";
            labelWorktypeLast.Text = "";
            labelRemarksLast.Text  = "";
            labelDateNext.Text     = "";
            labelTsnCsnNext.Text   = "";
            labelWorktypeNext.Text = "";
            labelRemarksNext.Text  = "";
            if (currentDirective.LastPerformance != null)
            {
                labelDateLast.Text     = UsefulMethods.NormalizeDate(currentDirective.LastPerformance.RecordDate);
                labelWorktypeLast.Text = currentDirective.LastPerformance.RecordType.FullName;
                labelRemarksLast.Text  = currentDirective.LastPerformance.Description;
                if (currentDirective.LastPerformance.Lifelength != Lifelength.NullLifelength && (currentDirective.LastPerformance.Lifelength.Hours.TotalHours != 0 && currentDirective.LastPerformance.Lifelength.Cycles != 0))
                {
                    labelTsnCsnLast.Text = currentDirective.LastPerformance.Lifelength.ToComplianceItemString();
                }
            }
            if (!currentDirective.Closed)
            {
                labelDateNext.Text = UsefulMethods.NormalizeDate(currentDirective.GetApproximateDate());
                if (currentDirective.NextWorkType != null)
                {
                    labelWorktypeNext.Text = currentDirective.NextWorkType.FullName;
                }
                if (currentDirective.NextPerformance != null)
                {
                    labelTsnCsnNext.Text = currentDirective.NextPerformance.ToComplianceItemString();
                }
            }
            labelDetailTsnCsnValue.Text = inspectedDetail.Lifelength.ToComplianceItemString();
            labelDetailTsoCsoValue.Text = "";// inspectedDetail.Limitation.ResourceSinceOverhaul.ToComplianceItemString();todo
            if (CurrentBaseDetail == null)
            {
                return;
            }
            linkDirectiveStatus.Text = BackLinkText;
        }
예제 #7
0
 private void ClearFields()
 {
     textBoxShortName.Text       = "";
     textBoxReportName.Text      = "";
     textBoxDescription.Text     = "";
     labelDownloadDateValue.Text = UsefulMethods.NormalizeDate(DateTime.Now);
     buttonSaveToFile.Enabled    = false;
     reportViewItem.Icon         = icons.PDFGray;
     reportViewItem.Cursor       = Cursors.Default;
     report     = new BiWeekly("", null);
     tempReport = new BiWeekly("", null);
 }
        private void AddListViewItem(AbstractPerformanceRecord apr, WorkPackage workPackage)
        {
            DirectiveRecord directiveRecord = (DirectiveRecord)apr;

            string           workTypeString = "";
            StaticDictionary workType;

            if (directiveRecord.Parent is MaintenanceDirective)
            {
                MaintenanceDirective parentDirective = (MaintenanceDirective)directiveRecord.Parent;
                workType       = parentDirective.WorkType;
                workTypeString = parentDirective.WorkType.ToString();
            }
            else if (directiveRecord.Parent is ComponentDirective)
            {
                ComponentDirective parentDirective = (ComponentDirective)directiveRecord.Parent;
                workType       = parentDirective.DirectiveType;
                workTypeString = parentDirective.DirectiveType + " of " + parentDirective.ParentComponent.Description;
            }
            else
            {
                workType = MaintenanceDirectiveTaskType.Unknown;
            }
            string[] subs = new[]  {
                workTypeString,
                UsefulMethods.NormalizeDate(directiveRecord.RecordDate),
                directiveRecord.OnLifelength != null
                                           ? directiveRecord.OnLifelength.ToString()
                                           : "",
                directiveRecord.Remarks,
            };
            ListViewItem newItem = new ListViewItem(subs)
            {
                Group = listViewCompliance.Groups[1],
                Tag   = directiveRecord
            };

            if (workPackage != null)
            {
                //запись о выполнении блокируется найденым пакетом
                apr.DirectivePackage = workPackage;
                newItem.BackColor    = Color.FromArgb(Highlight.Grey.Color);
                newItem.ToolTipText  =
                    "Perform of the task:" + workType +
                    "\nadded by Work Package:" +
                    "\n" + directiveRecord.DirectivePackage.Title +
                    "\nTo remove a performance of task, you need to exclude task from this work package," +
                    "\nor delete the work package ";
            }
            listViewCompliance.Items.Add(newItem);
        }
        private void AddListViewItem(AbstractPerformanceRecord apr, WorkPackage workPackage,
                                     MaintenanceCheckRecord mcr)
        {
            DirectiveRecord      directiveRecord = (DirectiveRecord)apr;
            MaintenanceDirective parentDirective = (MaintenanceDirective)directiveRecord.Parent;

            string[] subs = new[]  {
                parentDirective.WorkType.ToString(),
                     UsefulMethods.NormalizeDate(directiveRecord.RecordDate),
                directiveRecord.OnLifelength != null
                                                   ? directiveRecord.OnLifelength.ToString()
                                                   : "",
                "",
                "",
                directiveRecord.Remarks,
            };

            ListViewItem newItem = new ListViewItem(subs)
            {
                Group = listViewCompliance.Groups[1],
                Tag   = directiveRecord
            };

            if (workPackage != null)
            {
                //запись о выполнении блокируется найденым пакетом
                apr.DirectivePackage = workPackage;
                newItem.BackColor    = Color.FromArgb(Highlight.Grey.Color);
                newItem.ToolTipText  =
                    "Perform of the task:" + parentDirective.WorkType +
                    "\nadded by Work Package:" +
                    "\n" + directiveRecord.DirectivePackage.Title +
                    "\nTo remove a performance of task, you need to exclude task from this work package," +
                    "\nor delete the work package ";
            }
            else if (directiveRecord.MaintenanceCheckRecordId > 0 && mcr != null && mcr.ParentCheck != null)
            {
                MaintenanceCheck mc = mcr.ParentCheck;
                directiveRecord.MaintenanceCheck = mc;
                newItem.BackColor   = Color.FromArgb(Highlight.Grey.Color);
                newItem.ToolTipText =
                    "Perform of the task:" + parentDirective.WorkType +
                    "\nadded by Maintenance Check:" +
                    "\n" + mc.Name +
                    "\nTo remove a performance of task, you need to delete performance of maintenance check";
            }
            listViewCompliance.Items.Add(newItem);
        }
예제 #10
0
 /// <summary>
 /// Обновляет значения полей
 /// </summary>
 public override void FillControls()
 {
     BeginUpdate();
     if (Flight != null)
     {
         textFlightNo.Text = Flight.FlightNo;
         textDate.Text     = UsefulMethods.NormalizeDate(Flight.FlightDate);
         textFrom.Text     = Flight.StationFrom;
         textTo.Text       = Flight.StationTo;
     }
     else
     {
         textFlightNo.Text = textDate.Text = textFrom.Text = textTo.Text = "";
     }
     EndUpdate();
 }
예제 #11
0
 /// <summary>
 /// Обновляет значения полей
 /// </summary>
 public override void FillControls()
 {
     BeginUpdate();
     if (Discrepancy != null)
     {
         radioCrew.Checked             = Discrepancy.FilledBy == DiscrepancyFilledByEnum.Crew;
         radioMaintenanceStaff.Checked = Discrepancy.FilledBy == DiscrepancyFilledByEnum.MaintenanceStaff;
         textATA.Text         = Discrepancy.ATAChapter != null ? Discrepancy.ATAChapter.ShortName : "";
         radioOpen.Checked    = Discrepancy.Status == CorrectiveActionStatus.Open;
         radioClose.Checked   = Discrepancy.Status == CorrectiveActionStatus.Close;
         textDescription.Text = Discrepancy.Description;
         //
         if (Discrepancy.CorrectiveAction != null)
         {
             textCorrectiveAction.Text = Discrepancy.CorrectiveAction.Description;
             textPNOff.Text            = Discrepancy.CorrectiveAction.PartNumberOff;
             textSNOff.Text            = Discrepancy.CorrectiveAction.SerialNumberOff;
             textPNOn.Text             = Discrepancy.CorrectiveAction.PartNumberOn;
             textSNOn.Text             = Discrepancy.CorrectiveAction.SerialNumberOn;
             textADDNo.Text            = Discrepancy.CorrectiveAction.ADDNo;
         }
         else
         {
             textCorrectiveAction.Text = textPNOff.Text = textSNOff.Text = textPNOn.Text = textSNOn.Text = "";
         }
         //
         if (Discrepancy.CertificateOfReleaseToService != null)
         {
             textStation.Text = Discrepancy.CertificateOfReleaseToService.Station;
             textRTSDate.Text = UsefulMethods.NormalizeDate(Discrepancy.CertificateOfReleaseToService.Date);
             textAuthNo.Text  = Discrepancy.CertificateOfReleaseToService.AuthorizationNo;
         }
         else
         {
             textStation.Text = textRTSDate.Text = textAuthNo.Text = "";
         }
     }
     else
     {
         textATA.Text       = textADDNo.Text = textDescription.Text = textCorrectiveAction.Text = textPNOff.Text =
             textSNOff.Text = textPNOn.Text = textSNOn.Text = textStation.Text = textRTSDate.Text = textAuthNo.Text = "";
         radioOpen.Checked  = radioClose.Checked = radioCrew.Checked = radioMaintenanceStaff.Checked = false;
         //
         textDescription.Text = "What Where When Extent";
     }
     EndUpdate();
 }
예제 #12
0
 /// <summary>
 /// Обновляет значения полей
 /// </summary>
 public override void FillControls()
 {
     BeginUpdate();
     if (Flight != null && Flight.CertificateOfReleaseToService != null)
     {
         checkPFC.Checked = Flight.CertificateOfReleaseToService.CheckPerformed == "PFC";
         checkTC.Checked  = Flight.CertificateOfReleaseToService.CheckPerformed == "TC";
         checkDY.Checked  = Flight.CertificateOfReleaseToService.CheckPerformed == "DY";
         textDate.Text    = UsefulMethods.NormalizeDate(Flight.CertificateOfReleaseToService.Date);
         textAuth.Text    = Flight.CertificateOfReleaseToService.AuthorizationNo;
     }
     else
     {
         checkPFC.Checked = checkTC.Checked = checkDY.Checked = false;
         textDate.Text    = textAuth.Text = "";
     }
     EndUpdate();
 }
예제 #13
0
        protected override void AddListViewItem(NextPerformance np)
        {
            string[] subs =
                new[]
            {
                np.WorkType,
                np.PerformanceDate != null
                        ? UsefulMethods.NormalizeDate((DateTime)np.PerformanceDate)
                        : "N/A",
                np.PerformanceSource.ToString(),
                "",
            };

            ListViewItem newItem = new ListViewItem(subs)
            {
                Group = listViewCompliance.Groups[0],
                Tag   = np,
            };

            listViewCompliance.Items.Add(newItem);
        }
예제 #14
0
        /// <summary>
        /// Создание обекта для списка
        /// </summary>
        /// <param name="item">Добавляемое отклонение</param>
        private ListViewItem CreateListViewItem(IMaintainable item)
        {
            double e = 0.000000001;

            string[] itemsString = new string[]
            {
                item.AtaChapter != null ? item.AtaChapter.ShortName:"",
                item.Title,
                ProcessText(item.Description),
                GetNextLifelength(item),
                item.NextRemains == null ? "" : item.NextRemains.ToString().Trim(),
                item.WorkType != null?item.WorkType.ShortName.Trim() : "",
                    UsefulMethods.NormalizeDate(item.ApproximateDate),
                    item.ManHours < e ? "" : item.ManHours.ToString(),
                    item.Cost < e ? "" : item.Cost.ToString()
            };

            ListViewItem listViewItem = new ListViewItem(itemsString);

            listViewItem.Tag = item;
            return(listViewItem);
        }
예제 #15
0
        protected override void BackgroundWorkerDoWork(object sender, DoWorkEventArgs e)
        {
            backgroundWorker.ReportProgress(50);

            try
            {
                Invoke(new Action(() => listViewCompliance.Items.Clear()));
            }
            catch (Exception)
            {
            }

            if (_currentComponent == null)
            {
                e.Cancel = true;
                return;
            }
            var parentAircraft   = GlobalObjects.AircraftsCore.GetParentAircraft(_currentComponent);
            var lastRecords      = new List <AbstractRecord>();
            var nextPerformances = new List <NextPerformance>();

            var allWorkPackagesIncludedTask     = new CommonCollection <WorkPackage>();
            var openPubWorkPackagesIncludedTask = new CommonCollection <WorkPackage>();
            var closedWorkPackages           = new CommonCollection <WorkPackage>();
            var taskThatIncludeInWorkPackage = new List <IDirective>();

            lastRecords.AddRange(_currentComponent.TransferRecords.ToArray());
            lastRecords.AddRange(_currentComponent.ChangeLLPCategoryRecords.ToArray());
            lastRecords.AddRange(_currentComponent.ActualStateRecords.ToArray());

            //Объекты для в котороые будет извлекаться информация
            //из записеи о перемещении
            var lastDestination = "";
            //прогнозируемый ресурс
            //если известна родительская деталь данной директивы,
            //то ее текущая наработка и средняя утилизация
            //используются в качестве ресурсов прогноза
            //для расчета всех просроченных выполнений
            var forecastData = new ForecastData(DateTime.Now,
                                                GlobalObjects.AverageUtilizationCore.GetAverageUtillization(_currentComponent),
                                                GlobalObjects.CasEnvironment.Calculator.GetCurrentFlightLifelength(_currentComponent));

            foreach (var directive in _currentComponent.ComponentDirectives)
            {
                if (directive.IsAffect().GetValueOrDefault(true))
                {
                    //расчет след. выполнений директивы.
                    //если известен ресурс прогноза, то будут расчитаны все просрочнные выполнения
                    //если неизвестне, то только первое
                    //GlobalObjects.PerformanceCalculator.GetNextPerformance(directive, forecastData);
                    nextPerformances.AddRange(directive.NextPerformances);
                    lastRecords.AddRange(directive.PerformanceRecords.ToArray());

                    if (backgroundWorker.CancellationPending)
                    {
                        e.Cancel = true;
                        return;
                    }
                    taskThatIncludeInWorkPackage.Add(directive);
                }
                else
                {
                    var bindedItems = GlobalObjects.BindedItemsCore.GetBindedItemsFor(parentAircraft.ItemId, directive);
                    foreach (var bindedItem in bindedItems)
                    {
                        if (bindedItem is MaintenanceDirective)
                        {
                            var mpd = (MaintenanceDirective)bindedItem;
                            //прогнозируемый ресурс
                            //если известна родительская деталь данной директивы,
                            //то ее текущая наработка и средняя утилизация
                            //используются в качестве ресурсов прогноза
                            //для расчета всех просроченных выполнений
                            //расчет след. выполнений директивы.
                            //если известен ресурс прогноза, то будут расчитаны все просрочнные выполнения
                            //если неизвестне, то только первое
                            GlobalObjects.PerformanceCalculator.GetNextPerformance(mpd, forecastData);
                            nextPerformances.AddRange(mpd.NextPerformances);
                            lastRecords.AddRange(mpd.PerformanceRecords.ToArray());

                            taskThatIncludeInWorkPackage.Add(mpd);
                        }
                    }
                }
            }

            //загрузка рабочих пакетов для определения
            //перекрытых ими выполнений задач
            if (_openPubWorkPackages == null)
            {
                _openPubWorkPackages = new CommonCollection <WorkPackage>();
            }
            _openPubWorkPackages.Clear();

            //загрузка рабочих пакетов для определения
            _openPubWorkPackages.AddRange(GlobalObjects.WorkPackageCore.GetWorkPackagesLite(parentAircraft, WorkPackageStatus.Opened));
            _openPubWorkPackages.AddRange(GlobalObjects.WorkPackageCore.GetWorkPackagesLite(parentAircraft, WorkPackageStatus.Published));

            allWorkPackagesIncludedTask.AddRange(GlobalObjects.WorkPackageCore.GetWorkPackagesLite(parentAircraft, WorkPackageStatus.All, taskThatIncludeInWorkPackage));

            #region Добавление в список просроченных выполнений

            //и сравнение их с открытыми и опубликованными рабочими пакетами
            openPubWorkPackagesIncludedTask.AddRange(
                allWorkPackagesIncludedTask.Where(wp => wp.Status == WorkPackageStatus.Opened ||
                                                  wp.Status == WorkPackageStatus.Published));
            //сбор всех записей рабочих пакетов для удобства фильтрации
            var openPubWpRecords =
                openPubWorkPackagesIncludedTask.SelectMany(wp => wp.WorkPakageRecords).ToList();
            //LINQ запрос для сортировки записей по дате
            var sortNextRecords = (from record in nextPerformances
                                   orderby GetDate(record) descending
                                   select record).ToList();
            for (int i = 0; i < sortNextRecords.Count; i++)
            {
                if (backgroundWorker.CancellationPending)
                {
                    allWorkPackagesIncludedTask.Clear();
                    openPubWorkPackagesIncludedTask.Clear();
                    closedWorkPackages.Clear();

                    e.Cancel = true;
                    return;
                }

                //поиск записи в рабочих пакетах по данному чеку
                //чей номер группы выполнения (по записи) совпадает с расчитанным
                var parentDirective = sortNextRecords[i].Parent;
                //номер выполнения
                int parentCountPerf;
                if (parentDirective.LastPerformance != null)
                {
                    parentCountPerf = parentDirective.LastPerformance.PerformanceNum <= 0
                                                ? 1
                                                : parentDirective.LastPerformance.PerformanceNum;
                }
                else
                {
                    parentCountPerf = 0;
                }
                parentCountPerf += parentDirective.NextPerformances.IndexOf(sortNextRecords[i]);
                parentCountPerf += 1;

                var wpr = openPubWpRecords.FirstOrDefault(r => r.PerformanceNumFromStart == parentCountPerf &&
                                                          r.WorkPackageItemType == parentDirective.SmartCoreObjectType.ItemId &&
                                                          r.DirectiveId == parentDirective.ItemId);
                if (wpr != null)
                {
                    var wp = openPubWorkPackagesIncludedTask.GetItemById(wpr.WorkPakageId);
                    //запись о выполнении блокируется найденым пакетом
                    sortNextRecords[i].BlockedByPackage = wp;
                    //последующие записи о выполнении так же должны быть заблокированы
                    for (int j = i - 1; j >= 0; j--)
                    {
                        //блокировать нужно все рабочие записи, или до первой записи,
                        //заблокированной другим рабочим пакетом
                        if (sortNextRecords[j].BlockedByPackage != null ||
                            sortNextRecords[j].Condition != ConditionState.Overdue)
                        {
                            break;
                        }
                        if (sortNextRecords[j].Parent == parentDirective)
                        {
                            sortNextRecords[j].BlockedByPackage = wp;
                            Invoke(new Action <int, Color>(SetItemColor), j, Color.FromArgb(Highlight.GrayLight.Color));
                        }
                    }
                }
                Invoke(new Action <NextPerformance>(AddListViewItem), sortNextRecords[i]);
            }

            #endregion

            #region Добавление в список записей о произведенных выполнениях

            //и сравнение их с закрытыми рабочими пакетами
            closedWorkPackages.AddRange(allWorkPackagesIncludedTask.Where(wp => wp.Status == WorkPackageStatus.Closed));

            //LINQ запрос для сортировки записей по дате
            var sortLastRecords = (from record in lastRecords
                                   orderby record.RecordDate ascending
                                   select record).ToList();

            var items = new List <KeyValuePair <AbstractRecord, string[]> >();

            for (int i = 0; i < sortLastRecords.Count; i++)
            {
                if (backgroundWorker.CancellationPending)
                {
                    allWorkPackagesIncludedTask.Clear();
                    openPubWorkPackagesIncludedTask.Clear();
                    closedWorkPackages.Clear();

                    e.Cancel = true;
                    return;
                }

                string[] subs;
                if (sortLastRecords[i] is DirectiveRecord)
                {
                    var directiveRecord = (DirectiveRecord)sortLastRecords[i];
                    subs = new[]
                    {
                        directiveRecord.WorkType,
                        UsefulMethods.NormalizeDate(directiveRecord.RecordDate),
                        directiveRecord.OnLifelength != null
                                                                        ? directiveRecord.OnLifelength.ToString()
                                                                        : "",
                        "",
                        "",
                        directiveRecord.Remarks
                    };
                }
                else if (sortLastRecords[i] is TransferRecord)
                {
                    TransferRecord transferRecord = (TransferRecord)sortLastRecords[i];

                    string currentDestination, destinationObject;
                    DestinationHelper.GetDestination(transferRecord, out currentDestination, out destinationObject);

                    subs = new[]
                    {
                        lastDestination != ""
                                                                        ? "Transfered " + destinationObject + " from " + lastDestination + " to " + currentDestination
                                                                        : "Transfered " + destinationObject + " to " + currentDestination,
                        UsefulMethods.NormalizeDate(transferRecord.TransferDate),
                        transferRecord.OnLifelength.ToString(),
                        "",
                        "",
                        transferRecord.Remarks,
                    };
                    lastDestination = currentDestination;
                }
                else if (sortLastRecords[i] is ComponentLLPCategoryChangeRecord)
                {
                    ComponentLLPCategoryChangeRecord llpRecord  = (ComponentLLPCategoryChangeRecord)sortLastRecords[i];
                    LLPLifeLimitCategory             toCategory = llpRecord.ToCategory;
                    subs = new[]
                    {
                        "Changed to " + toCategory,
                        UsefulMethods.NormalizeDate(llpRecord.RecordDate),
                        llpRecord.OnLifelength.ToString(),
                        "",
                        "",
                        llpRecord.Remarks,
                    };
                }
                else if (sortLastRecords[i] is ActualStateRecord)
                {
                    ActualStateRecord actualStateRecord = (ActualStateRecord)sortLastRecords[i];
                    subs = new[]
                    {
                        "Actual state:",
                        UsefulMethods.NormalizeDate(actualStateRecord.RecordDate.Date),
                        actualStateRecord.OnLifelength != null
                                                                        ? actualStateRecord.OnLifelength.ToString()
                                                                        : "",
                        "",
                        "",
                        actualStateRecord.Remarks,
                    };
                }
                else
                {
                    subs = new[]
                    {
                        "Unknown record ",
                        UsefulMethods.NormalizeDate(sortLastRecords[i].RecordDate),
                        sortLastRecords[i].OnLifelength.ToString(),
                        "",
                        "",
                        sortLastRecords[i].Remarks,
                    };
                }
                items.Add(new KeyValuePair <AbstractRecord, string[]>(sortLastRecords[i], subs));
            }

            #endregion

            for (int i = items.Count - 1; i >= 0; i--)
            {
                WorkPackage workPackage = null;
                if (items[i].Key is AbstractPerformanceRecord)
                {
                    var apr = items[i].Key as AbstractPerformanceRecord;
                    workPackage = closedWorkPackages.FirstOrDefault(wp => wp.ItemId == apr.DirectivePackageId);
                }
                Invoke(new Action <AbstractRecord, string[], WorkPackage>(AddListViewItem), items[i].Key, items[i].Value, workPackage);
            }

            allWorkPackagesIncludedTask.Clear();
            openPubWorkPackagesIncludedTask.Clear();
            closedWorkPackages.Clear();

            backgroundWorker.ReportProgress(100);
        }
        /// <summary>
        /// Добавляется элемент в таблицу данных
        /// </summary>
        /// <param name="reportedDirective">Добавлямая директива</param>
        /// <param name="destinationDataSet">Таблица, в которую добавляется элемент</param>
        protected virtual void AddDirectiveToDataset(MaintenanceDirective reportedDirective, MaintenanceDirectivesDataSetLatAvia destinationDataSet)
        {
            if (reportedDirective == null)
            {
                return;
            }

            string     status = "";
            Lifelength remain = Lifelength.Null;
            Lifelength used   = Lifelength.Null;

            //string remarks = reportedDirective.LastPerformance != null ? reportedDirective.LastPerformance.Remarks : reportedDirective.Remarks;
            if (reportedDirective.Status == DirectiveStatus.Closed)
            {
                status = "C";
            }
            if (reportedDirective.Status == DirectiveStatus.Open)
            {
                status = "O";
            }
            if (reportedDirective.Status == DirectiveStatus.Repetative)
            {
                status = "R";
            }
            if (reportedDirective.Status == DirectiveStatus.NotApplicable)
            {
                status = "N/A";
            }

            string effectivityDate = UsefulMethods.NormalizeDate(reportedDirective.Threshold.EffectiveDate);
            string kits            = "";
            int    num             = 1;

            foreach (AccessoryRequired kit in reportedDirective.Kits)
            {
                kits += num + ": " + kit.PartNumber + "\n";
                num++;
            }

            //расчет остатка с даты производства и с эффективной даты
            //расчет остатка от выполнения с даты производтсва
            string firstPerformanceString =
                reportedDirective.Threshold.FirstPerformanceSinceNew.ToString();

            if (reportedDirective.LastPerformance != null)
            {
                used.Add(_current);
                used.Substract(reportedDirective.LastPerformance.OnLifelength);
                if (!reportedDirective.Threshold.RepeatInterval.IsNullOrZero())
                {
                    used.Resemble(reportedDirective.Threshold.RepeatInterval);
                }
                else if (!reportedDirective.Threshold.FirstPerformanceSinceNew.IsNullOrZero())
                {
                    used.Resemble(reportedDirective.Threshold.FirstPerformanceSinceNew);
                }

                if (reportedDirective.NextPerformanceSource != null && !reportedDirective.NextPerformanceSource.IsNullOrZero())
                {
                    remain.Add(reportedDirective.NextPerformanceSource);
                    remain.Substract(_current);
                    remain.Resemble(reportedDirective.Threshold.RepeatInterval);
                }
            }


            var             remainCalc = Lifelength.Zero;
            NextPerformance next       = null;

            try
            {
                if (_mpLimit)
                {
                    if (reportedDirective.LastPerformance != null)
                    {
                        if (!reportedDirective.Threshold.RepeatInterval.IsNullOrZero() && !reportedDirective.IsClosed)
                        {
                            next = reportedDirective.NextPerformance;

                            next.PerformanceSource = Lifelength.Zero;
                            next.PerformanceSource.Add(reportedDirective.LastPerformance.OnLifelength);
                            next.PerformanceSource.Add(reportedDirective.Threshold.RepeatInterval);
                            next.PerformanceSource.Resemble(reportedDirective.Threshold.RepeatInterval);

                            if (reportedDirective.Threshold.RepeatInterval.Days.HasValue)
                            {
                                next.PerformanceDate =
                                    reportedDirective.LastPerformance.RecordDate.AddDays(reportedDirective.Threshold
                                                                                         .RepeatInterval.Days.Value);
                            }
                            else
                            {
                                next.PerformanceDate = null;
                            }

                            remainCalc.Add(next.PerformanceSource);
                            remainCalc.Substract(_current);
                            remainCalc.Resemble(reportedDirective.Threshold.RepeatInterval);

                            if (next.PerformanceDate != null)
                            {
                                remainCalc.Days = DateTimeExtend.DifferenceDateTime(DateTime.Today, next.PerformanceDate.Value).Days;
                            }
                        }
                    }
                    else if (reportedDirective.NextPerformanceSource != null && !reportedDirective.NextPerformanceSource.IsNullOrZero())
                    {
                        if (!reportedDirective.Threshold.RepeatInterval.IsNullOrZero())
                        {
                            remainCalc.Add(reportedDirective.NextPerformanceSource);
                            remainCalc.Substract(_current);
                            remainCalc.Resemble(reportedDirective.Threshold.RepeatInterval);
                        }
                    }
                }
                else
                {
                    remainCalc = reportedDirective.Remains;
                    next       = reportedDirective.NextPerformance;
                }

                destinationDataSet.ItemsTable.AddItemsTableRow(reportedDirective.TaskCardNumber, reportedDirective.TaskNumberCheck, reportedDirective.Description,
                                                               firstPerformanceString,
                                                               reportedDirective.Threshold.RepeatInterval != null ? reportedDirective.Threshold.RepeatInterval.Hours?.ToString() : "*",
                                                               reportedDirective.Threshold.RepeatInterval != null ? reportedDirective.Threshold.RepeatInterval.Cycles?.ToString() : "*",
                                                               reportedDirective.Threshold.RepeatInterval != null ? reportedDirective.Threshold.RepeatInterval.Days?.ToString() : "*",
                                                               reportedDirective.LastPerformance != null ? reportedDirective.LastPerformance.OnLifelength.Hours?.ToString() : "*",
                                                               reportedDirective.LastPerformance != null ? reportedDirective.LastPerformance.OnLifelength.Cycles?.ToString() : "*",
                                                               reportedDirective.LastPerformance != null ? reportedDirective.LastPerformance.RecordDate.Date.ToString("dd.MM.yyyy") : "*",
                                                               next != null ? next.PerformanceSource.Hours.ToString() : "*",
                                                               next != null ? next.PerformanceSource.Cycles.ToString() : "*",
                                                               next?.PerformanceDate != null  ? next.PerformanceDate.Value.ToString("dd.MM.yyyy") : "*",
                                                               remainCalc != null ? remainCalc.Hours.ToString() : "*",
                                                               remainCalc != null ? remainCalc.Cycles.ToString() : "*",
                                                               remainCalc != null ? remainCalc.Days.ToString() : "*", "", ""
                                                               );
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
예제 #17
0
        private void FindNextCheck()
        {
            //вычисление самого последнего выполненного чека, вне зависимости от типа
            //последний выполненый чек по типу может нессответствовать текущему типу программы
            //в случае переключения
            MaintenanceCheck lastComplianceCheck = CheckItems.Where(c => c.LastPerformance != null).OrderByDescending(c => c.LastPerformance.RecordDate).FirstOrDefault();

            if (lastComplianceCheck != null && lastComplianceCheck.Schedule != Schedule && Schedule)
            {
                //тип программмы Maintenance был переключен, переключение с Unschedule на Schedule
                //вычисление самого последнего выполненного чека, заданного типа
                MaintenanceCheck lastComplianceScheduleTypeCheck =
                    CheckItems.Where(c => c.LastPerformance != null && c.Schedule == Schedule).OrderByDescending(c => c.LastPerformance.RecordDate).FirstOrDefault();

                MaintenanceCheckGroupByType group = new List <MaintenanceCheck>(CheckItems).GetNextCheckBySourceDifference(lastComplianceScheduleTypeCheck, TsnCsn.Days);
                //название чеков
                MaintenanceCheck maxIntervalCheckInGroup = group.GetMaxIntervalCheck();
                string           tNext = maxIntervalCheckInGroup.Name + " (";
                tNext += group.Checks.Aggregate(tNext, (current, maintenanceCheck) => current + (maintenanceCheck.Name + " "));
                tNext += ") ";
                string tNextDate = UsefulMethods.NormalizeDate(group.GroupComplianceDate);

                group.GroupComplianceLifelength.Cycles = group.GroupComplianceLifelength.Hours = null;
                string tNextLl = group.GroupComplianceLifelength.ToRepeatIntervalsFormat();

                group.GroupComplianceLifelength.Substract(TsnCsn);
                group.GroupComplianceLifelength.Cycles = group.GroupComplianceLifelength.Hours = null;
                string tRemainLl = Convert.ToInt32(group.GroupComplianceLifelength.Days).ToString();

                Action <string, string, string, string> addLast = AddNextCheckItem;
                if (InvokeRequired)
                {
                    Invoke(addLast, tNext, tNextDate, tNextLl, tRemainLl);
                }
                else
                {
                    addLast.Invoke(tNext, tNextDate, tNextLl, tRemainLl);
                }
            }
            else
            {
                if (_complianceGroupCollection == null)
                {
                    _complianceGroupCollection = CheckItems.GetNextComplianceCheckGroups(Schedule).OrderBy(GetNextComplianceDate);
                }

                foreach (MaintenanceCheckComplianceGroup complianceGroup in _complianceGroupCollection)
                {
                    string           tNext, tNextDate, tNextLl, tRemainLl;
                    MaintenanceCheck maxIntervalCheckInGroup;
                    if ((maxIntervalCheckInGroup = complianceGroup.GetMaxIntervalCheck()) == null)
                    {
                        continue;
                    }
                    complianceGroup.Sort();

                    string prefix = complianceGroup.GetGroupName();

                    if (complianceGroup.Grouping)
                    {
                        MaintenanceCheck lastOrMinCheck =
                            complianceGroup.GetLastComplianceChecks().FirstOrDefault() != null
                                ? complianceGroup.GetLastComplianceChecks().First()
                                : complianceGroup.GetMinIntervalCheck();


                        //дата следующего выполнения группы чеков
                        if (lastOrMinCheck.Interval.Days != null && lastOrMinCheck.Interval.Days > 0)
                        {
                            DateTime nextDate = lastOrMinCheck.NextPerformances.Count != 0 && lastOrMinCheck.NextPerformances[0].PerformanceDate != null
                                                    ? lastOrMinCheck.NextPerformances[0].PerformanceDate.Value
                                                    : lastOrMinCheck.LastPerformance != null
                                                          ? lastOrMinCheck.LastPerformance.RecordDate.AddDays(Convert.ToInt32(lastOrMinCheck.Interval.Days))
                                                          : lastOrMinCheck.ParentAircraft.ManufactureDate.AddDays(Convert.ToInt32(lastOrMinCheck.Interval.Days));

                            tNextDate = UsefulMethods.NormalizeDate(nextDate);

                            if (lastOrMinCheck.NextPerformances.Count != 0 &&
                                lastOrMinCheck.NextPerformances[0].Remains != null)
                            {
                                //Остаток до выполнения
                                Lifelength remains = lastOrMinCheck.NextPerformances[0].Remains;
                                tRemainLl = remains.IsNullOrZero() ? "N/A" : remains.ToString();
                            }
                            else
                            {
                                tRemainLl = " N/A ";
                            }
                        }
                        else
                        {
                            tNextDate = lastOrMinCheck.NextPerformances.Count != 0 &&
                                        lastOrMinCheck.NextPerformances[0].PerformanceDate != null
                                ? " approx. " + UsefulMethods.NormalizeDate(lastOrMinCheck.NextPerformances[0].PerformanceDate.Value)
                                : " N/A ";

                            if (lastOrMinCheck.NextPerformances.Count != 0 &&
                                lastOrMinCheck.NextPerformances[0].Remains != null)
                            {
                                //Остаток до выполнения
                                Lifelength remains = lastOrMinCheck.NextPerformances[0].Remains;
                                tRemainLl = remains.IsNullOrZero() ? "N/A" : remains.ToString();
                            }
                            else
                            {
                                tRemainLl = " N/A ";
                            }
                        }
                        //ресурс, на котором надо поризвести выполнение
                        //след выполнение
                        Lifelength next =
                            lastOrMinCheck.NextPerformances.Count != 0
                                ? lastOrMinCheck.NextPerformances[0].PerformanceSource
                                : Lifelength.Null;
                        next.Resemble(maxIntervalCheckInGroup.Interval);
                        tNextLl = next.IsNullOrZero() ? "N/A" : next.ToString();
                        //название чеков
                        tNext = prefix;
                        if (lastOrMinCheck.ParentAircraft != null &&
                            lastOrMinCheck.ParentAircraft.MSG < MSG.MSG3)
                        {
                            tNext += " (";
                            tNext  = complianceGroup.Checks.Aggregate(tNext, (current, maintenanceCheck) => current + (maintenanceCheck.Name + " "));
                            tNext += ") ";
                        }

                        Action <string, string, string, string> addLast = AddNextCheckItem;
                        if (InvokeRequired)
                        {
                            Invoke(addLast, tNext, tNextDate, tNextLl, tRemainLl);
                        }
                        else
                        {
                            addLast.Invoke(tNext, tNextDate, tNextLl, tRemainLl);
                        }
                    }
                    else
                    {
                        foreach (MaintenanceCheck maintenanceCheck in complianceGroup.Checks)
                        {
                            DateTime nextDate;
                            if (maintenanceCheck.Interval.Days != null && maintenanceCheck.Interval.Days > 0)
                            {
                                nextDate =
                                    maintenanceCheck.NextPerformances.Count != 0 && maintenanceCheck.NextPerformances[0].PerformanceDate != null
                                                    ? maintenanceCheck.NextPerformances[0].PerformanceDate.Value
                                                    : maintenanceCheck.LastPerformance != null
                                                          ? maintenanceCheck.LastPerformance.RecordDate.AddDays(Convert.ToInt32(maintenanceCheck.Interval.Days))
                                                          : maintenanceCheck.ParentAircraft.ManufactureDate.AddDays(Convert.ToInt32(maintenanceCheck.Interval.Days));

                                tNextDate = "\n" + UsefulMethods.NormalizeDate(nextDate);

                                if (maintenanceCheck.NextPerformances.Count != 0 &&
                                    maintenanceCheck.NextPerformances[0].Remains != null)
                                {
                                    //Остаток до выполнения
                                    Lifelength remains = maintenanceCheck.NextPerformances[0].Remains;
                                    tRemainLl = "\n" + (remains.IsNullOrZero() ? "N/A" : remains.ToString());
                                }
                                else
                                {
                                    tRemainLl = "\n N/A ";
                                }
                            }
                            else
                            {
                                if (maintenanceCheck.NextPerformanceDate != null)
                                {
                                    nextDate  = maintenanceCheck.NextPerformanceDate.Value;
                                    tNextDate = "\n approx. " + UsefulMethods.NormalizeDate(nextDate);
                                }
                                else
                                {
                                    tNextDate = "\n (N/A) ";
                                }

                                if (maintenanceCheck.NextPerformances.Count != 0 &&
                                    maintenanceCheck.NextPerformances[0].Remains != null)
                                {
                                    //Остаток до выполнения
                                    Lifelength remains = maintenanceCheck.NextPerformances[0].Remains;
                                    tRemainLl = "\n" + (remains.IsNullOrZero() ? "N/A" : remains.ToString());
                                }
                                else
                                {
                                    tRemainLl = "\n (N/A) ";
                                }
                            }
                            //след выполнение
                            Lifelength next =
                                maintenanceCheck.NextPerformances.Count != 0
                                    ? maintenanceCheck.NextPerformances[0].PerformanceSource
                                    : Lifelength.Null;
                            tNextLl = "\n" + (next.IsNullOrZero() ? "N/A" : next.ToString());

                            //название чеков
                            tNext = "\n" + maintenanceCheck.Name + " ";

                            Action <string, string, string, string> addLast = AddNextCheckItem;
                            if (InvokeRequired)
                            {
                                Invoke(addLast, tNext, tNextDate, tNextLl, tRemainLl);
                            }
                            else
                            {
                                addLast.Invoke(tNext, tNextDate, tNextLl, tRemainLl);
                            }
                        }
                    }
                }
            }
        }
예제 #18
0
        private void FindLastCheck()
        {
            MaintenanceCheckGroupCollection[] groupByType =
                CheckItems.GroupingCheckByType(Schedule)
                .OrderByDescending(g => g.GetLastComplianceDate())
                .ToArray();

            MaintenanceCheckGroupCollection checkGroupCollectionOrdered =
                new MaintenanceCheckGroupCollection(groupByType.SelectMany(gbt => gbt.ToArray())
                                                    .OrderByDescending(gbt => gbt.LastComplianceGroupDate));

            foreach (MaintenanceCheckGroupByType checkGroupByType in checkGroupCollectionOrdered)
            {
                string   lastCheck = "", lastComplianceDate = "", lastComplianceLl = "";
                DateTime last = DateTimeExtend.GetCASMinDateTime();
                if (checkGroupByType.Grouping)
                {
                    //Вычисление последней даты выполнения чеков данного типа
                    //A, B или C
                    foreach (MaintenanceCheck checkItem in checkGroupByType.Checks.Where(c => c.Schedule == Schedule))
                    {
                        if (checkItem.LastPerformance != null && last < checkItem.LastPerformance.RecordDate)
                        {
                            last = checkItem.LastPerformance.RecordDate;
                        }
                    }
                    //Если чеки с данным типом (A, B или C) еще не выполнялись
                    //то производится переход на след. тип. чека
                    if (last <= DateTimeExtend.GetCASMinDateTime() ||
                        last <= checkGroupCollectionOrdered.GetLastComplianceDateOfCheckWithHigherType(checkGroupByType.Schedule,
                                                                                                       checkGroupByType.Resource,
                                                                                                       checkGroupByType.Grouping,
                                                                                                       checkGroupByType.CheckType))
                    {
                        continue;
                    }
                    //lastGroupComplianceDates[checkGroupByType.Resource] = last;
                    //Если чеки с данным типом выполнялись
                    //то собирается група из чеков данного типа (A, B или C),
                    //чья дата выполнения равна найденой
                    MaintenanceCheckComplianceGroup lastComplianceGroup = new MaintenanceCheckComplianceGroup(Schedule);
                    foreach (MaintenanceCheck checkItem in checkGroupByType.Checks.Where(c => c.Schedule == Schedule))
                    {
                        if (checkItem.LastPerformance != null && last == checkItem.LastPerformance.RecordDate)
                        {
                            lastComplianceGroup.Checks.Add(checkItem);
                            if (lastComplianceGroup.CheckCycle < checkGroupByType.CheckCycle)
                            {
                                lastComplianceGroup.CheckCycle = checkGroupByType.CheckCycle;
                            }
                            if (lastComplianceGroup.GroupComplianceNum < checkItem.LastPerformance.NumGroup)
                            {
                                lastComplianceGroup.GroupComplianceNum = checkItem.LastPerformance.NumGroup;
                            }
                        }
                    }
                    MaintenanceCheck maxIntervalCheckInGroup;
                    //Поиск старшего чека данного типа в собранной группе
                    //Если его нет, переход к след. типу чеков
                    if ((maxIntervalCheckInGroup = lastComplianceGroup.GetMaxIntervalCheck()) == null)
                    {
                        continue;
                    }
                    //Упорядочивание собранной группы
                    lastComplianceGroup.Sort();

                    string prefix = lastComplianceGroup.GetComplianceGroupName();
                    lastComplianceDate = UsefulMethods.NormalizeDate(last);
                    lastComplianceLl   = maxIntervalCheckInGroup.LastPerformance.OnLifelength.ToString();

                    //название чеков
                    lastCheck = prefix;
                    if (maxIntervalCheckInGroup.ParentAircraft != null &&
                        maxIntervalCheckInGroup.ParentAircraft.MSG < MSG.MSG3)
                    {
                        lastCheck += " (";
                        lastCheck += lastComplianceGroup.Checks.Aggregate(lastCheck, (current, maintenanceCheck) => current + (maintenanceCheck.Name + " "));
                        lastCheck += ") ";
                    }

                    Action <string, string, string> addLast = AddLastCheckItem;
                    if (InvokeRequired)
                    {
                        Invoke(addLast, lastCheck, lastComplianceDate, lastComplianceLl);
                    }
                    else
                    {
                        addLast.Invoke(lastCheck, lastComplianceDate, lastComplianceLl);
                    }
                }
                else
                {
                    foreach (MaintenanceCheck checkItem in checkGroupByType.Checks.Where(c => c.Schedule == Schedule))
                    {
                        if (checkItem.LastPerformance != null)
                        {
                            lastComplianceDate = UsefulMethods.NormalizeDate(checkItem.LastPerformance.RecordDate);
                            lastComplianceLl   = checkItem.LastPerformance.OnLifelength.ToString();

                            //название чеков
                            lastCheck = checkItem.Name;
                        }

                        Action <string, string, string> addLast = AddLastCheckItem;
                        if (InvokeRequired)
                        {
                            Invoke(addLast, lastCheck, lastComplianceDate, lastComplianceLl);
                        }
                        else
                        {
                            addLast.Invoke(lastCheck, lastComplianceDate, lastComplianceLl);
                        }
                    }
                }
            }
        }
예제 #19
0
        public void UpdateControl(List <MTOPCheck> maintenanceChecks, List <MTOPCheck> maintenanceChecksDeleted,
                                  Aircraft currentAircraft, AverageUtilization averageUtilization)
        {
            _averageUtilization = averageUtilization;
            _currentAircraft    = currentAircraft;
            listViewCompliance.Items.Clear();

            ListViewItem newItem;

            string[] subs;

            var mtopCheckRecords = new List <MTOPCheckRecord>();

            mtopCheckRecords.AddRange(maintenanceChecksDeleted.SelectMany(i => i.PerformanceRecords));
            mtopCheckRecords.AddRange(maintenanceChecks.SelectMany(i => i.PerformanceRecords));

            var nps = maintenanceChecks.SelectMany(i => i.NextPerformances);

            foreach (var np in nps.OrderByDescending(i => i.PerformanceSource.Days))
            {
                string perfDate = "";
                if (np.PerformanceDate.HasValue)
                {
                    perfDate = UsefulMethods.NormalizeDate(np.PerformanceDate.Value);
                }

                var group = np.ParentCheck.IsZeroPhase ? $"0{np.Group}" : np.Group.ToString();


                subs = new[]  {
                    group,
                    np.ParentCheck.Name,
                    perfDate,
                    np.PerformanceSource.ToRepeatIntervalsFormat(),
                    $"HRS/DAY: {Math.Round(np.ParentCheck.AverageUtilization.Hours, 2)} CYC/DAY: {Math.Round((double) (np.ParentCheck?.AverageUtilization?.Hours / np.ParentCheck.AverageUtilization?.CyclesPerDay), 2)}",
                    ""
                };

                newItem = new ListViewItem(subs)
                {
                    Group     = listViewCompliance.Groups["next"],
                    Tag       = np,
                    BackColor = UsefulMethods.GetColor(np)
                };

                listViewCompliance.Items.Add(newItem);
            }

            foreach (var record in mtopCheckRecords.OrderByDescending(i => i.CalculatedPerformanceSource.Days))
            {
                var group = record.Parent.IsZeroPhase ? $"0{record.GroupName}" : record.GroupName.ToString();

                subs = new[]  {
                    group,
                    record.CheckName,
                    UsefulMethods.NormalizeDate(record.RecordDate),
                    record.CalculatedPerformanceSource.ToRepeatIntervalsFormat(),
                    record.AverageUtilization != null ? $"HRS/DAY: {Math.Round(record.AverageUtilization.Hours, 2)} CYC/DAY: {Math.Round((double) (record.AverageUtilization?.Hours / record.AverageUtilization?.CyclesPerDay), 2)}" : "",
                    record.Remarks
                };

                newItem = new ListViewItem(subs)
                {
                    Group = listViewCompliance.Groups["last"],
                    Tag   = record
                };

                listViewCompliance.Items.Add(newItem);
            }
        }
예제 #20
0
        /// <summary>
        /// Добавляется элемент в таблицу данных
        /// </summary>
        /// <param name="item">Добавлямая директива</param>
        /// <param name="destinationDataSet">Таблица, в которую добавляется элемент</param>
        private void AddDirectiveToDataset(BaseEntityObject item, WorkscopeDataSet destinationDataSet)
        {
            if (item == null)
            {
                return;
            }

            string status;
            string applicabilityString;
            string hiddenRemarks;
            string description;
            string itemString;
            string lastPerformanceString;
            string nextPerformanceString;
            string conditionString;
            string zone;
            string ataShort;
            string ataFull;
            string taskCardNumber;
            string programmString;
            string maintenanceCheckString;
            string remarks;
            string directiveType;
            double cost;
            double mh;
            string effectivityDate;
            string kits;
            string remainString;
            string firstPerformanceString;
            string repeatPerformanceToString;

            IBaseEntityObject parent;

            if (item is NextPerformance)
            {
                parent = ((NextPerformance)item).Parent;
            }
            else if (item is AbstractPerformanceRecord)
            {
                parent = ((AbstractPerformanceRecord)item).Parent;
            }
            else
            {
                parent = item;
            }

            if (parent == null)
            {
                return;
            }

            if (parent is Directive)
            {
                Directive directive = (Directive)parent;
                status = directive.Status.ToString();
                lastPerformanceString = directive.LastPerformance != null?directive.LastPerformance.ToStrings() : "";

                nextPerformanceString = directive.NextPerformance != null?directive.NextPerformance.ToStrings() : "";

                conditionString        = directive.Condition.ToString();
                zone                   = "";
                programmString         = "";
                maintenanceCheckString = "N/A";
                remarks                = "";
                directiveType          = directive.WorkType.ToString();
                cost                   = directive.Cost;
                mh = directive.ManHours;
                effectivityDate           = UsefulMethods.NormalizeDate(directive.Threshold.EffectiveDate);
                kits                      = directive.Kits != null && directive.Kits.Count > 0 ? directive.Kits.Count + " kits" : "";
                firstPerformanceString    = directive.Threshold.FirstPerformanceToStrings();
                repeatPerformanceToString = directive.Threshold.RepeatPerformanceToStrings();
                remainString              = directive.Remains.ToString();

                StringBuilder stringBuilder = new StringBuilder();
                applicabilityString = directive.Applicability;
                hiddenRemarks       = directive.HiddenRemarks;
                description         = directive.Description;

                stringBuilder.AppendLine(directive.DirectiveType.ShortName);
                stringBuilder.AppendLine(directive.Title);
                if (!string.IsNullOrEmpty(directive.Paragraph))
                {
                    stringBuilder.AppendLine("\n§ " + directive.Paragraph);
                }
                AtaChapter ata = directive.ATAChapter;
                ataShort       = ata.ShortName;
                ataFull        = ata.ToString();
                taskCardNumber = directive.EngineeringOrders;
                stringBuilder.AppendLine(directive.EngineeringOrders);

                itemString = stringBuilder.ToString();
            }
            else if (parent is BaseComponent)
            {
                var bd  = (BaseComponent)parent;
                var ata = bd.ATAChapter ?? (AtaChapter)GlobalObjects.CasEnvironment.GetDictionary <AtaChapter>().GetItemById(-1);

                ataShort = ata.ShortName;
                ataFull  = ata.ToString();

                applicabilityString = "";
                hiddenRemarks       = bd.HiddenRemarks;
                description         = "";
                status = "";
                lastPerformanceString = "";
                nextPerformanceString = bd.NextPerformance != null?bd.NextPerformance.ToStrings() : "";

                conditionString        = bd.Condition.ToString();
                zone                   = "";
                programmString         = "";
                maintenanceCheckString = "N/A";
                remarks                = bd.Remarks;
                directiveType          = MaintenanceDirectiveTaskType.Discard.ToString();
                cost                   = bd.Cost;
                mh = bd.ManHours;
                effectivityDate           = UsefulMethods.NormalizeDate(bd.Threshold.EffectiveDate);
                taskCardNumber            = "";
                kits                      = bd.Kits != null && bd.Kits.Count > 0 ? bd.Kits.Count + " kits" : "";
                firstPerformanceString    = bd.Threshold.FirstPerformanceToStrings();
                repeatPerformanceToString = bd.Threshold.RepeatPerformanceToStrings();
                remainString              = bd.Remains.ToString();

                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.AppendLine("Compnt.");
                stringBuilder.AppendLine(bd.PartNumber);
                stringBuilder.AppendLine(bd.Description);

                itemString = stringBuilder.ToString();
            }
            else if (parent is Component)
            {
                var d   = (Component)parent;
                var ata = d.ATAChapter ?? (AtaChapter)GlobalObjects.CasEnvironment.GetDictionary <AtaChapter>().GetItemById(-1);

                ataShort = ata.ShortName;
                ataFull  = ata.ToString();

                applicabilityString = "";
                hiddenRemarks       = d.HiddenRemarks;
                description         = d.Description;
                status = "";
                lastPerformanceString = "";
                nextPerformanceString = d.NextPerformance != null?d.NextPerformance.ToStrings() : "";

                conditionString        = d.Condition.ToString();
                zone                   = "";
                programmString         = "";
                maintenanceCheckString = "N/A";
                remarks                = d.Remarks;
                directiveType          = MaintenanceDirectiveTaskType.Discard.ToString();
                cost                   = d.Cost;
                mh = d.ManHours;
                effectivityDate           = UsefulMethods.NormalizeDate(d.Threshold.EffectiveDate);
                taskCardNumber            = "";
                kits                      = d.Kits != null && d.Kits.Count > 0 ? d.Kits.Count + " kits" : "";
                firstPerformanceString    = d.Threshold.FirstPerformanceToStrings();
                repeatPerformanceToString = d.Threshold.RepeatPerformanceToStrings();
                remainString              = d.Remains.ToString();

                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.AppendLine("Compnt.");
                stringBuilder.AppendLine("P/N:" + d.PartNumber);
                stringBuilder.AppendLine("S/N:" + d.SerialNumber);

                itemString = stringBuilder.ToString();
            }
            else if (parent is ComponentDirective)
            {
                var dd  = (ComponentDirective)parent;
                var ata = dd.ParentComponent.ATAChapter ?? (AtaChapter)GlobalObjects.CasEnvironment.GetDictionary <AtaChapter>().GetItemById(-1);

                ataShort = ata.ShortName;
                ataFull  = ata.ToString();

                applicabilityString = "";
                hiddenRemarks       = dd.HiddenRemarks;
                description         = "";
                status = dd.Status.ToString();
                lastPerformanceString = dd.LastPerformance != null?dd.LastPerformance.ToStrings() : "";

                nextPerformanceString = dd.NextPerformance != null?dd.NextPerformance.ToStrings() : "";

                conditionString        = dd.Condition.ToString();
                zone                   = "";
                programmString         = "";
                maintenanceCheckString = "N/A";
                remarks                = dd.Remarks;
                directiveType          = dd.DirectiveType.ToString();
                cost                   = dd.Cost;
                mh = dd.ManHours;
                effectivityDate           = UsefulMethods.NormalizeDate(dd.Threshold.EffectiveDate);
                taskCardNumber            = "";
                kits                      = dd.Kits != null && dd.Kits.Count > 0 ? dd.Kits.Count + " kits" : "";
                firstPerformanceString    = dd.Threshold.FirstPerformanceToStrings();
                repeatPerformanceToString = dd.Threshold.RepeatPerformanceToStrings();
                remainString              = dd.Remains.ToString();

                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.AppendLine("Compnt.");
                if (dd.ParentComponent != null)
                {
                    Component d = dd.ParentComponent;
                    stringBuilder.AppendLine("P/N:" + d.PartNumber);
                    stringBuilder.AppendLine("S/N:" + d.SerialNumber);

                    description = d.Description;
                }
                itemString = stringBuilder.ToString();
            }
            else if (parent is MaintenanceCheck)
            {
                return;
                //MaintenanceCheck mc = (MaintenanceCheck)parent;

                //AtaChapter ata = (AtaChapter)GlobalObjects.CasEnvironment.Dictionaries[typeof(AtaChapter)].GetItemById(-1);
                //ataShort = ata.ShortName;
                //ataFull = ata.ToString();

                //applicabilityString = "";
                //hiddenRemarks = "";
                //description = "";
                //status = "";
                //lastPerformanceString = mc.LastPerformance != null ? mc.LastPerformance.ToStrings() : "";
                //nextPerformanceString = mc.NextPerformance != null ? mc.NextPerformance.ToStrings() : "";
                //conditionString = mc.Condition.ToString();
                //zone = "";
                //programmString = "";
                //maintenanceCheckString = "";
                //remarks = "";
                //directiveType = "";
                //cost = mc.Cost;
                //mh = mc.ManHours;
                //effectivityDate = UsefulMethods.NormalizeDate(mc.Threshold.EffectiveDate);
                //taskCardNumber = "";
                //kits = mc.Kits != null && mc.Kits.Count > 0 ? mc.Kits.Count + " kits" : "";
                //firstPerformanceString = mc.Threshold.FirstPerformanceToStrings();
                //repeatPerformanceToString = mc.Threshold.RepeatPerformanceToStrings();
                //remainString = mc.Remains.ToString();

                //StringBuilder stringBuilder = new StringBuilder();
                //stringBuilder.AppendLine("Check");
                //stringBuilder.AppendLine(mc.ToString());

                //itemString = stringBuilder.ToString();
            }
            else if (parent is MaintenanceDirective)
            {
                MaintenanceDirective md = (MaintenanceDirective)parent;

                AtaChapter ata = md.ATAChapter;
                ataShort = ata.ShortName;
                ataFull  = ata.ToString();

                applicabilityString = md.Applicability;
                hiddenRemarks       = md.HiddenRemarks;
                description         = md.Description;
                status = md.Status.ToString();
                lastPerformanceString = md.LastPerformance != null?md.LastPerformance.ToStrings() : "";

                nextPerformanceString = md.NextPerformance != null?md.NextPerformance.ToStrings() : "";

                conditionString = md.Condition?.ToString();
                zone            = md.Zone;
                programmString  = md.Program.ToString();

                if (md.MaintenanceCheck != null)
                {
                    maintenanceCheckString = md.MaintenanceCheck.ToString();
                }
                else if (_workPackage != null)
                {
                    MaintenanceCheckBindTaskRecord record =
                        _workPackage.MaintenanceCheckBindTaskRecords.FirstOrDefault(br => br.TaskType == SmartCoreType.MaintenanceDirective &&
                                                                                    br.TaskId == md.ItemId);
                    if (record != null)
                    {
                        maintenanceCheckString = record.ParentCheck != null?record.ParentCheck.ToString() : "N/A";
                    }
                    else
                    {
                        maintenanceCheckString = "N/A";
                    }
                }
                else
                {
                    maintenanceCheckString = "N/A";
                }

                remarks                   = md.Remarks;
                directiveType             = md.WorkType.ToString();
                cost                      = md.Cost;
                mh                        = md.ManHours;
                effectivityDate           = UsefulMethods.NormalizeDate(md.Threshold.EffectiveDate);
                taskCardNumber            = md.TaskCardNumber;
                kits                      = md.Kits != null && md.Kits.Count > 0 ? md.Kits.Count + " kits" : "";
                firstPerformanceString    = md.Threshold.FirstPerformanceToStrings();
                repeatPerformanceToString = md.Threshold.RepeatPerformanceToStrings();
                remainString              = md.Remains.ToString();

                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.AppendLine("MPD");
                stringBuilder.AppendLine(md.TaskNumberCheck);
                stringBuilder.AppendLine(md.TaskCardNumber);

                itemString = stringBuilder.ToString();
            }
            else if (parent is NonRoutineJob)
            {
                NonRoutineJob job = (NonRoutineJob)parent;

                AtaChapter ata = job.ATAChapter;
                ataShort = ata.ShortName;
                ataFull  = ata.ToString();

                applicabilityString = "";
                hiddenRemarks       = "";
                description         = job.Description;
                status = "";
                lastPerformanceString = "";
                nextPerformanceString = "";
                conditionString       = job.Condition.ToString();
                zone                   = "";
                programmString         = "";
                maintenanceCheckString = "N/A";
                remarks                = "";
                directiveType          = "";
                cost                   = job.Cost;
                mh = job.ManHours;
                effectivityDate           = "";
                taskCardNumber            = "";
                kits                      = job.Kits != null && job.Kits.Count > 0 ? job.Kits.Count + " kits" : "";
                firstPerformanceString    = "";
                repeatPerformanceToString = "";
                remainString              = job.Remains.ToString();

                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.AppendLine("NRC");
                stringBuilder.AppendLine(job.Title);

                itemString = stringBuilder.ToString();
            }
            else
            {
                return;
            }

            destinationDataSet.ItemsTable.AddItemsTableRow(applicabilityString,
                                                           remarks,
                                                           hiddenRemarks,
                                                           description,
                                                           itemString,
                                                           "",
                                                           directiveType,
                                                           status,
                                                           effectivityDate,
                                                           firstPerformanceString,
                                                           lastPerformanceString,
                                                           nextPerformanceString,
                                                           remainString,
                                                           conditionString,
                                                           mh,
                                                           cost,
                                                           kits,
                                                           zone,
                                                           ataShort,
                                                           ataFull,
                                                           taskCardNumber,
                                                           programmString,
                                                           repeatPerformanceToString,
                                                           "",
                                                           maintenanceCheckString);
        }
예제 #21
0
        public void UpdateControl(List <MTOPCheck> maintenanceChecks,
                                  Dictionary <int, Lifelength> groupLifelengths,
                                  Dictionary <int, Lifelength> groupLifelengthsZeroPhase)
        {
            UpdateSchedule(maintenanceChecks.Where(i => !i.IsZeroPhase).OrderBy(i => i.PhaseThresh.Hours).ToList(), groupLifelengths);

            var aCheck = maintenanceChecks.Where(i => !i.IsZeroPhase).OrderBy(i => i.PhaseThresh.Hours).FirstOrDefault();

            UpdateScheduleZeroPhase(maintenanceChecks.Where(i => i.IsZeroPhase).OrderBy(i => i.PhaseThresh.Hours).ToList(), groupLifelengthsZeroPhase, aCheck);
            UpdateNotify(maintenanceChecks);
            listViewLastCheck.Items.Clear();
            listViewNextCheck.Items.Clear();

            ListViewItem newItem;

            string[] subs;

            foreach (var check in maintenanceChecks)
            {
                string perfDate = "";
                if (check.NextPerformance?.PerformanceDate != null)
                {
                    perfDate = UsefulMethods.NormalizeDate(check.NextPerformance.PerformanceDate.Value);
                }

                var group = "";

                if (check.NextPerformance != null)
                {
                    group = check.NextPerformance.ParentCheck.IsZeroPhase ? $"0{check.NextPerformance?.Group}" : check.NextPerformance?.Group.ToString();
                }

                subs = new[]  {
                    check.Name,
                    group,
                    perfDate,
                    check.NextPerformance?.PerformanceSource.ToRepeatIntervalsFormat(),
                    check.NextPerformance?.Remains.ToString()
                };

                listViewNextCheck.Groups.Add(check.CheckType.FullName, check.CheckType.FullName);

                newItem = new ListViewItem(subs)
                {
                    Tag   = check,
                    Group = listViewNextCheck.Groups[check.CheckType.FullName]
                };
                listViewNextCheck.Items.Add(newItem);


                if (check.PerformanceRecords.Count > 0)
                {
                    var lastRecord = check.PerformanceRecords.OrderByDescending(i => i.ItemId).First();

                    group = lastRecord.Parent.IsZeroPhase ? $"0{lastRecord.GroupName}" : lastRecord.GroupName.ToString();

                    subs = new[]  {
                        lastRecord.CheckName,
                        group,
                        UsefulMethods.NormalizeDate(lastRecord.RecordDate),
                        lastRecord.CalculatedPerformanceSource.ToRepeatIntervalsFormat()
                    };

                    listViewLastCheck.Groups.Add(check.CheckType.FullName, check.CheckType.FullName);

                    newItem = new ListViewItem(subs)
                    {
                        Group = listViewLastCheck.Groups[check.CheckType.FullName],
                        Tag   = lastRecord
                    };

                    listViewLastCheck.Items.Add(newItem);
                }
            }
        }
 private string[] GetItemsString(JobCard jobCard)
 {
     return(new string[] { jobCard.AirlineCardNumber, jobCard.WorkArea, jobCard.Revision, UsefulMethods.NormalizeDate(jobCard.Date) });
 }
예제 #23
0
        private void UpdateInformation()
        {
            if (_contextMenuStrip == null)
            {
                InitToolStripMenuItems();
            }

            listViewCompliance.Items.Clear();

            if (CheckItems == null)
            {
                return;
            }

            var lastRecords      = new List <MaintenanceCheckRecord>();
            var nextPerformances = new List <NextPerformance>();

            //Поиск и заполнение просроченных директив и записей о перемещении
            //Объекты для в которые будет извлекаться информация
            //из записеи о перемещении

            string[]     subs;
            ListViewItem newItem;

            var aircraftFrame = GlobalObjects.ComponentCore.GetBaseComponentById(_currentAircraft.AircraftFrameId);
            //прогнозируемый ресурс
            var forecastData = new ForecastData(DateTime.Now, aircraftFrame.AverageUtilization,
                                                GlobalObjects.CasEnvironment.Calculator.GetCurrentFlightLifelength(_currentAircraft));

            //GlobalObjects.CasEnvironment.Calculator.GetNextPerformanceGroup(CheckItems, _currentAircraft.Schedule, forecastData);

            foreach (MaintenanceCheck check in CheckItems)
            {
                if (check.Grouping)
                {
                    foreach (MaintenanceNextPerformance mnp in check.GetPergormanceGroupWhereCheckIsSenior())
                    {
                        //Добавляются все выполнения, дата которых меньше нынешней
                        //плюс еще одно выполнение дата которого выше нынешней
                        nextPerformances.Add(mnp);

                        if (mnp.PerformanceDate != null && mnp.PerformanceDate > DateTime.Now)
                        {
                            break;
                        }
                    }
                }
                else
                {
                    foreach (NextPerformance mnp in check.NextPerformances)
                    {
                        //Добавляются все выполнения, дата которых меньше нынешней
                        //плюс еще одно выполнение дата которого выше нынешней
                        nextPerformances.Add(mnp);

                        if (mnp.PerformanceDate != null && mnp.PerformanceDate > DateTime.Now)
                        {
                            break;
                        }
                    }
                }

                lastRecords.AddRange(check.PerformanceRecords.ToArray());

                foreach (MaintenanceDirective mpd in check.BindMpds)
                {
                    GlobalObjects.PerformanceCalculator.GetNextPerformance(mpd, forecastData);
                }
            }
            ////////////////////////////////////////////
            //загрузка рабочих пакетов для определения
            //перекрытых ими выполнений задач
            if (_openPubWorkPackages == null)
            {
                _openPubWorkPackages = new CommonCollection <WorkPackage>();
            }
            _openPubWorkPackages.Clear();
            _openPubWorkPackages.AddRange(GlobalObjects.WorkPackageCore.GetWorkPackagesLite(_currentAircraft, WorkPackageStatus.Opened));
            _openPubWorkPackages.AddRange(GlobalObjects.WorkPackageCore.GetWorkPackagesLite(_currentAircraft, WorkPackageStatus.Published));

            var allWorkPackagesIncludedTask = new CommonCollection <WorkPackage>();
            var openPubWorkPackages         = new CommonCollection <WorkPackage>();
            var closedWorkPackages          = new CommonCollection <WorkPackage>();

            allWorkPackagesIncludedTask.AddRange(GlobalObjects.WorkPackageCore.GetWorkPackagesLite(_currentAircraft,
                                                                                                   WorkPackageStatus.All,
                                                                                                   CheckItems.Select(m => (IDirective)m).ToList()));

            #region Добавление в список просроченных выполнений
            //и сравнение их с открытыми и опубликованными рабочими пакетами
            openPubWorkPackages.AddRange(allWorkPackagesIncludedTask.Where(wp => wp.Status == WorkPackageStatus.Opened ||
                                                                           wp.Status == WorkPackageStatus.Published));
            //сбор всех записей рабочих пакетов для удобства фильтрации
            List <WorkPackageRecord> openPubWPRecords = new List <WorkPackageRecord>();
            foreach (WorkPackage openWorkPackage in openPubWorkPackages)
            {
                openPubWPRecords.AddRange(openWorkPackage.WorkPakageRecords);
            }

            //LINQ запрос для сортировки записей по дате
            List <NextPerformance> sortNextRecords = (from record in nextPerformances
                                                      orderby record.GetPerformanceDateOrDefault() descending
                                                      select record).ToList();

            for (int i = 0; i < sortNextRecords.Count; i++)
            {
                //поиск записи в рабочих пакетах по данному чеку
                //чей номер группы выполнения (по записи) совпадает с расчитанным
                MaintenanceCheck check = (MaintenanceCheck)sortNextRecords[i].Parent;

                //if (check.Name == "5C")
                //{

                //}
                //номер выполнения
                int parentCountPerf;
                if (check.LastPerformance != null)
                {
                    parentCountPerf = check.LastPerformance.NumGroup <= 0
                        ? 1
                        : check.LastPerformance.NumGroup;
                }
                else
                {
                    parentCountPerf = 0;
                }

                if (check.Grouping)
                {
                    MaintenanceNextPerformance mnp = sortNextRecords[i] as MaintenanceNextPerformance;
                    if (mnp != null)
                    {
                        parentCountPerf = mnp.PerformanceGroupNum;
                    }
                    else
                    {
                        parentCountPerf += check.NextPerformances.IndexOf(sortNextRecords[i]);
                        parentCountPerf += 1;
                    }
                }
                else
                {
                    parentCountPerf += check.NextPerformances.IndexOf(sortNextRecords[i]);
                    parentCountPerf += 1;
                }

                WorkPackageRecord wpr =
                    openPubWPRecords.Where(r => r.PerformanceNumFromStart == parentCountPerf &&
                                           r.WorkPackageItemType == check.SmartCoreObjectType.ItemId &&
                                           r.DirectiveId == check.ItemId).FirstOrDefault();
                if (wpr != null)
                {
                    WorkPackage wp = openPubWorkPackages.GetItemById(wpr.WorkPakageId);
                    //запись о выполнении блокируется найденым пакетом
                    sortNextRecords[i].BlockedByPackage = wp;
                    //последующие записи о выполнении так же должны быть заблокированы
                    for (int j = i - 1; j >= 0; j--)
                    {
                        //блокировать нужно все рабочие записи, или до первой записи,
                        //заблокированной другим рабочим пакетом
                        if (sortNextRecords[j].BlockedByPackage != null &&
                            sortNextRecords[j].Parent == check ||
                            sortNextRecords[j].Condition != ConditionState.Overdue)
                        {
                            break;
                        }
                        if (sortNextRecords[j].Parent == check)
                        {
                            sortNextRecords[j].BlockedByPackage   = wp;
                            listViewCompliance.Items[j].BackColor = Color.FromArgb(Highlight.GrayLight.Color);
                        }
                    }
                }

                string type        = check.Schedule ? " (Schedule) " : " (Store) ";
                string resource    = check.Resource.ToString();
                string grouping    = check.Grouping ? " (Group)" : "";
                string stringNumGr = (sortNextRecords[i] is MaintenanceNextPerformance
                    ? ((MaintenanceNextPerformance)sortNextRecords[i]).PerformanceGroupNum.ToString()
                    : "N/A") + type + resource + grouping;

                subs = new[]  {
                    stringNumGr,
                    sortNextRecords[i].Title,
                    sortNextRecords[i].PerformanceDate != null
                                       ? UsefulMethods.NormalizeDate((DateTime)sortNextRecords[i].PerformanceDate)
                                       : "N/A",
                    sortNextRecords[i].PerformanceSource.ToString(),
                    "",
                };
                newItem = new ListViewItem(subs)
                {
                    Group     = listViewCompliance.Groups["next"],
                    Tag       = sortNextRecords[i],
                    BackColor = UsefulMethods.GetColor(sortNextRecords[i])
                };

                listViewCompliance.Items.Add(newItem);
            }
            #endregion

            #region Добавление в список записей о произведенных выполнениях
            //и сравнение их с закрытыми рабочими пакетами
            closedWorkPackages.AddRange(allWorkPackagesIncludedTask.Where(wp => wp.Status == WorkPackageStatus.Closed));
            //сбор всех записей рабочих пакетов для удобства фильтрации
            List <WorkPackageRecord> closedWPRecords = new List <WorkPackageRecord>();
            foreach (WorkPackage closedWorkPackage in closedWorkPackages)
            {
                closedWPRecords.AddRange(closedWorkPackage.WorkPakageRecords);
            }

            List <MaintenanceCheckRecordGroup> maintenanceCheckRecordGroups = new List <MaintenanceCheckRecordGroup>();

            foreach (MaintenanceCheckRecord record in lastRecords)
            {
                //Поиск коллекции групп, в которую входят группы с нужными критериями
                //по плану, группировка и основному ресурсу
                if (record.ParentCheck.Grouping)
                {
                    MaintenanceCheckRecordGroup recordGroup = maintenanceCheckRecordGroups
                                                              .FirstOrDefault(g => g.Schedule == record.ParentCheck.Schedule &&
                                                                              g.Grouping == record.ParentCheck.Grouping &&
                                                                              g.Resource == record.ParentCheck.Resource &&
                                                                              g.GroupComplianceNum == record.NumGroup);
                    if (recordGroup != null)
                    {
                        //Коллекция найдена
                        //Поиск в ней группы чеков с нужным типом
                        recordGroup.Records.Add(record);
                    }
                    else
                    {
                        //Коллекции с нужными критериями нет
                        //Созадние и добавление
                        recordGroup =
                            new MaintenanceCheckRecordGroup(record.ParentCheck.Schedule, record.ParentCheck.Grouping,
                                                            record.ParentCheck.Resource, record.NumGroup);
                        recordGroup.Records.Add(record);
                        maintenanceCheckRecordGroups.Add(recordGroup);
                    }
                }
                else
                {
                    MaintenanceCheckRecordGroup recordGroup =
                        new MaintenanceCheckRecordGroup(record.ParentCheck.Schedule, record.ParentCheck.Grouping,
                                                        record.ParentCheck.Resource);
                    recordGroup.Records.Add(record);
                    maintenanceCheckRecordGroups.Add(recordGroup);
                }
            }

            List <object> tempRecords = new List <object>();
            tempRecords.AddRange(maintenanceCheckRecordGroups.ToArray());
            tempRecords.AddRange(_currentAircraft.MaintenanceProgramChangeRecords.ToArray());

            List <object> sortLastRecords =
                tempRecords.OrderByDescending(tr => (tr is MaintenanceCheckRecordGroup
                                                        ? ((MaintenanceCheckRecordGroup)tr).LastGroupComplianceDate
                                                        : tr is AbstractRecord
                                                            ? ((AbstractRecord)tr).RecordDate
                                                            : DateTimeExtend.GetCASMinDateTime()))
                .ToList();
            foreach (object t in sortLastRecords)
            {
                if (t is MaintenanceCheckRecordGroup)
                {
                    MaintenanceCheckRecordGroup mcrg            = (MaintenanceCheckRecordGroup)t;
                    MaintenanceCheckRecord      directiveRecord = mcrg.Records.First();
                    MaintenanceCheck            parentDirective = (MaintenanceCheck)directiveRecord.Parent;
                    newItem = GetListViewItem(mcrg);

                    WorkPackage workPackage =
                        closedWorkPackages.Where(wp => wp.ItemId == directiveRecord.DirectivePackageId).FirstOrDefault();
                    if (workPackage != null)
                    {
                        //запись о выполнении блокируется найденым пакетом
                        directiveRecord.DirectivePackage = workPackage;
                        newItem.BackColor   = Color.FromArgb(Highlight.Grey.Color);
                        newItem.ToolTipText =
                            "Perform of the task:" + parentDirective.Name +
                            "\nadded by Work Package:" +
                            "\n" + directiveRecord.DirectivePackage.Title +
                            "\nTo remove a performance of task, you need to exclude task from this work package," +
                            "\nor delete the work package ";
                    }
                    listViewCompliance.Items.Add(newItem);
                }
                else if (t is MaintenanceProgramChangeRecord)
                {
                    MaintenanceProgramChangeRecord mpcr = (MaintenanceProgramChangeRecord)t;
                    subs = new[]
                    {
                        "N/A",
                        "Changet to " + mpcr.MSG,
                        UsefulMethods.NormalizeDate(mpcr.RecordDate),
                        mpcr.OnLifelength.ToString(),
                        "",
                    };
                    newItem = new ListViewItem(subs)
                    {
                        Group     = listViewCompliance.Groups["last"],
                        Tag       = mpcr,
                        BackColor = Color.FromArgb(Highlight.GrayLight.Color)
                    };

                    listViewCompliance.Items.Add(newItem);
                }
            }
            #endregion

            if (_toolStripMenuItemsWorkPackages != null)
            {
                foreach (ToolStripMenuItem item in _toolStripMenuItemsWorkPackages.DropDownItems)
                {
                    item.Click -= AddToWorkPackageItemClick;
                }

                _toolStripMenuItemsWorkPackages.DropDownItems.Clear();

                foreach (WorkPackage workPackage in _openPubWorkPackages)
                {
                    ToolStripMenuItem item = new ToolStripMenuItem(workPackage.Title);
                    item.Click += AddToWorkPackageItemClick;
                    item.Tag    = workPackage;
                    _toolStripMenuItemsWorkPackages.DropDownItems.Add(item);
                }
            }

            ButtonAdd.Enabled = false;
        }
예제 #24
0
        /// <summary>
        /// Добавляется элемент в таблицу данных
        /// </summary>
        /// <param name="reportedDirective">Добавлямая директива</param>
        /// <param name="destinationDataSet">Таблица, в которую добавляется элемент</param>
        protected virtual void AddDirectiveToDataset(MaintenanceDirective reportedDirective, MaintenanceDirectivesDataSetLatAvia destinationDataSet)
        {
            if (reportedDirective == null)
            {
                return;
            }

            string     status = "";
            Lifelength remain = Lifelength.Null;
            Lifelength used   = Lifelength.Null;

            //string remarks = reportedDirective.LastPerformance != null ? reportedDirective.LastPerformance.Remarks : reportedDirective.Remarks;
            string remarks       = reportedDirective.Remarks;
            string directiveType = reportedDirective.WorkType.ToString();
            double cost          = reportedDirective.Cost;
            double mh            = reportedDirective.ManHours;

            if (reportedDirective.Status == DirectiveStatus.Closed)
            {
                status = "C";
            }
            if (reportedDirective.Status == DirectiveStatus.Open)
            {
                status = "O";
            }
            if (reportedDirective.Status == DirectiveStatus.Repetative)
            {
                status = "R";
            }
            if (reportedDirective.Status == DirectiveStatus.NotApplicable)
            {
                status = "N/A";
            }

            string effectivityDate = UsefulMethods.NormalizeDate(reportedDirective.Threshold.EffectiveDate);
            string kits            = "";
            int    num             = 1;

            foreach (AccessoryRequired kit in reportedDirective.Kits)
            {
                kits += num + ": " + kit.PartNumber + "\n";
                num++;
            }

            //расчет остатка с даты производства и с эффективной даты
            //расчет остатка от выполнения с даты производтсва
            string firstPerformanceString =
                reportedDirective.Threshold.FirstPerformanceSinceNew.ToString();

            if (reportedDirective.LastPerformance != null)
            {
                used.Add(_current);
                used.Substract(reportedDirective.LastPerformance.OnLifelength);
                if (!reportedDirective.Threshold.RepeatInterval.IsNullOrZero())
                {
                    used.Resemble(reportedDirective.Threshold.RepeatInterval);
                }
                else if (!reportedDirective.Threshold.FirstPerformanceSinceNew.IsNullOrZero())
                {
                    used.Resemble(reportedDirective.Threshold.FirstPerformanceSinceNew);
                }

                if (reportedDirective.NextPerformanceSource != null && !reportedDirective.NextPerformanceSource.IsNullOrZero())
                {
                    remain.Add(reportedDirective.NextPerformanceSource);
                    remain.Substract(_current);
                    remain.Resemble(reportedDirective.Threshold.RepeatInterval);
                }
            }


            destinationDataSet.ItemsTable.AddItemsTableRow(reportedDirective.TaskCardNumber, reportedDirective.TaskNumberCheck, reportedDirective.Description,
                                                           firstPerformanceString,
                                                           reportedDirective.ParentComponentDirective?.RepeatInterval != null ? reportedDirective.ParentComponentDirective?.RepeatInterval.Hours?.ToString() : "*",
                                                           reportedDirective.ParentComponentDirective?.RepeatInterval != null ? reportedDirective.ParentComponentDirective?.RepeatInterval.Cycles?.ToString() : "*",
                                                           reportedDirective.ParentComponentDirective?.RepeatInterval != null ? reportedDirective.ParentComponentDirective?.RepeatInterval.Days?.ToString() : "*",
                                                           reportedDirective.ParentComponentDirective?.LastPerformance != null ? reportedDirective.ParentComponentDirective?.LastPerformance.OnLifelength.Hours?.ToString() : "*",
                                                           reportedDirective.ParentComponentDirective?.LastPerformance != null ? reportedDirective.ParentComponentDirective?.LastPerformance.OnLifelength.Cycles?.ToString() : "*",
                                                           reportedDirective.ParentComponentDirective?.LastPerformance != null ? reportedDirective.ParentComponentDirective?.LastPerformance.RecordDate.ToString("dd.MM.yyyy") : "*",
                                                           reportedDirective.ParentComponentDirective?.NextPerformance != null ? reportedDirective.ParentComponentDirective?.NextPerformance.PerformanceSource.Hours.ToString() : "*",
                                                           reportedDirective.ParentComponentDirective?.NextPerformance != null ? reportedDirective.ParentComponentDirective?.NextPerformance.PerformanceSource.Cycles.ToString() : "*",
                                                           reportedDirective.ParentComponentDirective?.NextPerformance != null ? reportedDirective.ParentComponentDirective?.NextPerformance.PerformanceDate.Value.ToString("dd.MM.yyyy") : "*",
                                                           reportedDirective.ParentComponentDirective?.Remains != null ? reportedDirective.ParentComponentDirective?.Remains.Hours.ToString() : "*",
                                                           reportedDirective.ParentComponentDirective?.Remains != null ? reportedDirective.ParentComponentDirective?.Remains.Cycles.ToString() : "*",
                                                           reportedDirective.ParentComponentDirective?.Remains != null ? reportedDirective.ParentComponentDirective?.Remains.Days.ToString() : "*",
                                                           reportedDirective.CompnentSN,
                                                           reportedDirective.CompnentPN
                                                           );
        }
예제 #25
0
        private ListViewItem GetListViewItem(MaintenanceCheckRecordGroup grouping)
        {
            string name              = "N/A";
            string type              = "N/A";
            string resource          = "N/A";
            string group             = "N/A";
            string num               = "N/A";
            string recordDate        = "N/A";
            string performanceSource = "N/A";
            string remarksString     = "N/A";
            Color  backColor         = Color.White;

            if (grouping.Records.Count > 0)
            {
                grouping.Sort();

                MaintenanceCheckRecord mcr = grouping.LastOrDefault();
                MaintenanceCheck       mc  = grouping.GetMaxIntervalCheck();

                type      = mc.Schedule ? " (Schedule) " : " (Store) ";
                resource  = mc.Resource.ToString();
                group     = mc.Grouping ? " (Group)" : "";
                backColor = mc.Schedule ? Color.White : Color.Gainsboro;

                if (mcr != null)
                {
                    num  = mc.Grouping ? mcr.NumGroup.ToString() : "N/A";
                    name = _currentAircraft != null && _currentAircraft.MaintenanceProgramCheckNaming
                                        ? (!string.IsNullOrEmpty(grouping.First().ComplianceCheckName)
                                               ? mcr.ComplianceCheckName
                                               : mc.Name)
                                        : mc.Name;
                    recordDate        = UsefulMethods.NormalizeDate(mcr.RecordDate);
                    performanceSource = mcr.OnLifelength.ToRepeatIntervalsFormat();
                    remarksString     = mcr.Remarks;

                    if (mc.Grouping)
                    {
                        MaintenanceProgramChangeRecord mpcr = mc.ParentAircraft != null
                            ? mc.ParentAircraft.MaintenanceProgramChangeRecords.
                                                              GetLastKnownRecord(Convert.ToDateTime(mcr.RecordDate))
                            : null;

                        if (mpcr == null || mpcr.MSG < MSG.MSG3)
                        {
                            var complianceItems = from compliance in grouping
                                                  orderby compliance.OnLifelength.Hours descending
                                                  select compliance;
                            name += " (" + complianceItems.Aggregate("", (current, compliance) => current + (compliance.ParentCheck.Name + " ")) + ")";
                        }
                    }
                }
            }

            ListViewItem listViewItem = new ListViewItem(num + type + resource + group)
            {
                Tag       = grouping.ToList(),
                Group     = listViewCompliance.Groups["last"],
                BackColor = backColor
            };

            listViewItem.SubItems.Add(name);
            listViewItem.SubItems.Add(recordDate);
            listViewItem.SubItems.Add(performanceSource);
            listViewItem.SubItems.Add(remarksString);
            return(listViewItem);
        }
예제 #26
0
        /// <summary>
        /// Заполняет краткую информацию о директиве
        /// </summary>
        public void UpdateInformation()
        {
            if ((currentDirective == null) || !(currentDirective.Parent is BaseDetail))
            {
                return;
            }
            BaseDetail inspectedDetail = (BaseDetail)currentDirective.Parent;

            labelDateAsOfValue.Text      = DateTime.Today.ToString(new TermsProvider()["DateFormat"].ToString());
            labelDirectiveValue.Text     = currentDirective.Title + " for";
            labelDescriptionValue.Text   = currentDirective.Description;
            labelEffectiveDateValue.Text = currentDirective.EffectivityDate.ToString(new TermsProvider()["DateFormat"].ToString());
            if (currentDirective.Condition == DirectiveConditionState.NotSatisfactory)
            {
                labelRemains.Text = "Overdue:";
            }
            else
            {
                labelRemains.Text = "Remains:";
            }
            if (currentDirective.Closed)
            {
                labelStatusValue.Text  = "Closed";
                labelRemainsValue.Text = "";
            }
            else
            {
                if (currentDirective.RepeatedlyPerform && currentDirective.FirstPerformOccured)
                {
                    labelStatusValue.Text = "Repeatable";
                }
                else
                {
                    labelStatusValue.Text = "Open";
                }
                //labelRemainsValue.Text = currentDirective.RemainsNextPerformance().ToComplianceItemStringFull();
                labelRemainsValue.Text = currentDirective.RemainsNextPerformance().ToComplianceItemString();
            }

            linkDetailInfoFirst.Text  = inspectedDetail.ToString();
            linkDetailInfoSecond.Text = inspectedDetail.ToString();

            labelDateLast.Text     = "";
            labelTsnCsnLast.Text   = "";
            labelWorktypeLast.Text = "";
            labelRemarksLast.Text  = "";
            labelDateNext.Text     = "";
            labelTsnCsnNext.Text   = "";
            labelWorktypeNext.Text = "";
            labelRemarksNext.Text  = "";
            if (currentDirective.LastPerformance != null)
            {
                labelDateLast.Text     = UsefulMethods.NormalizeDate(currentDirective.LastPerformance.RecordDate);
                labelWorktypeLast.Text = currentDirective.LastPerformance.RecordType.FullName;
                labelRemarksLast.Text  = currentDirective.LastPerformance.Description;
                if (currentDirective.LastPerformance.Lifelength != Lifelength.NullLifelength && (currentDirective.LastPerformance.Lifelength.Hours.TotalHours != 0 && currentDirective.LastPerformance.Lifelength.Cycles != 0))
                {
                    labelTsnCsnLast.Text = currentDirective.LastPerformance.Lifelength.ToComplianceItemString();
                }
            }
            if (!currentDirective.Closed)
            {
                labelDateNext.Text = UsefulMethods.NormalizeDate(currentDirective.GetApproximateDate());
                if (currentDirective.NextWorkType != null)
                {
                    labelWorktypeNext.Text = currentDirective.NextWorkType.FullName;
                }
                if (currentDirective.NextPerformance != null)
                {
                    labelTsnCsnNext.Text = currentDirective.NextPerformance.ToComplianceItemString();
                }
            }
            labelDetailTsnCsnValue.Text = inspectedDetail.Lifelength.ToComplianceItemString();
            if (CurrentBaseDetail == null)
            {
                return;
            }
            linkDirectiveStatus.Text = BackLinkText;
        }
        /// <summary>
        /// Добавляется элемент в таблицу данных
        /// </summary>
        /// <param name="reportedDirective">Добавлямая директива</param>
        /// <param name="destinationDataSet">Таблица, в которую добавляется элемент</param>
        protected override void AddDirectiveToDataset(MaintenanceDirective reportedDirective, MaintenanceDirectivesDataSet destinationDataSet)
        {
            if (reportedDirective == null)
            {
                return;
            }

            string     status = "";
            Lifelength used   = Lifelength.Null;

            //string remarks = reportedDirective.LastPerformance != null ? reportedDirective.LastPerformance.Remarks : reportedDirective.Remarks;
            string remarks       = reportedDirective.Remarks;
            string directiveType = reportedDirective.WorkType.ShortName;
            double cost          = reportedDirective.Cost;
            double mh            = reportedDirective.ManHours;

            if (reportedDirective.Status == DirectiveStatus.Closed)
            {
                status = "C";
            }
            if (reportedDirective.Status == DirectiveStatus.Open)
            {
                status = "O";
            }
            if (reportedDirective.Status == DirectiveStatus.Repetative)
            {
                status = "R";
            }
            if (reportedDirective.Status == DirectiveStatus.NotApplicable)
            {
                status = "N/A";
            }

            string effectivityDate = UsefulMethods.NormalizeDate(reportedDirective.Threshold.EffectiveDate);
            string kits            = "";
            int    num             = 1;

            foreach (AccessoryRequired kit in reportedDirective.Kits)
            {
                kits += num + ": " + kit.PartNumber + "\n";
                num++;
            }

            //расчет остатка с даты производства и с эффективной даты
            //расчет остатка от выполнения с даты производтсва
            string firstPerformanceString    = "";
            string repeatPerformanceToString = reportedDirective.Threshold.RepeatPerformanceToStrings();

            if (reportedDirective.LastPerformance != null)
            {
                used.Add(Current);
                used.Substract(reportedDirective.LastPerformance.OnLifelength);
                if (!reportedDirective.Threshold.RepeatInterval.IsNullOrZero())
                {
                    used.Resemble(reportedDirective.Threshold.RepeatInterval);
                }
                else if (!reportedDirective.Threshold.FirstPerformanceSinceNew.IsNullOrZero())
                {
                    used.Resemble(reportedDirective.Threshold.FirstPerformanceSinceNew);
                }
            }
            else
            {
                firstPerformanceString = reportedDirective.Threshold.FirstPerformanceToStrings();
            }

            destinationDataSet.ItemsTable.AddItemsTableRow(reportedDirective.Applicability,
                                                           remarks,
                                                           reportedDirective.HiddenRemarks,
                                                           reportedDirective.Description.Replace("\r\n", " "),
                                                           reportedDirective.TaskNumberCheck,
                                                           reportedDirective.Access,
                                                           directiveType,
                                                           status,
                                                           effectivityDate,
                                                           firstPerformanceString,
                                                           reportedDirective.LastPerformance != null ? reportedDirective.LastPerformance.ToStrings() : "",
                                                           reportedDirective.NextPerformance != null ? reportedDirective.NextPerformance.ToStrings() : "",
                                                           reportedDirective.Remains.ToStrings(),
                                                           reportedDirective.Condition.ToString(),
                                                           mh,
                                                           cost,
                                                           kits,
                                                           reportedDirective.Zone,
                                                           reportedDirective.ATAChapter != null ? reportedDirective.ATAChapter.ShortName : "",
                                                           reportedDirective.ATAChapter != null ? reportedDirective.ATAChapter.FullName : "",
                                                           reportedDirective.TaskCardNumber,
                                                           reportedDirective.Program.ToString(),
                                                           repeatPerformanceToString,
                                                           used.ToStrings(),
                                                           reportedDirective.MaintenanceCheck != null ? reportedDirective.MaintenanceCheck.ToString() : "N/A");
        }
예제 #28
0
        private void UpdateNotify(List <MTOPCheck> maintenanceChecks)
        {
            listViewNotify.Items.Clear();

            ListViewItem newItem;

            string[] subs;

            foreach (var check in maintenanceChecks)
            {
                var nextPerformance = check.NextPerformance;
                listViewNotify.Groups.Add(check.CheckType.FullName, check.CheckType.FullName);

                if (check.PerformanceRecords.Count > 0)
                {
                    var lastCompliance = check.PerformanceRecords.OrderByDescending(i => i.ItemId).First();
                    var lastGroup      = lastCompliance.Parent.IsZeroPhase ? $"0{lastCompliance.GroupName}" : lastCompliance.GroupName.ToString();
                    var checkGroup     = check.IsZeroPhase ? $"0{check.Group}" : check.Group.ToString();


                    subs = new[]  {
                        check.Name,
                        UsefulMethods.NormalizeDate(lastCompliance.RecordDate),
                        lastCompliance.CalculatedPerformanceSource.ToRepeatIntervalsFormat(),
                        lastGroup,
                        $"{lastGroup}{lastCompliance.CheckName}",
                        nextPerformance?.PerformanceDate != null?UsefulMethods.NormalizeDate(nextPerformance.PerformanceDate.Value) : "",
                            nextPerformance?.PerformanceSource.ToRepeatIntervalsFormat(),
                            checkGroup,
                            $"{checkGroup}{check.Name}",
                            check.NextPerformance?.Remains.ToString()
                    };

                    newItem = new ListViewItem(subs)
                    {
                        Tag   = check,
                        Group = listViewNotify.Groups[check.CheckType.FullName]
                    };
                    listViewNotify.Items.Add(newItem);
                }
                else
                {
                    string perfDate = "";
                    if (nextPerformance?.PerformanceDate != null)
                    {
                        perfDate = UsefulMethods.NormalizeDate(nextPerformance.PerformanceDate.Value);
                    }

                    var group = "";
                    if (check.NextPerformance != null)
                    {
                        group = check.NextPerformance.ParentCheck.IsZeroPhase ? $"0{check.NextPerformance?.Group}" : check.NextPerformance?.Group.ToString();
                    }


                    subs = new[]  {
                        check.Name,
                        "",
                        "",
                        "",
                        "",
                        perfDate,
                        nextPerformance?.PerformanceSource.ToRepeatIntervalsFormat(),
                        group,
                        $"{group}{check.Name}",
                        check.NextPerformance?.Remains.ToString()
                    };

                    newItem = new ListViewItem(subs)
                    {
                        Tag   = check,
                        Group = listViewNotify.Groups[check.CheckType.FullName]
                    };
                    listViewNotify.Items.Add(newItem);
                }
            }
        }
예제 #29
0
        ///<summary>
        ///</summary>
        public void Save()
        {
            foreach (CompliancePDFItem pdFitem in flowLayoutPanelContainer.Controls)
            {
                pdFitem.ApplyChanges();

                MaintenanceCheckRecord lastPerformance;

                if (_isEdit == false)
                {
                    lastPerformance = new MaintenanceCheckRecord {
                        ParentCheck = pdFitem.Check
                    };
                    if (pdFitem.Check.Grouping)
                    {
                        MaintenanceNextPerformance mnp =
                            _performances.FirstOrDefault(p => p.Parent != null && p.Parent.ItemId == pdFitem.Check.ItemId);
                        lastPerformance.PerformanceNum = mnp != null ? mnp.PerformanceNum : _numGroup;
                    }
                    else
                    {
                        lastPerformance.PerformanceNum = _numGroup;
                    }
                    lastPerformance.NumGroup = _numGroup;
                    lastPerformance.CalculatedPerformanceSource =
                        lastPerformance.ParentCheck.Interval * lastPerformance.PerformanceNum;
                }
                else
                {
                    lastPerformance = pdFitem.Record;
                }

                lastPerformance.AttachedFile        = pdFitem.AttachedFile;
                lastPerformance.ComplianceCheckName = textBoxCheckName.Text.Trim();
                lastPerformance.RecordDate          = dateTimePicker1.Value;
                lastPerformance.OnLifelength        = lifelengthViewer_LastCompliance.Lifelength;
                lastPerformance.IsControlPoint      = checkBoxControlPoint.Checked;
                lastPerformance.Remarks             = textBox_Remarks.Text.Trim();

                try
                {
                    GlobalObjects.PerformanceCore.RegisterPerformance(pdFitem.Check, lastPerformance);

                    IEnumerable <DirectiveRecord> bindedDirectivesRecord = pdFitem.BindDirectivesRecords;
                    foreach (DirectiveRecord record in bindedDirectivesRecord)
                    {
                        if (record.ItemId > 0 && record.IsDeleted)
                        {
                            GlobalObjects.PerformanceCore.Delete(record);
                        }
                        else
                        {
                            record.MaintenanceCheckRecordId = lastPerformance.ItemId;
                            record.OnLifelength             = GlobalObjects.CasEnvironment.Calculator.GetFlightLifelengthOnStartOfDay(_currentAircraft, record.RecordDate);
                            record.Remarks = string.IsNullOrEmpty(lastPerformance.Remarks)
                                                 ? "This performance added by " + pdFitem.Check.Name + " on " +
                                             UsefulMethods.NormalizeDate(lastPerformance.RecordDate)
                                                 : lastPerformance.Remarks;

                            GlobalObjects.CasEnvironment.Manipulator.Save(record, false);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Program.Provider.Logger.Log("Error while save performance for maintenance check", ex);

                    break;
                }
            }
        }
예제 #30
0
        /// <summary>
        /// Добавляется элемент в таблицу данных
        /// </summary>
        /// <param name="componentобавляемый агрегат</param>
        /// <param name="previousNumber">Порядковый номер агрегата</param>
        /// <param name="destinationDataSet">Таблица, в которую добавляется элемент</param>
        protected virtual void AddDetailToDataset(Component component, ref int previousNumber, DetailListDataSet destinationDataSet)
        {
            string atachapter;
            string componentNumber;
            string atachapterfull;
            string partNumber;
            string description;
            string serialNumber;
            string positionNumber;
            string maintanceType;
            string instalationDate;

            AtaChapter ata = component.ATAChapter;

            atachapter      = ata.ShortName;
            componentNumber = (previousNumber++).ToString();
            atachapterfull  = ata.FullName;
            partNumber      = component.PartNumber;
            description     = component.Description;
            serialNumber    = component.SerialNumber;
            positionNumber  = component.TransferRecords.Count > 0
                ? component.TransferRecords.GetLast().Position : "";
            maintanceType   = "";//((Detail) detail).MaintenanceType.ShortName;
            instalationDate = component.TransferRecords.Count > 0
                ? UsefulMethods.NormalizeDate(component.TransferRecords.GetLast().TransferDate) : "";

            string complianceTSN      = "";
            string complianceDate     = "";
            string complianceWorkType = "";

            /*       if ((Deta)detail. != null)
             *     {
             *         complianceDate = UsefulMethods.NormalizeDate(detail.Limitation.LastPerformance.RecordDate);
             *         if (complianceDate != "")
             *             complianceTSN = lifelengthFormatter.GetHoursData(detail.Limitation.LastPerformance.Lifelength, " hrs\r\n") +
             *                             lifelengthFormatter.GetCyclesData(detail.Limitation.LastPerformance.Lifelength, " cyc\r\n");
             *         else
             *             complianceTSN = lifelengthFormatter.GetData(detail.Limitation.LastPerformance.Lifelength, " hrs\r\n", " cyc\r\n", " day");
             *         complianceWorkType = detail.Limitation.LastPerformance.RecordType.ShortName;
             *     }*/

            string nextTSN      = "";
            string nextDate     = "";
            string nextRemains  = "";
            string nextWorkType = "";

/*
 *          nextDate = UsefulMethods.NormalizeDate(detail.Limitation.NextDate);
 *          nextRemains = lifelengthFormatter.GetData(detail.Limitation.LeftTillNextPerformance, " hrs\r\n", " cyc\r\n", " day");
 *          if (detail.Limitation.NextPerformance != null)
 *          {
 *              if (nextDate != "")
 *                  nextTSN = lifelengthFormatter.GetHoursData(detail.Limitation.NextPerformance, " hrs\r\n") +
 *                            lifelengthFormatter.GetCyclesData(detail.Limitation.NextPerformance, " cyc\r\n");
 *              else
 *                  nextTSN = lifelengthFormatter.GetData(detail.Limitation.NextPerformance, " hrs\r\n", " cyc\r\n", " day");
 *          }
 *          if (detail.Limitation.NextWorkType != null)
 *          {
 *              nextWorkType = detail.Limitation.NextWorkType.ShortName;
 *          }
 */

            GlobalObjects.PerformanceCalculator.GetNextPerformance(component);

            string condition = component.Condition.GetHashCode().ToString();


            destinationDataSet.ItemsTable.AddItemsTableRow(componentNumber,
                                                           atachapter, atachapterfull, partNumber, description,
                                                           serialNumber, positionNumber,
                                                           maintanceType,
                                                           instalationDate,
                                                           complianceTSN,
                                                           complianceDate,
                                                           complianceWorkType, nextTSN,
                                                           nextDate,
                                                           nextRemains,
                                                           nextWorkType, condition, "", "", "", "", "", "", "", "", "", "");
        }