Пример #1
0
 /// <summary>
 /// Создает форму для добавления ActualStateRecord
 /// </summary>
 /// <param name="details">Агрегаты, к которым добавляются записи</param>
 public ActualStateRecordForm(List <Detail> details)
 {
     mode          = ScreenMode.Add;
     parentDetails = details;
     currentRecord = new ActualStateRecord();
     InitializeComponent();
 }
Пример #2
0
        /// <summary>
        /// Возвращает значение, показывающее были ли изменения в данном элементе управления
        /// </summary>
        /// <returns></returns>
        public bool GetChangeStatus()
        {
            if (_currentBaseComponent == null)
            {
                return(false);
            }

            TransferRecord    lastTransfer = _currentBaseComponent.TransferRecords.GetLast();
            ActualStateRecord acr          = lastTransfer != null
                                        ? _currentBaseComponent.ActualStateRecords[lastTransfer.TransferDate]
                                        : null;

            return((comboBoxEngineModel.SelectedItem?.ItemId != _currentBaseComponent.Model?.ItemId) ||
                   (textBoxManufacturer.Text != _currentBaseComponent.Manufacturer) ||
                   (textBoxPosition.Text != _currentBaseComponent.PositionNumber) ||
                   (textBoxSerialNumber.Text != _currentBaseComponent.SerialNumber) ||
                   (textBoxPartialNumber.Text != _currentBaseComponent.PartNumber) ||
                   (dateTimePickerManufactureDate.Value != _currentBaseComponent.ManufactureDate) ||
                   (!lifelengthViewerStart.Lifelength.IsEqual(_currentBaseComponent.StartLifelength)) ||
                   (dateTimePickerStart.Value != _currentBaseComponent.StartDate) ||
                   (!lifelengthViewerLifeLimit.Lifelength.IsEqual(_currentBaseComponent.LifeLimit)) ||
                   (!lifelengthViewerWarranty.Lifelength.IsEqual(_currentBaseComponent.Warranty)) ||
                   (lastTransfer != null
                                ? (lastTransfer.Position != textBoxPosition.Text)
                                : (textBoxPosition.Text != "")) ||
                   (lastTransfer != null
                                ? (lastTransfer.TransferDate != dateTimePickerInstallation.Value)
                                : (dateTimePickerInstallation.Value != DateTimeExtend.GetCASMinDateTime())));
        }
Пример #3
0
 /// <summary>
 /// Создает форму для добавления ActualStateRecord
 /// </summary>
 /// <param name="detail">Агрегат, к которому добавляется запись</param>
 public ActualStateRecordForm(AbstractDetail detail)
 {
     mode          = ScreenMode.Add;
     parentDetail  = detail;
     currentRecord = new ActualStateRecord();
     InitializeComponent();
 }
Пример #4
0
 ///<summary>
 ///</summary>
 ///<param name="actualStateRecord"></param>
 public ActualStateDialog(ActualStateRecord actualStateRecord)
     : this()
 {
     _currentActualStateRecord = actualStateRecord;
     _currentComponent         = _currentActualStateRecord.ParentComponent;
     UpdateInformation();
 }
Пример #5
0
 /// <summary>
 /// Создает форму для редактирования ActualStateRecord
 /// </summary>
 /// <param name="detailRecord">Актуальное состояние агрегата</param>
 public ActualStateRecordForm(ActualStateRecord detailRecord)
 {
     mode          = ScreenMode.Edit;
     parentDetail  = (AbstractDetail)detailRecord.Parent;
     currentRecord = detailRecord;
     InitializeComponent();
     UpdateInformation();
 }
 public ActualStateRecordView(ActualStateRecord source)
 {
     if (source == null)
     {
         return;
     }
     Id               = source.Id;
     FlightRegimeId   = source.FlightRegimeId;
     Remarks          = source.Remarks;
     OnLifelength     = Lifelength.ConvertFromByteArray(source.OnLifelengthByte);
     RecordDate       = source.RecordDate;
     WorkRegimeTypeId = source.WorkRegimeTypeId;
     ComponentId      = source.ComponentId.Value;
 }
Пример #7
0
        ///<summary>
        ///</summary>
        ///<param name="currentComponent/param>
        public ActualStateDialog(Component currentComponent)
            : this()
        {
            if (currentComponent == null)
            {
                throw new ArgumentNullException("currentComponent", "must be not null");
            }
            _currentComponent = currentComponent;

            _currentActualStateRecord = new ActualStateRecord {
                RecordDate = _currentComponent.ManufactureDate.Date
            };

            UpdateInformation();
        }
 /// <summary>
 /// Сохранаяет данные заданного агрегата
 /// </summary>
 /// <param name="detail">Агрегат</param>
 public bool SaveData(AbstractDetail detail)
 {
     for (int i = 0; i < existPrformances.Count; i++)
     {
         if (!existPrformances[i].SaveData())
         {
             return(false);
         }
     }
     for (int i = 0; i < addedPerformances.Count; i++)
     {
         if (addedPerformances[i].Interval != Lifelength.NullLifelength)
         {
             DetailDirective detailDirective = addedPerformances[i].GetDetailDirective();
             detail.AddDetailDirective(detailDirective);
             if (addedPerformances[i].AddActualStateRecordToDetail)
             {
                 ActualStateRecord record = new ActualStateRecord(addedPerformances[i].ComponentLastPerformance);
                 record.RecordDate = addedPerformances[i].RecordDate;
                 detail.AddRecord(record);
             }
             if (addedPerformances[i].AddActualStateRecordToAircraft)
             {
                 ActualStateRecord record = new ActualStateRecord(addedPerformances[i].AircraftLastPerformance);
                 record.RecordDate = addedPerformances[i].RecordDate;
                 if (detail is BaseDetail)
                 {
                     ((BaseDetail)detail).ParentAircraft.AddRecord(record);
                 }
                 else
                 {
                     ((Aircraft)detail.Parent.Parent).AddRecord(record);
                 }
             }
         }
     }
     if (currentDetail != null)
     {
         UpdateInformation();
     }
     return(true);
 }
Пример #9
0
        /// <summary>
        /// Данные работы обновляются по введенным значениям
        /// </summary>
        private bool SaveData()
        {
            if (dateTimePicker1.Value.Date > DateTime.Today.Date)
            {
                return(false);
            }
            if (comboBoxCategories.SelectedIndex == -1)
            {
                MessageBox.Show(@"You did not select a new category for detail",
                                new GlobalTermsProvider()["SystemName"].ToString(), MessageBoxButtons.OK,
                                MessageBoxIcon.Exclamation);
                return(false);
            }
            if (_currentComponent.ChangeLLPCategoryRecords.GetLast() != null &&
                _currentComponent.ChangeLLPCategoryRecords[dateTimePicker1.Value] != null &&
                _currentComponent.ChangeLLPCategoryRecords[dateTimePicker1.Value].ItemId != _currentRecord.ItemId)
            {
                MessageBox.Show(@"On this day there is a record of the change of category.\n
								  Change record date"                                ,
                                new GlobalTermsProvider()["SystemName"].ToString(), MessageBoxButtons.OK,
                                MessageBoxIcon.Exclamation);
                return(false);
            }

            if (lifelengthViewer_LastCompliance.Lifelength.Days == null)
            {
                if (_currentRecord.ParentComponent != null)
                {
                    lifelengthViewer_LastCompliance.Lifelength.Days = GlobalObjects.CasEnvironment.Calculator.GetFlightLifelengthOnEndOfDay
                                                                          (_currentRecord.ParentComponent, dateTimePicker1.Value).Days;
                }
            }
            _currentRecord.ToCategory   = ((LLPLifeLimitCategory)comboBoxCategories.SelectedItem);
            _currentRecord.RecordDate   = dateTimePicker1.Value;
            _currentRecord.Remarks      = Remarks;
            _currentRecord.OnLifelength = lifelengthViewer_LastCompliance.Lifelength;


            var actualStateRecord = new ActualStateRecord
            {
                ComponentId  = _currentComponent.ItemId,
                OnLifelength = lifelengthViewer_LastCompliance.Lifelength,
                RecordDate   = dateTimePicker1.Value,
                Remarks      = $"{(LLPLifeLimitCategory)comboBoxCategories.SelectedItem} Category"
            };

            if (fileControl.GetChangeStatus())
            {
                fileControl.ApplyChanges();
                _currentRecord.AttachedFile = fileControl.AttachedFile;
            }
            try
            {
                GlobalObjects.ComponentCore.RegisterChangeLLPCategory(_currentComponent, _currentRecord);
                GlobalObjects.ComponentCore.RegisterActualState(_currentComponent, actualStateRecord);
            }
            catch (Exception ex)
            {
                Program.Provider.Logger.Log("Error while saving data", ex);
                return(false);
            }
            return(true);
        }
Пример #10
0
        private void ButtonDelete_Click(object sender, EventArgs e)
        {
            if (listViewTransferedDetails.SelectedItems.Count == 0)
            {
                return;
            }

            ComponentCollection             removedComponents   = new ComponentCollection();
            ComponentCollection             installedComponents = new ComponentCollection(_installedComponents.ToArray());
            List <ReplaceComponentFormItem> replaceDetailFormItems;

            foreach (ListViewItem item in listViewTransferedDetails.SelectedItems)
            {
                if (item.Group == listViewTransferedDetails.Groups[0])
                {
                    Component component = (Component)item.Tag;
                    removedComponents.Add(component);
                }
            }

            if (removedComponents.Count == 0)
            {
                return;
            }

            replaceDetailFormItems = new List <ReplaceComponentFormItem>();
            foreach (Component item in removedComponents)
            {
                var newItem = new ReplaceComponentFormItem(item, null,
                                                           _removedTransfers.GetRecordByComponentId(item.ItemId), null, _parentType);
                replaceDetailFormItems.Add(newItem);

                if (installedComponents.Count == 0)
                {
                    newItem.UpdateInformation(false);
                    continue;
                }

                foreach (Component installedItem in installedComponents)
                {
                    //проверка по сходству ID
                    //проверка по сходству названия
                    if (installedItem.ItemId == item.ItemId ||
                        installedItem.Description.ToUpper() == item.Description.ToUpper())
                    {
                        //Если ID идентичны, то эта деталь сначала была перемещена куда-то,
                        //а потом обратно на самолет

                        //если название идентично, значит эта могла быть направлена на самолет
                        //для замены снятой
                        newItem.ReplacedByComponent      = installedItem;
                        newItem.ReplacedByDetailTransfer = installedItem.TransferRecords.GetLast();

                        //удаление элемента из коллекции, что бы он не попал в результат дважды
                        installedComponents.Remove(installedItem);
                        break;
                    }
                }
                newItem.UpdateInformation(false);
            }

            var form = new ReplaceComponentForm(_removedComponents, _installedComponents, replaceDetailFormItems.ToArray(), _parentType);

            form.UpdateLabels(false);

            TopMost = false;             //что бы данное онко не перекрывало окно диалога
            form.ShowDialog();
            TopMost = true;
            //Если изменения не были произведены, то просто возвращаемся из данной функции
            if (form.DialogResult == DialogResult.Cancel)
            {
                return;
            }
            //иначе производится замена/перемещение компонентов
            List <ReplaceComponentFormItem> replacedItems = new List <ReplaceComponentFormItem>(form.GetReplacedItems());

            foreach (ReplaceComponentFormItem replacedItem in replacedItems)
            {
                if (replacedItem.ParentComponent != null)
                {
                    TransferRecord record = _removedTransfers.GetRecordByComponentId(replacedItem.ParentComponent.ItemId);
                    record.PODR = true;

                    if (replacedItem.ReplacedByComponent != null)
                    {
                        record.ReplaceComponentId        = replacedItem.ReplacedByComponent.ItemId;
                        record.IsReplaceComponentRemoved = false;
                    }

                    GlobalObjects.CasEnvironment.NewKeeper.Save(record);

                    BaseComponent from = GlobalObjects.ComponentCore.GetBaseComponentById(record.FromBaseComponentId);
                    //уменьшение необходимого кол-ва деталей родительского компонента
                    //сохранение родительского компонента
                    if (from != null)
                    {
                        from.ComponentCount--;
                        GlobalObjects.ComponentCore.Save(from);
                    }
                    _removedComponents.Remove(replacedItem.ParentComponent);
                    _removedTransfers.Remove(record);
                }

                if (replacedItem.ReplacedByComponent != null)
                {
                    ActualStateRecord actual =
                        replacedItem.ReplacedByComponent.ActualStateRecords[replacedItem.ReplacedByComponent.TransferRecords.GetLast().StartTransferDate];

                    actual.RecordDate   = replacedItem.ReplacedByDate;
                    actual.OnLifelength = GlobalObjects.CasEnvironment.Calculator.GetFlightLifelengthOnEndOfDay(replacedItem.ReplacedByComponent, DateTime.Now);//TODO:(Evgenii Babak) пересмотреть подход, наработка считается на начало дня, а в метод передаем DateTime.Now(может быть и началом дня)
                    GlobalObjects.CasEnvironment.NewKeeper.Save(actual);

                    replacedItem.ReplacedByComponent.TransferRecords.GetLast().DODR         = true;
                    replacedItem.ReplacedByComponent.TransferRecords.GetLast().TransferDate =
                        replacedItem.ReplacedByDate;
                    //увеличение необходимого кол-ва деталей родительского компонента
                    //сохранение родительского компонента
                    if (replacedItem.ReplacedByComponent.ParentBaseComponent != null)
                    {
                        replacedItem.ReplacedByComponent.ParentBaseComponent.ComponentCount++;
                        GlobalObjects.ComponentCore.Save(replacedItem.ReplacedByComponent.ParentBaseComponent);
                    }
                    GlobalObjects.CasEnvironment.NewKeeper.Save(replacedItem.ReplacedByComponent.TransferRecords.GetLast());
                    _installedComponents.Remove(replacedItem.ReplacedByComponent);
                    TransferRecord record = _installedTransfers.GetRecordByComponentId(replacedItem.ReplacedByComponent.ItemId);
                    if (record != null)
                    {
                        _installedTransfers.Remove(record);
                    }
                }
            }
            InvokeButtonDeleteClick();

            UpdateInformation();
        }
        ///<summary>
        ///</summary>
        public void UpdateInformation()
        {
            if (_currentComponentDirective == null)
            {
                return;
            }

            if (_currentComponentDirective.ParentComponent != null && _currentComponentDirective.ParentComponent is BaseComponent)
            {
                BaseComponent inspectedBaseComponent = (BaseComponent)_currentComponentDirective.ParentComponent;

                string baseDetailTypeString = inspectedBaseComponent.BaseComponentType.ToString();
                labelCompntTCSN.Text = baseDetailTypeString;
            }

            imageLinkLabelStatus.Text       = _currentComponentDirective.DirectiveType.ToString();
            labelFirstPerformanceValue.Text = "n/a";
            if (_currentComponentDirective.Threshold.FirstPerformanceSinceNew != null &&
                !_currentComponentDirective.Threshold.FirstPerformanceSinceNew.IsNullOrZero())
            {
                labelFirstPerformanceValue.Text = "s/n: " + _currentComponentDirective.Threshold.FirstPerformanceSinceNew;
            }

            if (_currentComponentDirective.Threshold.FirstPerformanceSinceEffectiveDate != null &&
                !_currentComponentDirective.Threshold.FirstPerformanceSinceEffectiveDate.IsNullOrZero())
            {
                if (labelFirstPerformanceValue.Text != "n/a")
                {
                    labelFirstPerformanceValue.Text += " or ";
                }
                else
                {
                    labelFirstPerformanceValue.Text = "";
                }
                labelFirstPerformanceValue.Text += "s/e.d: " + _currentComponentDirective.Threshold.FirstPerformanceSinceEffectiveDate;
            }
            labelRptIntervalValue.Text   = _currentComponentDirective.Threshold.RepeatInterval.ToString();
            labelKitValue.Text           = _currentComponentDirective.KitRequired;
            labelManHoursValue.Text      = _currentComponentDirective.ManHours.ToString();
            labelCostValue.Text          = _currentComponentDirective.Cost.ToString();
            labelRemarksValue.Text       = _currentComponentDirective.Remarks;
            labelHiddenRemarksValue.Text = _currentComponentDirective.HiddenRemarks;
            labelWarrantyRemains.Text    = _currentComponentDirective.Threshold.Warranty.ToString();

            //GlobalObjects.PerformanceCalculator.GetNextPerformance(_currentComponentDirective);

            Lifelength temp;
            ComponentDirectiveThreshold threshold;
            Component tempComponent;
            var       tempAircraft = GlobalObjects.AircraftsCore.GetAircraftById(_currentComponentDirective.ParentComponent.ParentAircraftId);//TODO:(Evgenii Babak) пересмотреть использование ParentAircrafId здесь

            labelCompntRemains.Text = "";
            labelCompntSince.Text   = "";
            if (_currentComponentDirective.Remains != null && _currentComponentDirective.Condition != ConditionState.NotEstimated)
            {
                if (_currentComponentDirective.Remains.IsOverdue() && _currentComponentDirective.Condition == ConditionState.Overdue)
                {
                    labelRemains.Text           = "Overdue:";
                    imageLinkLabelStatus.Status = Statuses.NotSatisfactory;
                }
                else if (_currentComponentDirective.Condition == ConditionState.Notify)
                {
                    labelRemains.Text           = "Remains:";
                    imageLinkLabelStatus.Status = Statuses.Notify;
                }
                else if (_currentComponentDirective.Condition == ConditionState.Satisfactory)
                {
                    labelRemains.Text           = "Remains:";
                    imageLinkLabelStatus.Status = Statuses.Satisfactory;
                }
                else
                {
                    labelRemains.Text           = "Remains:";
                    imageLinkLabelStatus.Status = Statuses.NotActive;
                }

                labelCompntRemains.Text = _currentComponentDirective.Remains.ToString();
            }

            labelDateLast.Text         = "";
            labelCompntTCSNLast.Text   = "";
            labelAircraftTCSNLast.Text = "";

            labelDateNext.Text         = "n/a";
            labelCompntTCSNNext.Text   = "n/a";
            labelAircraftTCSNNext.Text = "n/a";

            if (_currentComponentDirective.LastPerformance != null)
            {
                //Заполнение Last-ов
                //дата последнего выполнения
                labelDateLast.Text = SmartCore.Auxiliary.Convert.GetDateFormat(_currentComponentDirective.LastPerformance.RecordDate);

                Lifelength current;
                if (_currentComponentDirective.ParentComponent is BaseComponent)
                {
                    current = GlobalObjects.CasEnvironment.Calculator.GetCurrentFlightLifelength((BaseComponent)_currentComponentDirective.ParentComponent);
                }
                else
                {
                    current = GlobalObjects.CasEnvironment.Calculator.GetCurrentFlightLifelength(_currentComponentDirective.ParentComponent);
                }
                //наработка компонента на последнем исполнении
                temp = _currentComponentDirective.LastPerformance.OnLifelength;
                if (temp != Lifelength.Null)
                {
                    labelCompntTCSNLast.Text = temp.ToString();
                    if (!current.IsNullOrZero())
                    {
                        current.Substract(temp);
                        labelCompntSince.Text = current.ToString();
                    }
                }


                temp = tempAircraft != null &&
                       _currentComponentDirective.ParentComponent.TransferRecords.GetLast().TransferDate < _currentComponentDirective.LastPerformance.RecordDate
    ? _currentComponentDirective.LastPerformance.OnLifelength
    : Lifelength.Null;


                //            if (temp != Lifelength.Null)
                //                labelAircraftTCSNLast.Text = temp.ToString();

                //наработка самолета на последнем исполнении
                labelAircraftTCSNLast.Text = GlobalObjects.CasEnvironment.Calculator.GetFlightLifelengthOnEndOfDay(tempAircraft,
                                                                                                                   _currentComponentDirective.LastPerformance.RecordDate).ToString();



                //Заполнение Next-ов
                threshold = _currentComponentDirective.Threshold;
                if (threshold.RepeatInterval != null && !threshold.RepeatInterval.IsNullOrZero())
                {
                    //наработка компонента на следующее исполнение
                    //var nextComponentTsnCsn = new Lifelength(_currentComponentDirective.LastPerformance.OnLifelength);
                    //nextComponentTsnCsn.Add(threshold.RepeatInterval);
                    //nextComponentTsnCsn.Resemble(threshold.RepeatInterval);
                    //labelCompntTCSNNext.Text = nextComponentTsnCsn.ToString();
                    labelCompntTCSNNext.Text = _currentComponentDirective.NextPerformance.PerformanceSource.ToString();
                    if (_currentComponentDirective.NextPerformanceDate.HasValue)
                    {
                        labelDateNext.Text = SmartCore.Auxiliary.Convert.GetDateFormat(_currentComponentDirective.NextPerformanceDate.Value);
                    }

                    //наработка самолета на следующее исполнение

                    //Могут вводится записи, которые были сделаны на агрегате еще
                    //до появления этого агрегате в системе. в данном случае надо проверять
                    //не является ли наработка на след.выполнение меньше той наработки
                    //при которой был установлен агрегат

                    var asr = _currentComponentDirective.ParentComponent.ActualStateRecords.GetFirst();
                    //if (asr != null && tempAircraft != null &&
                    //    threshold.FirstPerformanceSinceNew.IsGreaterNullable(_currentComponentDirective.ParentComponent.ActualStateRecords.GetFirst().OnLifelength))
                    //{
                    //наработка на след выполнение больше той, что была при установке агрегата
                    temp = GlobalObjects.CasEnvironment.Calculator.GetCurrentFlightLifelength(tempAircraft);
                    //temp.Add(remains);
                    temp.Add(_currentComponentDirective.Remains);
                    temp.Resemble(threshold.RepeatInterval);
                    labelAircraftTCSNNext.Text = temp.ToString();
                    //}
                    //else
                    //{
                    //    labelAircraftTCSNNext.Text = "";
                    //}
                }
            }
            else
            {
                //последнего исполнения не было
                //расчет ведется по FirstPerformance

                //Заполнение Next-ов
                threshold     = _currentComponentDirective.Threshold;
                tempComponent = _currentComponentDirective.ParentComponent;
                if (threshold.FirstPerformanceSinceNew != null && !threshold.FirstPerformanceSinceNew.IsNullOrZero())
                {
                    if (_currentComponentDirective.NextPerformanceDate.HasValue)
                    {
                        labelDateNext.Text = SmartCore.Auxiliary.Convert.GetDateFormat(_currentComponentDirective.NextPerformanceDate.Value);
                    }
                    //наработка компонента на следующее исполнение
                    //labelCompntTCSNNext.Text = threshold.FirstPerformanceSinceNew.ToString();
                    labelCompntTCSNNext.Text = _currentComponentDirective.NextPerformance.PerformanceSource.ToString();

                    //наработка самолета на следующее исполнение
                    //наработка = наработка самолета на сегодня + остаток до первого исполнения
                    //ActualStateRecord asr = _currentComponentDirective.ParentComponent.ActualStateRecords.GetFirst();
                    //if (asr != null && tempAircraft != null &&
                    //    threshold.FirstPerformanceSinceNew.IsGreaterNullable(_currentComponentDirective.ParentComponent.ActualStateRecords.GetFirst().OnLifelength))
                    //{
                    //наработка на след выполнение больше той, что была при установке агрегата
                    temp = GlobalObjects.CasEnvironment.Calculator.GetCurrentFlightLifelength(tempAircraft);
                    //temp.Add(remains);
                    temp.Add(_currentComponentDirective.Remains);
                    temp.Resemble(threshold.FirstPerformanceSinceNew);
                    labelAircraftTCSNNext.Text = temp.ToString();

                    //else
                    //    labelAircraftTCSNNext.Text = "";
                }
                else if (threshold.FirstPerformanceSinceEffectiveDate != null &&
                         !threshold.FirstPerformanceSinceEffectiveDate.IsNullOrZero())
                {
                    //дата Следующего исполнения
                    if (threshold.FirstPerformanceSinceEffectiveDate.Days != null)
                    {
                        //если в первом выполнении заданы дни
                        //то выводится точная дата следующего выполнения

                        //дата = дата_производства + первое_исполнение.дни
                        labelDateNext.Text =
                            SmartCore.Auxiliary.Convert.GetDateFormat(
                                threshold.EffectiveDate.AddDays((double)threshold.FirstPerformanceSinceEffectiveDate.Days));
                    }//иначе, точную дату выполнения расчитать нельзя


                    //наработка компонента на следующее исполнение
                    //Определение наработки
                    if (threshold.EffectiveDate < DateTime.Today)
                    {
                        Lifelength sinceEffDate = _currentComponentDirective.ParentComponent is BaseComponent
                            ? GlobalObjects.CasEnvironment.Calculator.GetFlightLifelengthOnEndOfDay((BaseComponent)_currentComponentDirective.ParentComponent, _currentComponentDirective.Threshold.EffectiveDate)
                            : GlobalObjects.CasEnvironment.Calculator.GetFlightLifelengthOnEndOfDay(_currentComponentDirective.ParentComponent, _currentComponentDirective.Threshold.EffectiveDate);

                        sinceEffDate.Add(_currentComponentDirective.Threshold.FirstPerformanceSinceEffectiveDate);
                        sinceEffDate.Resemble(_currentComponentDirective.Threshold.FirstPerformanceSinceEffectiveDate);

                        if (labelCompntTCSNNext.Text != "n/a")
                        {
                            labelCompntTCSNNext.Text += " or ";
                        }
                        else
                        {
                            labelCompntTCSNNext.Text = "";
                        }
                        labelCompntTCSNNext.Text += "s/e.d: " + sinceEffDate;
                    }
                    //наработка самолета на следующее исполнение
                    //наработка = наработка самолета на сегодня + остаток до первого исполнения
                    ActualStateRecord asr = _currentComponentDirective.ParentComponent.ActualStateRecords.GetFirst();
                    //if (asr != null && tempAircraft != null &&
                    //    threshold.FirstPerformanceSinceEffectiveDate.IsGreaterNullable(asr.OnLifelength))
                    //{
                    //наработка на след выполнение больше той, что была при установке агрегата
                    temp = GlobalObjects.CasEnvironment.Calculator.GetCurrentFlightLifelength(tempAircraft);
                    //temp.Add(remains);
                    temp.Add(_currentComponentDirective.Remains);
                    temp.Resemble(threshold.FirstPerformanceSinceNew);
                    labelAircraftTCSNNext.Text = temp.ToString();
                    //}
                    //else
                    //    labelAircraftTCSNNext.Text = "";
                }
            }
        }
Пример #12
0
        /// <summary>
        /// Сохранаяет данные текущего ВС
        /// </summary>
        public void SaveData()
        {
            var aircraftFrame = GlobalObjects.ComponentCore.GetBaseComponentById(CurrentAircraft.AircraftFrameId);

            if (dictionaryComboBoxAircraftModel.SelectedItem != CurrentAircraft.Model)
            {
                CurrentAircraft.Model = (AircraftModel)dictionaryComboBoxAircraftModel.SelectedItem;
            }
            if (dateTimePickerManufactureDate.Value != CurrentAircraft.ManufactureDate)
            {
                CurrentAircraft.ManufactureDate = dateTimePickerManufactureDate.Value;
            }
            if (textBoxSerialNumber.Text != CurrentAircraft.SerialNumber)
            {
                CurrentAircraft.SerialNumber = textBoxSerialNumber.Text;
                aircraftFrame.SerialNumber   = textBoxSerialNumber.Text;
            }
            if (textBoxRegistrationNumber.Text != CurrentAircraft.RegistrationNumber)
            {
                CurrentAircraft.RegistrationNumber   = textBoxRegistrationNumber.Text;
                linkMonthlyUtilization.Text          = aircraftFrame + ". Log Book";
                linkMonthlyUtilization.DisplayerText = aircraftFrame + ". Log Book";
                if (DisplayerRequested != null)
                {
                    DisplayerRequested(this, new ReferenceEventArgs(null,
                                                                    ReflectionTypes.ChangeTextOfContainingDisplayer,
                                                                    CurrentAircraft.RegistrationNumber +
                                                                    ". Aircraft General Data"));
                }
            }

            CurrentAircraft.APUFH = (double)numericUpDownAPU.Value;
            if (textBoxOwner.Text != CurrentAircraft.Owner)
            {
                CurrentAircraft.Owner = textBoxOwner.Text;
            }
            if (textBoxAircraftTypeCertificateNo.Text != CurrentAircraft.TypeCertificateNumber)
            {
                CurrentAircraft.TypeCertificateNumber = textBoxAircraftTypeCertificateNo.Text;
            }
            if (textBoxVariableNumber.Text != CurrentAircraft.VariableNumber)
            {
                CurrentAircraft.VariableNumber = textBoxVariableNumber.Text;
            }
            if (textBoxLineNumber.Text != CurrentAircraft.LineNumber)
            {
                CurrentAircraft.LineNumber = textBoxLineNumber.Text;
            }
            if (comboBoxMSG.SelectedItem != null && (MSG)comboBoxMSG.SelectedItem != CurrentAircraft.MSG)
            {
                CurrentAircraft.MSG = (MSG)comboBoxMSG.SelectedItem;
            }
            if (!string.IsNullOrEmpty(comboBoxApuWorktime.Text) && double.Parse(comboBoxApuWorktime.Text, CultureInfo.InvariantCulture) != CurrentAircraft.ApuUtizationPerFlightinMinutes)
            {
                short apuworktime = (short)Math.Round(double.Parse(comboBoxApuWorktime.Text, CultureInfo.InvariantCulture), 1);
                if (apuworktime == 0)
                {
                    CurrentAircraft.ApuUtizationPerFlightinMinutes = null;
                }
                else
                {
                    CurrentAircraft.ApuUtizationPerFlightinMinutes = apuworktime;
                }
            }

            ActualStateRecord actualStateRecord =
                aircraftFrame.ActualStateRecords[aircraftFrame.StartDate];

            if (actualStateRecord == null)
            {
                actualStateRecord             = new ActualStateRecord();
                actualStateRecord.ComponentId = aircraftFrame.ItemId;
            }

            actualStateRecord.RecordDate   = dateTimePickerStart.Value;
            actualStateRecord.OnLifelength = lifelengthViewerStart.Lifelength;
            GlobalObjects.ComponentCore.RegisterActualState(aircraftFrame, actualStateRecord);

            aircraftFrame.StartDate       = dateTimePickerStart.Value;
            aircraftFrame.StartLifelength = lifelengthViewerStart.Lifelength;
            GlobalObjects.ComponentCore.Save(aircraftFrame);

            CurrentAircraft.DeliveryDate = dateTimePickerStart.Value;
        }
Пример #13
0
        /// <summary>
        /// Возвращает значение, показывающее является ли значение элемента управления допустимым
        /// </summary>
        /// <returns></returns>
        private bool ValidateData(out string message)
        {
            message = "";

            if (dateTimePicker1.Value.Date > DateTime.Now.Date)
            {
                if (message != "")
                {
                    message += "\n ";
                }
                message += "Performance date must be less than current date.";
                return(false);
            }
            if (dateTimePicker1.Value.Date < _currentComponent.ManufactureDate.Date)
            {
                if (message != "")
                {
                    message += "\n ";
                }
                message += "Performance date must be grather than manufacture date.";
                return(false);
            }

            Lifelength perfLifeLength = lifelengthViewer_LastCompliance.Lifelength;

            if (_currentActualStateRecord.ItemId <= 0)
            {
                IWorkRegime       workRegime = comboBoxFlightRegime.SelectedItem as IWorkRegime ?? FlightRegime.UNK;
                ActualStateRecord acr        = _currentComponent.ActualStateRecords[dateTimePicker1.Value, workRegime];
                if (acr != null)
                {
                    //Актуальное состояние на заданную дату есть
                    message =
                        $"On a given date {SmartCore.Auxiliary.Convert.GetDateFormat(dateTimePicker1.Value)} have a saved record";
                    return(false);
                }

                acr = _currentComponent.ActualStateRecords.GetLastKnownRecord(dateTimePicker1.Value, workRegime);
                if (acr != null && perfLifeLength.IsLessByAnyParameter(acr.OnLifelength))
                {
                    message = "Performance source must be grather than " + acr.OnLifelength;
                    return(false);
                }

                acr = _currentComponent.ActualStateRecords.GetFirstKnownRecord(dateTimePicker1.Value, workRegime);
                if (acr != null && perfLifeLength.IsGreaterByAnyParameter(acr.OnLifelength))
                {
                    message = "Performance source must be less than " + acr.OnLifelength;
                    return(false);
                }
            }


            if (_prevPerfLifelength != null && perfLifeLength.IsLessByAnyParameter(_prevPerfLifelength))
            {
                if (message != "")
                {
                    message += "\n ";
                }
                message += "Performance source must be grather than " + _prevPerfLifelength;
                return(false);
            }
            if (_nextPerfLifelength != null && perfLifeLength.IsGreaterByAnyParameter(_nextPerfLifelength))
            {
                if (message != "")
                {
                    message += "\n ";
                }
                message += "Performance source must be less than " + _nextPerfLifelength;
                return(false);
            }
            return(true);
        }
Пример #14
0
        private void ButtonDeleteClick(object sender, EventArgs e)
        {
            if (listViewCompliance.SelectedItems.Count == 0)
            {
                return;
            }

            if (listViewCompliance.SelectedItems[0].Tag is DirectiveRecord)
            {
                DirectiveRecord record = (DirectiveRecord)listViewCompliance.SelectedItems[0].Tag;
                if (record.DirectivePackage != null)
                {
                    MessageBox.Show("Perform of the task:" + listViewCompliance.SelectedItems[0].Text +
                                    "\nadded by Work Package:" +
                                    "\n" + record.DirectivePackage.Title +
                                    "\nTo remove a performance of task, you need to exclude task from this work package," +
                                    "\nor delete the work package ",
                                    (string)new GlobalTermsProvider()["SystemName"],
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Warning,
                                    MessageBoxDefaultButton.Button1);
                    return;
                }

                switch (MessageBox.Show(@"Delete this compliance " + record.RecordType + " ?", (string)new GlobalTermsProvider()["SystemName"],
                                        MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation,
                                        MessageBoxDefaultButton.Button2))
                {
                case DialogResult.Yes:
                    GlobalObjects.PerformanceCore.Delete(record);
                    InvokeComplianceAdded(null);
                    break;

                case DialogResult.No:
                    break;
                }
            }
            else if (listViewCompliance.SelectedItems[0].Tag is ActualStateRecord)
            {
                ActualStateRecord record = (ActualStateRecord)listViewCompliance.SelectedItems[0].Tag;

                switch (MessageBox.Show(@"Delete this actual state record ?", (string)new GlobalTermsProvider()["SystemName"],
                                        MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation,
                                        MessageBoxDefaultButton.Button2))
                {
                case DialogResult.Yes:
                    GlobalObjects.ComponentCore.DeleteActualStateRecord(record);
                    InvokeComplianceAdded(null);
                    break;

                case DialogResult.No:
                    break;
                }
            }
            else if (listViewCompliance.SelectedItems[0].Tag is ComponentLLPCategoryChangeRecord)
            {
                ComponentLLPCategoryChangeRecord record = (ComponentLLPCategoryChangeRecord)listViewCompliance.SelectedItems[0].Tag;

                if (record.ParentComponent == null)
                {
                    record.ParentComponent = _currentComponent;
                }

                switch (MessageBox.Show(@"Delete this LLP category change record ?", (string)new GlobalTermsProvider()["SystemName"],
                                        MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation,
                                        MessageBoxDefaultButton.Button2))
                {
                case DialogResult.Yes:
                    GlobalObjects.ComponentCore.DeleteLLPCategoryChangeRecord(record);
                    InvokeComplianceAdded(null);
                    break;

                case DialogResult.No:
                    break;
                }
            }
        }
Пример #15
0
        /// <summary>
        /// Сохранаяет данные текущего базового агрегата
        /// </summary>
        public void SaveData()
        {
            if (_currentBaseComponent == null)
            {
                return;
            }
            if (comboBoxEngineModel.SelectedItem != _currentBaseComponent.Model)
            {
                var d = comboBoxEngineModel.SelectedItem as ComponentModel;
                _currentBaseComponent.Model       = d;
                _currentBaseComponent.Description = d.FullName;
            }

            if (textBoxManufacturer.Text != _currentBaseComponent.Manufacturer)
            {
                _currentBaseComponent.Manufacturer = textBoxManufacturer.Text;
            }
            _currentBaseComponent.ManufactureDate = dateTimePickerManufactureDate.Value;
            if (textBoxSerialNumber.Text != _currentBaseComponent.SerialNumber)
            {
                _currentBaseComponent.SerialNumber = textBoxSerialNumber.Text;
            }

            _currentBaseComponent.PartNumber = textBoxPartialNumber.Text;
            _currentBaseComponent.LifeLimit  = lifelengthViewerLifeLimit.Lifelength;
            _currentBaseComponent.Warranty   = lifelengthViewerWarranty.Lifelength;

            if (_currentBaseComponent.ItemId > 0)
            {
                #region Актуальное состояние на стартовую дату

                ActualStateRecord actualStateRecord = _currentBaseComponent.ActualStateRecords[_currentBaseComponent.StartDate];
                if (actualStateRecord == null)
                {
                    actualStateRecord             = new ActualStateRecord();
                    actualStateRecord.ComponentId = _currentBaseComponent.ItemId;
                }

                actualStateRecord.RecordDate   = dateTimePickerStart.Value;
                actualStateRecord.OnLifelength = lifelengthViewerStart.Lifelength;
                GlobalObjects.ComponentCore.RegisterActualState(_currentBaseComponent, actualStateRecord);

                #endregion

                _currentBaseComponent.StartDate       = dateTimePickerStart.Value;
                _currentBaseComponent.StartLifelength = lifelengthViewerStart.Lifelength;

                TransferRecord    record = _currentBaseComponent.TransferRecords.GetLast();
                ActualStateRecord actual = _currentBaseComponent.ActualStateRecords[record.TransferDate];
                if (record.Position != textBoxPosition.Text ||
                    record.TransferDate != dateTimePickerInstallation.Value ||
                    (actual != null
                         ? !actual.OnLifelength.IsEqual(lifelengthViewerInstallation.Lifelength)
                         : !lifelengthViewerInstallation.Lifelength.IsNullOrZero()))
                {
                    record.Position = textBoxPosition.Text;
                    if (actual != null)
                    {
                        if (record.TransferDate >= dateTimePickerInstallation.Value)
                        {
                            //Дата установки изменена на более раннюю
                            actual.OnLifelength = lifelengthViewerInstallation.Lifelength;
                            actual.RecordDate   = dateTimePickerInstallation.Value;
                            GlobalObjects.CasEnvironment.NewKeeper.Save(actual);
                        }
                        else if (record.TransferDate < dateTimePickerInstallation.Value)
                        {
                            _currentBaseComponent.ActualStateRecords.Remove(actual);
                            actual.OnLifelength = lifelengthViewerInstallation.Lifelength;
                            actual.RecordDate   = dateTimePickerInstallation.Value;
                            GlobalObjects.ComponentCore.RegisterActualState(_currentBaseComponent, actual);
                        }
                    }
                    else
                    {
                        actual              = new ActualStateRecord();
                        actual.ComponentId  = _currentBaseComponent.ItemId;
                        actual.RecordDate   = dateTimePickerInstallation.Value;
                        actual.OnLifelength = lifelengthViewerInstallation.Lifelength;
                        GlobalObjects.ComponentCore.RegisterActualState(_currentBaseComponent, actual);
                    }
                    record.TransferDate = dateTimePickerInstallation.Value;
                    GlobalObjects.CasEnvironment.NewKeeper.Save(record);
                }

                //GlobalObjects.CasEnvironment.Keeper.Save(_currentBaseDetail.TransferRecords.GetLast());
                GlobalObjects.ComponentCore.Save(_currentBaseComponent);
            }
            else
            {
                _currentBaseComponent.StartDate       = dateTimePickerStart.Value;
                _currentBaseComponent.StartLifelength = lifelengthViewerStart.Lifelength;

                GlobalObjects.ComponentCore.
                AddBaseComponent(_currentBaseComponent, _currentAircraft, dateTimePickerInstallation.Value,
                                 textBoxPosition.Text, lifelengthViewerInstallation.Lifelength, true, false);
                ActualStateRecord actualStateRecord = _currentBaseComponent.ActualStateRecords[_currentBaseComponent.StartDate];
                if (actualStateRecord == null)
                {
                    actualStateRecord             = new ActualStateRecord();
                    actualStateRecord.ComponentId = _currentBaseComponent.ItemId;
                }

                actualStateRecord.RecordDate   = dateTimePickerInstallation.Value;
                actualStateRecord.OnLifelength = lifelengthViewerInstallation.Lifelength;
                GlobalObjects.ComponentCore.RegisterActualState(_currentBaseComponent, actualStateRecord);
            }
        }
Пример #16
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);
        }
Пример #17
0
        private void ButtonAdd_Click(object sender, EventArgs e)
        {
            if (listViewTransferedDetails.SelectedItems.Count == 0)
            {
                return;
            }

            ComponentCollection             installedComponents = new ComponentCollection();
            ComponentCollection             removedComponents   = new ComponentCollection(_removedComponents.ToArray());
            List <ReplaceComponentFormItem> replaceDetailFormItems;

            foreach (ListViewItem item in listViewTransferedDetails.SelectedItems)
            {
                if (item.Group == listViewTransferedDetails.Groups[1])
                {
                    Component component = (Component)item.Tag;
                    installedComponents.Add(component);

                    //detail.TransferRecords.Last.DODR = true;

                    ////увеличение необходимого кол-ва деталей родительского компонента
                    ////сохранение родительского компонента
                    //detail.ParentBaseDetail.ComponentCount++;
                    //GlobalObjects.CasEnvironment.Keeper.Save(detail.ParentBaseDetail);

                    //GlobalObjects.CasEnvironment.Keeper.Save(detail.TransferRecords.Last);
                    //_installedDetails.Remove(detail);
                    //TransferRecord record = _installedTransfers.GetTransferRecordByDetailID(detail.DetailId);
                    //if (record != null) _installedTransfers.Remove(record);
                }
            }

            if (installedComponents.Count == 0)
            {
                return;
            }
            replaceDetailFormItems = new List <ReplaceComponentFormItem>();

            foreach (Component item in installedComponents)
            {
                var newItem = new ReplaceComponentFormItem(item, null, _parentType);
                replaceDetailFormItems.Add(newItem);

                if (item is BaseComponent)
                {
                    newItem.comboBoxReplaceByDetail.Items.AddRange(_waitremovedConfirmComponents.Where(i => i is BaseComponent).ToArray());
                }
                if (item is Component)
                {
                    newItem.comboBoxReplaceByDetail.Items.AddRange(_waitremovedConfirmComponents.Where(i => i is Component).ToArray());
                }

                if (removedComponents.Count == 0)
                {
                    newItem.UpdateInformation(true);
                    continue;
                }

                foreach (Component removedItem in removedComponents)
                {
                    //проверка по сходству ID
                    //проверка по сходству названия
                    if (removedItem.ItemId == item.ItemId ||
                        removedItem.Description.ToUpper() == item.Description.ToUpper())
                    {
                        //Если ID идентичны, то эта деталь сначала была перемещена куда-то,
                        //а потом обратно на самолет

                        //если название идентично, значит эта могла быть направлена на самолет
                        //для замены снятой
                        newItem.ReplacedByComponent      = removedItem;
                        newItem.ReplacedByDetailTransfer =
                            _removedTransfers.GetRecordByComponentId(removedItem.ItemId);

                        //удаление элемента из коллекции, что бы он не попал в результат дважды
                        removedComponents.Remove(removedItem);
                        break;
                    }
                }
                newItem.UpdateInformation(true);
            }

            var form = new ReplaceComponentForm(_installedComponents, _removedComponents, replaceDetailFormItems.ToArray(), _parentType);

            form.UpdateLabels(true);

            TopMost = false; //что бы данное онко не перекрывало окно диалога
            form.ShowDialog();
            TopMost = true;

            //return;

            //Если изменения не были произведены, то просто возвращаемся из данной функции
            if (form.DialogResult == DialogResult.Cancel)
            {
                return;
            }
            //иначе производится замена/перемещение компонентов
            var replacedItems = new List <ReplaceComponentFormItem>(form.GetReplacedItems());

            foreach (ReplaceComponentFormItem replacedItem in replacedItems)
            {
                if (!replacedItem.ConfirmTransfer)
                {
                    continue;
                }

                if (replacedItem.ParentComponent != null)
                {
                    if (replacedItem.ParentComponent.IsBaseComponent)
                    {
                        BaseComponent bd =
                            GlobalObjects.CasEnvironment.BaseComponents.
                            GetItemById(replacedItem.ParentComponent.ItemId);

                        ActualStateRecord actual =
                            bd.ActualStateRecords[bd.TransferRecords.GetLast().StartTransferDate];

                        if (actual != null)
                        {
                            actual.RecordDate = replacedItem.ConfirmDate;
                            //TODO:(Evgenii Babak) пересмотреть подход, наработка считается на начало дня, а в метод передаем DateTime.Now(может быть и концом дня)
                            actual.OnLifelength = GlobalObjects.CasEnvironment.Calculator.GetFlightLifelengthOnStartOfDay(bd, replacedItem.ConfirmDate);
                            GlobalObjects.CasEnvironment.NewKeeper.Save(actual);
                        }
                        else
                        {
                            actual = new ActualStateRecord
                            {
                                ComponentId = bd.ItemId,
                                RecordDate  = DateTime.Now,
                                //TODO:(Evgenii Babak) пересмотреть подход, наработка считается на начало дня, а в метод передаем DateTime.Now(может быть и концом дня)
                                OnLifelength = GlobalObjects.CasEnvironment.Calculator.GetFlightLifelengthOnStartOfDay(bd, replacedItem.ConfirmDate)
                            };
                            GlobalObjects.ComponentCore.RegisterActualState(bd, actual);
                        }

                        bd.TransferRecords.GetLast().DODR = true;
                        bd.TransferRecords.GetLast().PreConfirmTransfer = true;
                        bd.TransferRecords.GetLast().TransferDate       = replacedItem.ConfirmDate;
                        GlobalObjects.CasEnvironment.NewKeeper.Save(bd.TransferRecords.GetLast());
                    }
                    else
                    {
                        ActualStateRecord actual =
                            replacedItem.ParentComponent.ActualStateRecords[replacedItem.ParentComponent.TransferRecords.GetLast().StartTransferDate];

                        if (actual != null)
                        {
                            actual.RecordDate = replacedItem.ConfirmDate;
                            //TODO:(Evgenii Babak) пересмотреть подход, наработка считается на начало дня, а в метод передаем DateTime.Now(может быть и началом дня)
                            actual.OnLifelength = GlobalObjects.CasEnvironment.Calculator.GetFlightLifelengthOnEndOfDay(replacedItem.ParentComponent, DateTime.Now);
                            GlobalObjects.CasEnvironment.NewKeeper.Save(actual);
                        }
                        else
                        {
                            actual = new ActualStateRecord
                            {
                                ComponentId = replacedItem.ParentComponent.ItemId,
                                RecordDate  = DateTime.Now,
                                //TODO:(Evgenii Babak) пересмотреть подход, наработка считается на начало дня, а в метод передаем DateTime.Now(может быть и началом дня)
                                OnLifelength = GlobalObjects.CasEnvironment.Calculator.GetFlightLifelengthOnEndOfDay(replacedItem.ParentComponent, DateTime.Now)
                            };
                            GlobalObjects.ComponentCore.RegisterActualState(replacedItem.ParentComponent, actual);
                        }

                        if (replacedItem.ReplacedByComponent != null && replacedItem.ReplacedByComponent.ComponentDirectives.Count > 0)
                        {
                            foreach (var directive in replacedItem.ReplacedByComponent.ComponentDirectives)
                            {
                                var newDirective = directive.GetCopyUnsaved();
                                newDirective.ComponentId     = replacedItem.ParentComponent.ItemId;
                                newDirective.ParentComponent = replacedItem.ParentComponent;
                                GlobalObjects.CasEnvironment.NewKeeper.Save(newDirective);
                            }
                        }


                        replacedItem.ParentComponent.TransferRecords.GetLast().DODR = true;
                        replacedItem.ParentComponent.TransferRecords.GetLast().PreConfirmTransfer = true;
                        replacedItem.ParentComponent.TransferRecords.GetLast().TransferDate       =
                            replacedItem.ConfirmDate;
                        //увеличение необходимого кол-ва деталей родительского компонента
                        //сохранение родительского компонента
                        if (replacedItem.ParentComponent.ParentBaseComponent != null)
                        {
                            replacedItem.ParentComponent.ParentBaseComponent.ComponentCount++;
                            GlobalObjects.ComponentCore.Save(replacedItem.ParentComponent.ParentBaseComponent);//TODO:(Evgenii Babak) заменить на использование ComponentCore
                        }
                        GlobalObjects.CasEnvironment.NewKeeper.Save(replacedItem.ParentComponent.TransferRecords.GetLast());
                    }
                    _installedComponents.Remove(replacedItem.ParentComponent);
                    TransferRecord record = _installedTransfers.GetRecordByComponentId(replacedItem.ParentComponent.ItemId);
                    if (record != null)
                    {
                        _installedTransfers.Remove(record);

                        if (replacedItem.ReplacedByComponent != null)
                        {
                            record.ReplaceComponentId        = replacedItem.ReplacedByComponent.ItemId;
                            record.IsReplaceComponentRemoved = true;
                            GlobalObjects.CasEnvironment.NewKeeper.Save(record);
                        }
                    }
                }

                if (replacedItem.ReplacedByComponent != null)
                {
                    TransferRecord record = _removedTransfers.GetRecordByComponentId(replacedItem.ReplacedByComponent.ItemId);
                    if (record != null)
                    {
                        _removedTransfers.Remove(record);
                        record.PODR = true;
                        GlobalObjects.CasEnvironment.NewKeeper.Save(record);

                        BaseComponent from = GlobalObjects.ComponentCore.GetBaseComponentById(record.FromBaseComponentId);
                        //уменьшение необходимого кол-ва деталей родительского компонента
                        //сохранение родительского компонента
                        if (from != null)
                        {
                            from.ComponentCount--;
                            GlobalObjects.ComponentCore.Save(from);
                        }

                        _removedComponents.Remove(replacedItem.ReplacedByComponent);
                    }
                }
            }

            //создание события ButtonAddClick
            InvokeButtonAddClick();

            UpdateInformation();
        }
Пример #18
0
        protected bool AddNewDetail(bool changePageName)
        {
            string message = "";

            if (addnewcomponentControl.BaseDetailAddTo == null)
            {
                message += "Please choose base component";
            }
            if (generalInformationControl.PartNumber == "")
            {
                GetMessage(ref message, "Part Number");
            }
            if (generalInformationControl.SerialNumber == "")
            {
                GetMessage(ref message, "Serial Number");
            }
            if (generalInformationControl.ATAChapter == null)
            {
                GetMessage(ref message, "ATA Chapter");
            }
            if (message != "")
            {
                MessageBox.Show(message, new TermsProvider()["SystemName"].ToString(), MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return(false);
            }
            generalInformationControl.SaveData(addedDetail);
            warrantyControl.SaveData(addedDetail);
            if (isStore)
            {
                storeControl.SaveData(addedDetail);
                if (generalInformationControl.ComponentTSNCSN != Lifelength.NullLifelength)
                {
                    ActualStateRecord record = new ActualStateRecord();
                    record.RecordDate = generalInformationControl.DateAsOf;
                    record.Lifelength = generalInformationControl.ComponentTSNCSN;
                    addedDetail.AddRecord(record);
                }
            }
            else
            {
                parentBaseDetail = addnewcomponentControl.BaseDetailAddTo;
                parentBaseDetail.Add(addedDetail, "", generalInformationControl.InstallationDate);//todo
                if (generalInformationControl.ComponentTSNCSN != Lifelength.NullLifelength)
                {
                    ActualStateRecord record = new ActualStateRecord();
                    record.RecordDate = generalInformationControl.InstallationDate;
                    record.Lifelength = generalInformationControl.ComponentTSNCSN;
                    addedDetail.AddRecord(record);
                }
                if (generalInformationControl.SetActualDataToAircraft)
                {
                    ActualStateRecord record = new ActualStateRecord();
                    record.RecordDate = generalInformationControl.InstallationDate;
                    record.Lifelength = generalInformationControl.AircraftTSNCSN;
                    parentBaseDetail.ParentAircraft.AddRecord(record);
                }
                if (generalInformationControl.SetCurrentComponentTSNCSN)
                {
                    ActualStateRecord record = new ActualStateRecord();
                    record.RecordDate = generalInformationControl.DateAsOf;
                    record.Lifelength = generalInformationControl.AircraftTSNCSN + (generalInformationControl.ComponentCurrentTSNCSN - generalInformationControl.ComponentTSNCSN);
                    parentBaseDetail.ParentAircraft.AddRecord(record);
                }
                compliancePerformanceListControl.SaveData(addedDetail);
                if (addedDetail.GetDetailDirectives().Length > 0 || addedDetail.LifeLimit != Lifelength.NullLifelength)
                {
                    addedDetail.MaintenanceType = MaintenanceTypeCollection.Instance.HardTimeType;
                }
                else
                {
                    addedDetail.MaintenanceType = MaintenanceTypeCollection.Instance.OnConditionType;
                }
                addedDetail.Save();
            }
            return(true);
        }
Пример #19
0
        /// <summary>
        /// Данные работы обновляются по введенным значениям
        /// </summary>
        private bool SaveData()
        {
            TimeSpan hours;
            int      cycles;

            if (!UsefulMethods.ParseTime(textBoxHours.Text, out hours))
            {
                SimpleBalloon.Show(textBoxHours, ToolTipIcon.Warning, "Incorrect time format", "Please enter the time period in the following format:\nHH:MM");
                return(false);
            }
            if (!int.TryParse(textBoxCycles.Text, out cycles))
            {
                SimpleBalloon.Show(textBoxCycles, ToolTipIcon.Warning, "Incorrect value", "Please enter integer value");
                return(false);
            }
            if (currentRecord.RecordDate != Date)
            {
                currentRecord.RecordDate = Date;
            }
            if (currentRecord.Description != Remarks)
            {
                currentRecord.Description = Remarks;
            }
            if (currentRecord.AttachedFile != AttachedFile)
            {
                currentRecord.AttachedFile.FileName = AttachedFile.FileName;
                currentRecord.AttachedFile.FileData = AttachedFile.FileData;
            }
            if (currentRecord.MaintenanceOrganization != MaintenanceOrganization)
            {
                currentRecord.MaintenanceOrganization = MaintenanceOrganization;
            }
            if (currentRecord.Reference != Reference)
            {
                currentRecord.Reference = Reference;
            }
            if (currentRecord.OfficialDocumentsReceived != OfficialRecordsReceived)
            {
                currentRecord.OfficialDocumentsReceived = OfficialRecordsReceived;
            }

            try
            {
                if (mode == ScreenMode.Add)
                {
                    currentRecord.Completed = true;
                    if (currentDetail != null)
                    {
                        currentRecord = new DetailDirectiveRecord(currentRecord);
                        ((DetailDirective)comboBoxWorkType.SelectedItem).AddPerformance((DetailDirectiveRecord)currentRecord);
                    }
                    else
                    {
                        if (currentRecord.RecordType != RecordType)
                        {
                            currentRecord.RecordType = RecordType;
                        }
                        if (currentRecord.RecordType == RecordTypesCollection.Instance.DirectivePerformanceRecordType &&
                            !currentDirective.RepeatedlyPerform)
                        {
                            currentRecord.RecordType = RecordTypesCollection.Instance.DirectiveClosingRecordType;
                        }
                        currentDirective.AddRecord(currentRecord);
                    }
                    if (AttachedFile != null)
                    {
                        currentRecord.AttachedFile.FileName = AttachedFile.FileName;
                        currentRecord.AttachedFile.FileData = AttachedFile.FileData;
                    }
                    mode = ScreenMode.Edit;
                }
                currentRecord.Save(true);
                if (actualStateChanged)
                {
                    bool exist = false;
                    int  index = -1;
                    for (int i = actualStateRecords.Length - 1; i >= 0; i--)
                    {
                        if (UsefulMethods.CompareDates(actualStateRecords[i].RecordDate, dateTimePickerDate.Value))
                        {
                            exist = true;
                            index = i;
                            break;
                        }
                    }
                    if (exist)
                    {
                        if (MessageBox.Show("There is another actual state record for this date.\nExisting data will be updated.\nContinue?", new GlobalTermsProvider()["SystemName"].ToString(), MessageBoxButtons.YesNoCancel, MessageBoxIcon.Exclamation) == DialogResult.Yes)
                        {
                            actualStateRecords[index].Lifelength = new Lifelength(new TimeSpan(0), cycles, hours);
                            actualStateRecords[index].Save();
                        }
                    }
                    else
                    {
                        ActualStateRecord record = new ActualStateRecord(new Lifelength(new TimeSpan(0), cycles, hours));
                        record.RecordDate = dateTimePickerDate.Value;
                        if (currentRecord.Parent.Parent is BaseDetail)
                        {
                            ((BaseDetail)currentRecord.Parent.Parent).AddRecord(record);
                        }
                        else
                        {
                            ((BaseDetail)currentRecord.Parent.Parent.Parent).AddRecord(record);
                        }
                    }
                }
                if (RecordChanged != null)
                {
                    RecordChanged(this, EventArgs.Empty);
                }
            }
            catch (Exception ex)
            {
                Program.Provider.Logger.Log("Error while saving data", ex);
                return(false);
            }
            return(true);
        }