private string getEmployeeFolderName(RowData employee)
    {
        if (employee == null)
        {
            return(null);
        }

        string r = "";

        if (!String.IsNullOrEmpty(employee.GetString("FirstName")))
        {
            r += employee.GetString("FirstName")[0].ToString() + ".";
        }
        if (!String.IsNullOrEmpty(employee.GetString("MiddleName")))
        {
            r += employee.GetString("MiddleName")[0].ToString() + ".";
        }
        string res = string.Format("{0} {1}", employee.GetString("LastName"), r);

        if (!string.IsNullOrEmpty(res))
        {
            return(res.Trim());
        }

        return(null);
    }
Esempio n. 2
0
        /// <summary>
        /// Получение перечня ремонтных работ.
        /// </summary>
        public ArrayList GetRepairWorks()
        {
            ArrayList RepairWorksList = new ArrayList();

            // Если прибор гарантийный и гарантия не аннулирована, не включаем ремонтные работы в калькуляцию
            if ((this.WarrantyRepair) && (!this.VoidWarranty))
            {
                return(RepairWorksList);
            }

            // Если клиент отказался от ремонта, то не включаем ремонтные работы в калькуляцию
            //if (this.RefusalToRepair)
            //{ return RepairWorksList; }

            CardData    SCard       = Card.CardScript.Session.CardManager.GetCardData(new Guid(this.ServiceCardID));
            SectionData RepairWorks = SCard.Sections[RefServiceCard.RepairWorks.ID.ToGuid()];

            if ((RepairWorks != null) && (RepairWorks.Rows.Count > 0))
            {
                RowDataCollection RowDescriptions = SCard.Sections[RefServiceCard.DescriptionOfFault.ID.ToGuid()].Rows;
                foreach (RowData Row in RepairWorks.Rows)
                {
                    if (Row.GetString(RefServiceCard.RepairWorks.NegotiationResult) != "Не выполнять")
                    {
                        RowData Description = null;
                        foreach (RowData RowDescription in RowDescriptions)
                        {
                            if (RowDescription.GetGuid(RefServiceCard.DescriptionOfFault.Id) == Row.GetGuid(RefServiceCard.RepairWorks.ParentTableRowId))
                            {
                                Description = RowDescription;
                            }
                        }

                        string BlockName           = Description.GetString(RefServiceCard.DescriptionOfFault.BlockOfDevice);
                        string BlockNameID         = Description.GetString(RefServiceCard.DescriptionOfFault.BlockOfDeviceID);
                        string WorksType           = Row.GetString(RefServiceCard.RepairWorks.WorksType);
                        string WorksTypeID         = Row.GetString(RefServiceCard.RepairWorks.WorksTypeID);
                        int    Amount              = this.DoubleCost == true ? (int)Row.GetDecimal(RefServiceCard.RepairWorks.Amount) * 2 : (int)Row.GetDecimal(RefServiceCard.RepairWorks.Amount);
                        bool   Improvement         = (bool)Row.GetBoolean(RefServiceCard.RepairWorks.Revision);
                        bool   VoidWarranty        = this.VoidWarranty;
                        bool   DoubleCost          = this.DoubleCost;
                        string DescriptionOfReason = this.DescriptionOfReason;
                        bool   RefusalToRepair     = this.RefusalToRepair;


                        CalculationItem NewItem = new CalculationItem(Card, DeviceName, DeviceItemID, BlockName, BlockNameID, WorksType, WorksTypeID, Improvement, Amount, true, VoidWarranty, DoubleCost,
                                                                      DescriptionOfReason, RefusalToRepair);
                        RepairWorksList.Add(NewItem);
                    }
                }
            }
            return(RepairWorksList);
        }
        private static Guid AddItemToRegestry(this CardData self, CardData refUniversal)
        {
            var sdp = self.Sections[CardOrd.Properties.ID];

            RowData rtd = refUniversal.Sections[RefUniversal.ItemType.ID]
                          .FindRow("@Name='Справочник готовых приборов'");

            SubSectionData items        = rtd.ChildSections[refUniversal.Type.AllSections["Item"].Id];
            SubSectionData propertyItem = rtd.ChildSections[refUniversal.Type.AllSections["TypeProperties"].Id];

            // Свойства записи
            RowData partyProperty         = propertyItem.FindRow("@Name='Партия'");
            RowData statusProperty        = propertyItem.FindRow("@Name='Статус'");
            RowData unitYearProperty      = propertyItem.FindRow("@Name='Год прибора'");
            RowData unitNumberProperty    = propertyItem.FindRow("@Name='Номер прибора'");
            RowData unitPassportProperty  = propertyItem.FindRow("@Name='Паспорт прибора'");
            RowData warrantyTalonProperty = propertyItem.FindRow("@Name='Гарантийный талон'");
            RowData unitNameProperty      = propertyItem.FindRow("@Name='Наименование прибора'");

            // Свойства карточки
            RowData unit       = sdp.FindRow("@Name='Прибор'");
            RowData party      = sdp.FindRow("@Name='№ партии'");
            RowData unitYear   = sdp.FindRow(string.Format("@Name = '{0}'", "/Год прибора"));
            RowData unitNumber = sdp.FindRow("@Name='Заводской номер прибора'");

            // Создаем запись в справочнике готовых приборов
            RowData newItem = items.Rows.AddNew();

            newItem.SetString("Name", self.Description);
            SubSectionData subrow = newItem.ChildSections[refUniversal.Type.AllSections["Properties"].Id];

            // Прописываем свойства
            AddItem(subrow.Rows.AddNew(),
                    unitNumberProperty.GetString("RowID"), unitNumber.GetString("DisplayValue"), unitNumber.GetString("Value"));
            AddItem(subrow.Rows.AddNew(),
                    unitYearProperty.GetString("RowID"), unitYear.GetString("DisplayValue"), unitYear.GetString("Value"));
            AddItem(subrow.Rows.AddNew(),
                    partyProperty.GetString("RowID"), party.GetString("DisplayValue"), party.GetString("Value"));
            AddItem(subrow.Rows.AddNew(),
                    statusProperty.GetString("RowID"), "В эксплуатации", "6");
            AddItem(subrow.Rows.AddNew(),
                    unitNameProperty.GetString("RowID"), unit.GetString("DisplayValue"), unit.GetString("Value"));
            AddItem(subrow.Rows.AddNew(),
                    unitPassportProperty.GetString("RowID"), self.Description, self.Id.ToString());
            AddItem(subrow.Rows.AddNew(),
                    unitNumber.GetString("RowID"), self.Description, self.Id.ToString());
            AddItem(subrow.Rows.AddNew(),
                    warrantyTalonProperty.GetString("RowID"), "", "");
            return(newItem.Id);
        }
Esempio n. 4
0
        private void View_Sensors_ValidatingEditor(Object sender, BaseContainerValidateEditorEventArgs e)
        {
            RowData Row = null;

            if (View_Sensors.FocusedRowHandle >= 0)
            {
                DataList[View_Sensors.FocusedRowHandle].Valid = false;
                switch (UniversalCard.VerifySensor(out Row, e.Value as String, !DataList.Select(r => r._Sensor).Where(s => !String.IsNullOrEmpty(s)).Contains(e.Value as String), DeviceState.Shipped, DeviceState.Operating))
                {
                case -2: DataList[View_Sensors.FocusedRowHandle].ToolTip = "Не введено значение!";
                    break;

                case -1: DataList[View_Sensors.FocusedRowHandle].ToolTip = "Датчик с указанным номером должен быть в состоянии «Отгружен», либо «В эксплуатации»!";
                    break;

                case 0: DataList[View_Sensors.FocusedRowHandle].ToolTip = "Датчик с указанным номером не существует!";
                    break;

                case 1:
                    if (BusySensors.Contains(e.Value as String) && !DataList.Select(r => r._Sensor).Where(s => !String.IsNullOrEmpty(s)).Contains(e.Value as String))
                    {
                        DataList[View_Sensors.FocusedRowHandle].ToolTip = "Датчик с указанным номером уже указан в данной карточке!";
                    }
                    else
                    {
                        DataList[View_Sensors.FocusedRowHandle].ToolTip = Row.GetString("Name");
                        DataList[View_Sensors.FocusedRowHandle].Valid   = true;
                    }
                    break;

                default: DataList[View_Sensors.FocusedRowHandle].ToolTip = "Обнаружена неоднозначность (по запросу обнаружено несколько записей)!";
                    break;
                }
            }
        }
Esempio n. 5
0
        /// <summary>
        ///  Поиск справочника сборочных узлов по типу прибора.
        /// </summary>
        /// <param name="UniversalCard"> Универсальный справочник.</param>
        /// <param name="DeviceType"> Тип прибора.</param>
        public static string FindBlocksDictionary(CardData UniversalCard, string DeviceType)
        {
            SectionData Items = UniversalCard.Sections[RefUniversal.Item.ID];
            RowData     Item  = Items.GetRow(new Guid(DeviceType));

            if (Item == null)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("Не удалось найти прибор в 'Справочнике приборов и комплектующих'. Обратитесь к системному администратору.");
                return("");
            }
            else
            {
                string  DicID      = "";
                string  DeviceName = Item.GetString("Name");
                RowData ItemsType  = UniversalCard.Sections[RefUniversal.ItemType.ID].FindRow("@Name = 'Сборочные узлы и детали на комплектацию'");

                foreach (RowData Row in ItemsType.ChildRows)
                {
                    if (Row.GetString("Name") == DeviceName)
                    {
                        DicID = Row.GetString("RowID");
                        break;
                    }
                }
                if (DicID == "")
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("Не удалось найти 'Справочник сборочных узлов' для прибора '" + DeviceName + "'. Обратитесь к системному администратору.");
                }
                return(DicID);
            }
        }
Esempio n. 6
0
        /// <summary>
        ///  Добавление ремонтной работы/доработки.
        /// </summary>
        /// <param name="sender"> sender.</param>
        /// <param name="e"> e.</param>
        private void AddButton_Click(object sender, EventArgs e)
        {
            bool          Improvement;
            object        activateParam = new object[] { "{DD20BF9B-90F8-4D9A-9553-5B5F17AD724E}", "", "{43A6DA44-899C-47D8-9567-2185E05D8524}", null, null, true };
            VbaCollection result        = (VbaCollection)Card.CardScript.CardFrame.CardHost.SelectFromCard(new Guid("{B2A438B7-8BB3-4B13-AF6E-F2F8996E148B}"), "Выберите вид ремонтных работ или доработку", activateParam);

            if (result != null)
            {
                foreach (object r in result)
                {
                    // Проверка выбранной записи
                    bool              Verify       = true;
                    RowData           WorkRow      = UniversalCard.GetItemRow(r.ToGuid());
                    int               WorksType    = (int)WorkRow.ChildSections[RefUniversal.Properties.ID].FindRow("@Name = 'Тип работ'").GetInt32(RefUniversal.Properties.Value);
                    RowDataCollection WorksDevices = WorkRow.ChildSections[RefUniversal.Properties.ID].FindRow("@Name = 'Приборы'").ChildSections[RefUniversal.SelectedValues.ID].Rows;
                    if (WorksType == 3)
                    {
                        DevExpress.XtraEditors.XtraMessageBox.Show("Позиция '" + WorkRow.GetString(RefUniversal.Item.Name) + "' не является ремонтной работой или доработкой. Она не будет добавлена в перечень ремонтных работ.");
                        Verify = false;
                    }

                    if (!WorksDevices.Any(row => row.GetString(RefUniversal.SelectedValues.SelectedValue).ToGuid().Equals(DeviceType.ToGuid())))
                    {
                        string DeviceTypeName = UniversalCard.GetItemName(new Guid(DeviceType));
                        DevExpress.XtraEditors.XtraMessageBox.Show("Позиция '" + WorkRow.GetString(RefUniversal.Item.Name) + "' не относится к прибору " + DeviceTypeName + ". Она не будет добавлена в перечень ремонтных работ.");
                        Verify = false;
                    }

                    if (Verify)
                    {
                        // Добавление выбранной записи
                        Improvement = WorksType == 2 ? true : false;
                        object[] Parametr = new object[9];
                        Parametr[0] = UniversalCard.GetItemName(r.ToGuid());
                        Parametr[1] = r.ToString();
                        Parametr[2] = 1;
                        Parametr[3] = Improvement;
                        Parametr[4] = Card.Context.GetCurrentEmployee().DisplayName;
                        Parametr[5] = Card.Context.GetObjectRef(Card.Context.GetCurrentEmployee()).Id.ToString();
                        Parametr[6] = 0;
                        Parametr[7] = null;
                        Parametr[8] = Work.NegotiationResult.NotAgreed.GetDescription();
                        DataRow NewRow = Table.Rows.Add(Parametr);
                    }
                }
            }
        }
Esempio n. 7
0
        private Boolean GetDevice(Boolean IsNeedComplete = false)
        {
            Object[] activateParams = new Object[] {
                MyHelper.RefUniversalItem.ToString("B").ToUpper(),
                String.Empty,
                MyHelper.RefItem_Devices.ToString("B").ToUpper(),
                false, String.Empty, false
            };
            Object Id = Host.SelectFromCard(MyHelper.RefUniversal, "Выберите прибор...", activateParams);

            if (Id.IsNull())
            {
                return(false);
            }

            RowData DeviceItemRow = Devices.ChildSections[MyHelper.RefUniversalItem].Rows[Id.ToGuid()];

            AC = MyMessageBox.Show("Поступили только комплектующие (без прибора)?", "Комплектация", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes;

            DeviceName = DeviceItemRow.GetString("Name");
            RowData DeviceCompleteInfo = Devices.AllChildRows.Find("Name", DeviceName);

            ACList = String.Empty;
            CData  = String.Empty;

            if (!DeviceCompleteInfo.IsNull())
            {
                SubSectionData DeviceItems = DeviceCompleteInfo.ChildSections[MyHelper.RefUniversalItem];
                CompleteForm   Form        = new CompleteForm(DeviceName, DeviceItems, AC, Verify, true, false);

                switch (Form.ShowDialog())
                {
                case DialogResult.OK:
                    ACList = Form.ACList;
                    CData  = Form.CData;
                    ACRows = Form.ACRows;
                    Button_ChangeComplete.Enabled = true;
                    break;

                default:
                    Button_ChangeComplete.Enabled = false;
                    if (IsNeedComplete)
                    {
                        return(false);
                    }
                    break;
                }
            }
            else
            {
                ACRows = null;
                Button_ChangeComplete.Enabled = false;
            }

            DeviceId = DeviceItemRow.Id;
            return(true);
        }
    private bool setRightsFoFolder(RowData newEmployeeDocsvision, string folderId)
    {
        if (folderId != null)
        {
            CardData    refStaffData = Session.CardManager.GetDictionaryData(RefStaff.ID);
            SectionData unitsSection = refStaffData.Sections[RefStaff.Units.ID];

            //Права
            var accountName = newEmployeeDocsvision.GetString(RefStaff.Employees.AccountName);
            if (string.IsNullOrEmpty(accountName))
            {
                return(false);
            }


            var profileCardId = Session.ProfileManager.GetProfileId(accountName);
            var profileCard   = (UserProfileCard)Session.CardManager.GetCard(profileCardId);
            if (profileCard.DefaultFolderId == new Guid(folderId))
            {
                return(false);
            }

            profileCard.DefaultFolderId = new Guid(folderId);

            var employee = objectContext.GetObject <StaffEmployee>(newEmployeeDocsvision.Id);
            if (employee.PersonalFolder == null)
            {
                return(false);
            }

            var staffService = objectContext.GetService <IStaffService>();
            staffService.SetFoldersRights(employee.PersonalFolder, employee.AccountName);


            //logger.Info("Права на папку созданы.");
            //Ограничения

            FolderCard folderCard = (FolderCard)Session.CardManager.GetDictionary(new Guid("DA86FABF-4DD7-4A86-B6FF-C58C24D12DE2"));

            Folder folder = folderCard.GetFolder(new Guid(folderId.ToString()));
            if ((folder.Restrictions & FolderRestrictions.Types) == 0)
            {
                folder.Restrictions |= FolderRestrictions.Types;
            }


            //logger.Info("Ограничения на папку созданы.");
            //Разрешения

            if ((folder.Restrictions & FolderRestrictions.Types) == 0)
            {
                folder.Restrictions = folder.Restrictions | FolderRestrictions.Types;
                folder.AllowedCardTypes.AddNew(new Guid("6D76D0A7-5434-40F2-912E-6370D33C3151"));
            }
        }
        return(true);
    }
        /// <summary>
        /// Инициализирует папку заданными значениями.
        /// </summary>
        /// <param name="Device">Прибор.</param>
        /// <param name="CodeID">ID кода СКБ.</param>
        /// <param name="CodeName">Отобразаемое значение кода СКБ.</param>
        /// <param name="DocumentID">ID документа.</param>
        /// <param name="DocumentName">Название документа.</param>
        /// <param name="FolderID">ID папки.</param>
        public DocumentsFolder(Folder ParentFolder, CardData Document, SavedSearchGroup SearchGroup, SavedView View, FolderCard FolderCard)
        {
            this.ParentFolder = ParentFolder;
            this.Document     = Document;
            DocumentID        = Document.Id;

            SectionData Properties = Document.Sections[CardOrd.Properties.ID];

            DocumentType = Properties.FindRow("@Name = '" + RefPropertiesCD.Requisities.FileType + "'").GetString("Value");
            RowData Code = Properties.FindRow("@Name = '" + RefPropertiesCD.Requisities.Code + "'");

            CodeID   = Code.GetGuid("Value").Value;
            CodeName = Code.GetString("DisplayValue");
            RowData Applicable = Properties.FindRow("@Name = '" + RefPropertiesCD.Requisities.Applicable + "'");

            Applicability = Applicable.GetString("DisplayValue");
            RowData Name = Properties.FindRow("@Name = '" + RefPropertiesCD.Requisities.DocumentName + "'");

            string ShortType = DocumentType == "СД - Спецификация (не платы)" || DocumentType == "СП - Спецификация платы" ? "" : DocumentType.Remove(DocumentType.IndexOf(" - "));

            DocumentName = CodeName + " " + ShortType + " " + Name.GetString("Value");

            Folder      = FolderCard.CreateFolder(ParentFolder.Id, DocumentName);
            Folder.Type = FolderTypes.Virtual;

            if (!SearchGroup.Queries.Any(row => row.Name == DocumentName))
            {
                SearchQuery   Query    = FolderCard.Session.CreateSearchQuery();
                CardTypeQuery CardType = Query.AttributiveSearch.CardTypeQueries.AddNew(CardOrd.ID);
                SectionQuery  Section  = CardType.SectionQueries.AddNew(CardOrd.MainInfo.ID);
                Section.Operation = SectionQueryOperation.And;
                Section.ConditionGroup.Operation = ConditionGroupOperation.And;
                Section.ConditionGroup.Conditions.AddNew(CardOrd.MainInfo.Type, FieldType.RefId, ConditionOperation.Equals, MyHelper.RefType_CD);

                Section           = CardType.SectionQueries.AddNew(CardOrd.Properties.ID);
                Section.Operation = SectionQueryOperation.And;
                Section.ConditionGroup.Operation = ConditionGroupOperation.And;
                Section.ConditionGroup.Conditions.AddNew(CardOrd.Properties.Value, FieldType.Unistring, ConditionOperation.Equals, DocumentType);
                Section.ConditionGroup.Conditions.AddNew(CardOrd.Properties.Name, FieldType.Unistring, ConditionOperation.Equals, RefPropertiesCD.Requisities.FileType);

                Section           = CardType.SectionQueries.AddNew(CardOrd.Properties.ID);
                Section.Operation = SectionQueryOperation.And;
                Section.ConditionGroup.Operation = ConditionGroupOperation.And;
                Section.ConditionGroup.Conditions.AddNew(CardOrd.Properties.Value, FieldType.RefId, ConditionOperation.Equals, CodeID);
                Section.ConditionGroup.Conditions.AddNew(CardOrd.Properties.Name, FieldType.Unistring, ConditionOperation.Equals, RefPropertiesCD.Requisities.Code);
                Query.Limit = 0;
                SearchGroup.Queries.AddNew(DocumentName).Import(Query);
            }
            SavedSearchQuery SavedQuery = SearchGroup.Queries.First(row => row.Name == DocumentName);

            Folder.RefId = SavedQuery.Id;

            Folder.CurrentViewId = View.Id;
            Folder.DefaultViewId = View.Id;
        }
Esempio n. 10
0
        /// <summary>
        /// Инициализирует строку по данным карточки файла.
        /// </summary>
        /// <param name="Context">Объектный контекст.</param>
        /// <param name="FileCard">Данные карточки файла.</param>
        private void Initalize(ObjectContext Context, CardData FileCard)
        {
            RowData        FileCardMainInfoRow = FileCard.Sections[CardFile.MainInfo.ID].FirstRow;
            List <RowData> FileCardCategories  = FileCard.Sections[CardFile.Categories.ID].Rows.Where(row => !row.GetObject(CardFile.Categories.CategoryID).ToGuid().IsEmpty()).ToList();
            Guid           AuthorId            = FileCardMainInfoRow.GetGuid(CardFile.MainInfo.Author) ?? Guid.Empty;

            this.Name         = FileCardMainInfoRow.GetString(CardFile.MainInfo.FileName);
            this.Size         = (Decimal)FileCardMainInfoRow.GetInt32(CardFile.MainInfo.FileSize) / (Decimal)1024;
            this.Category     = FileCardCategories.Any() ? FileCardCategories.Select(row => row.GetString("Name")).Aggregate((a, b) => a + ";" + b) : String.Empty;
            this.Registrar    = AuthorId.IsEmpty() ? String.Empty : Context.GetEmployeeDisplay(AuthorId);
            this.RegistrarId  = AuthorId;
            this.CreationDate = FileCard.CreateDate;
        }
 private static void SetRowEnumValue(this SectionData self,
                                     string fieldValue, string value)
 {
     if (!String.IsNullOrEmpty(value) && !RegexEngine.IsMatch(value, @"^\s+$"))
     {
         RowData        rd  = self.FindRow(string.Format("@Name='{0}'", fieldValue));
         SubSectionData ssd = rd.ChildSections[self.Card.Type.AllSections["EnumValues"].Id];
         RowData        srd = ssd.GetAllRows().ToList().Find(r => RegexEngine.IsMatch(r.GetString("ValueName"), value));
         srd = srd ?? ssd.GetAllRows().ToList().Find(r => RegexEngine.IsMatch(value, r.GetString("ValueName")));
         if (srd != null)
         {
             rd.SetInt32("Value", srd.GetInt32("ValueID"));
             rd.SetString("DisplayValue", srd.GetString("ValueName"));
         }
         else
         {
             logger.Warn("cardId='{0}'; {2}='{1}' value not found", self.Card.Id, value, fieldValue);
         }
     }
 }
Esempio n. 12
0
        /// <summary>
        /// Конструктор формы заполнения журнала условий калибровки.
        /// </summary>
        /// <param name="Session">Пользовательская сессия DV.</param>
        /// <param name="Context">Объектный контекст.</param>
        /// <param name="JournalItemType">Тип справочника.</param>
        /// <param name="CurrentItem">Текущая строка справочника.</param>
        /// <param name="CabinetNumber">Номер кабинета.</param>
        public JournalForm(UserSession Session, ObjectContext Context, BaseUniversalItemType JournalItemType, BaseUniversalItem CurrentItem, Int32 CabinetNumber)
        {
            InitializeComponent();
            this.Session = Session;
            this.Context = Context;
            IBaseUniversalService baseUniversalService = Context.GetService <IBaseUniversalService>();

            staffEmployee = Context.GetCurrentEmployee();
            itemCard      = baseUniversalService.OpenOrCreateItemCard(CurrentItem);
            CardData    itemCardData = Session.CardManager.GetCardData(Context.GetObjectRef <BaseUniversalItemCard>(itemCard).Id);
            SectionData CalibrationConditionsSection = itemCardData.Sections[itemCardData.Type.Sections["CalibrationConditions"].Id];
            RowData     CalibrationConditionsRow     = CalibrationConditionsSection.FirstRow;

            this.Text          = "Каб. №" + (CabinetNumber == 237 ? 226 : 228) + ". Условия на " + DateTime.Today.ToShortDateString();
            this.Date.DateTime = (DateTime?)CalibrationConditionsRow.GetDateTime("Date") ?? DateTime.Today;
            this.Employee.Text = CalibrationConditionsRow.GetString("Employee") != null?Context.GetEmployeeDisplay(new Guid(CalibrationConditionsRow.GetString("Employee"))) : staffEmployee.DisplayString;

            this.Temperature.Value = (decimal?)CalibrationConditionsRow.GetDecimal("Temperature") ?? 0;
            this.Humidity.Value    = (decimal?)CalibrationConditionsRow.GetDecimal("Humidity") ?? 0;
            this.Pressure.Value    = (decimal?)CalibrationConditionsRow.GetDecimal("Pressure") ?? 0;
        }
        private static void CreateUnitCard(UserSession Session, Protocol protocol, List <RawView> passportsRawView, CardData TemplateCard, Folder PassportFolder, CardData refUniversal)
        {
            var unitCard = TemplateCard.Copy();

            unitCard.IsTemplate = false;
            PassportFolder.Shortcuts.AddNew(unitCard.Id, true);

            var sdp = unitCard.Sections[CardOrd.Properties.ID];
            var rdm = unitCard.Sections[CardOrd.MainInfo.ID].FirstRow;

            #region Filling card fields

            sdp.BeginUpdate();
            sdp.SetRowDoubleValue("Заводской номер прибора",
                                  protocol.Number.StartsWith("0") ? protocol.Number.Substring(1) : protocol.Number);
            sdp.SetRowDoubleValue("/Год прибора", protocol.Year);
            sdp.SetRowDoubleValue("Год партии", protocol.Year);
            sdp.SetRowEnumValue("Состояние прибора", "В эксплуатации");

            // поиск партии по прибору
            string partyNumber = string.Empty;
            var    foundParty  = SearchParty(Session, protocol, refUniversal);

            if (foundParty != null)
            {
                RowData rdfp = foundParty.GetRowData();
                partyNumber = rdfp.GetString("Name");
                sdp.SetRowValue("№ партии", "DisplayValue", partyNumber);
                sdp.SetRowValue("№ партии", "Value", rdfp.Id, fieldType: FieldType.RefId);

                foreach (var row in rdfp.ChildSections[0].Rows)
                {
                    if (row.GetString("Name") == "Наименование прибора")
                    {
                        var unitName = row.GetString("DisplayValue");
                        sdp.SetRowValue("Прибор", "DisplayValue", unitName);
                        sdp.SetRowValue("Прибор", "Value", row.GetGuid("Value"), fieldType: FieldType.RefId);

                        // поиск прибора в справочнике
                        var si = refUniversal.Sections[RefUniversal.ItemType.ID].FindRow("@Name = 'Приборы и комплектующие'").ChildSections[RefUniversal.Item.ID].FindRow("@Name = '" + unitName + "'");
                        //var si = SearchItemInReference(refUniversal,RefUniversal.Item.ID, "Name", unitName);
                        if (si != null)
                        {
                            var code = si.ChildSections[0].FindRow("@Name = 'Код СКБ'");
                            sdp.SetRowValue("Код СКБ", "DisplayValue", code.GetString("DisplayValue"));
                            sdp.SetRowValue("Код СКБ", "Value", code.GetGuid("Value"), fieldType: FieldType.RefId);
                        }
                        else
                        {
                            logger.Info("Прибор не найден в справочнике: {0}", protocol.PhysicalFile.Name);
                        }
                    }

                    if (row.GetString("Name") == "Карточка плана")
                    {
                        var guid = row.GetGuid("Value");
                        if (guid.HasValue)
                        {
                            var rdcr = unitCard.Sections[CardOrd.CardReferences.ID].Rows.AddNew();
                            rdcr.SetGuid("Link", guid.Value);
                            rdcr.SetGuid("Type", new Guid("508F52C7-ACE1-48F0-B978-B55FC0649776"));

                            var cdp = Session.CardManager.GetCardData(guid.Value);
                            if (cdp.LockStatus == LockStatus.Free)
                            {
                                rdcr = cdp.Sections[CardOrd.CardReferences.ID].Rows.AddNew();
                                rdcr.SetGuid("Link", unitCard.Id);
                                rdcr.SetGuid("Type", new Guid("C8DE0604-03CD-4806-B0E1-304A92A6E277"));
                            }
                            else
                            {
                                logger.Warn("Card of plan is locked, ref not added {0}", protocol.PhysicalFile.Name);
                            }
                        }
                    }

                    if (row.GetString("Name") == "Комментарий")
                    {
                        sdp.SetRowDoubleValue("Комментарии к партии", row.GetString("Value"));
                    }
                }
            }
            else
            {
                logger.Warn("Партия не найдена для прибора: {0}", protocol.PhysicalFile.Name);
            }
            sdp.EndUpdate();

            rdm.BeginUpdate();

            RowData CurrentUser = SearchItemInReference(Session, Session.CardManager
                                                        .GetDictionaryData(DocsVision.Platform.Cards.Constants.RefStaff.ID), DocsVision.Platform.Cards.Constants.RefStaff.Employees.ID, "AccountName",
                                                        (string)Session.Properties["AccountName"].Value);

            var name = string.Format("{0} № {1}/{2} из партии {3}",
                                     protocol.DVUnitName, protocol.Number, protocol.Year, partyNumber);
            rdm.SetString("Name", name);
            rdm.SetString("Digest", name);
            rdm.SetGuid("RegisteredBy", CurrentUser.Id);
            rdm.EndUpdate();

            #endregion

            unitCard.Description = name;
            passportsRawView.Add(new RawView {
                Description = unitCard.Description, InstanceId = unitCard.Id
            });

            sdp.SetRowValue("Запись в справочнике", "Value", unitCard.AddItemToRegestry(refUniversal), fieldType: FieldType.RefId);

            sdp.SetTableProperty("Дата", DateTime.Now, FieldType.DateTime);
            sdp.SetTableProperty("Действие", "Паспорт создан на основании протокола калибровки");
            sdp.SetTableProperty("Участник", CurrentUser.Id, FieldType.UniqueId);
            sdp.SetTableProperty("Комментарий", "Паспорт создан автоматически в процессе работы утилиты \"ProtocolsRegistrar\"");
            sdp.SetTableProperty("Ссылки", null);

            unitCard.AttachDocumentToCard(Session, protocol, false);

            var em = Session.ExtensionManager.GetExtensionMethod("UploadExtension", "AssignRights");
            em.Parameters.AddNew("cardId", 0).Value = unitCard.Id.ToString();
            em.Execute();
        }
        private void printApproval_ItemClick(System.Object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            DocsVision.BackOffice.ObjectModel.Document FileCardDocument = this.Context.GetObject <DocsVision.BackOffice.ObjectModel.Document>(new System.Guid("224D391A-B7ED-E511-9414-E4115BB03AEA"));
            //MessageBox.Show("Документ нашли");
            string oTempPath = System.IO.Path.GetTempPath();
            string oFilePath = oTempPath + FileCardDocument.MainInfo.MainFileName;

            this.DocumentService.DownloadMainFile(FileCardDocument, oFilePath);

            //MessageBox.Show("Документ скачали");
            //получаем объект word
            Microsoft.Office.Interop.Word.ApplicationClass oApplication = new Microsoft.Office.Interop.Word.ApplicationClass();
            oApplication.Visible = true;
            object oMissing      = Type.Missing;
            object oFileNameMain = (object)oFilePath;
            object oFalse        = false;
            object oTrue         = true;

            try{
                Microsoft.Office.Interop.Word.Document oMainFileWord = oApplication.Documents.Open(ref oFileNameMain, ref oMissing,
                                                                                                   ref oFalse, ref oFalse, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                                                                                   ref oMissing, ref oTrue, ref oMissing, ref oMissing, ref oTrue, ref oMissing);

                //MessageBox.Show("Открыли");

                object replaceAll = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;

                string temp = String.Empty;

                BaseCardSectionRow row = (BaseCardSectionRow)Document.GetSection(new System.Guid("30EB9B87-822B-4753-9A50-A1825DCA1B74"))[0];
                Guid      tempId       = new System.Guid(row["ResponsDepartment"].ToString());
                StaffUnit unit         = Context.GetObject <StaffUnit>(tempId);

                oApplication.Selection.Find.ClearFormatting();
                oApplication.Selection.Find.Text = "&Организация.";
                oApplication.Selection.Find.Replacement.ClearFormatting();
                oApplication.Selection.Find.Replacement.Text = unit.Name;
                oApplication.Selection.Find.Execute(ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                                    ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                                    ref replaceAll, ref oMissing, ref oMissing, ref oMissing, ref oMissing);

                oApplication.Selection.Find.ClearFormatting();
                oApplication.Selection.Find.Text = "&Состояние.";
                oApplication.Selection.Find.Replacement.ClearFormatting();
                oApplication.Selection.Find.Replacement.Text = Document.SystemInfo.State.LocalizedName;
                oApplication.Selection.Find.Execute(ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                                    ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                                    ref replaceAll, ref oMissing, ref oMissing, ref oMissing, ref oMissing);

                BaseCardSectionRow docPartnerRow     = (BaseCardSectionRow)Document.GetSection(new System.Guid("6E976D72-3EA7-4708-A2C2-2A1499141301"))[0];
                CardData           PartnerDictionary = Session.CardManager.GetCardData(new System.Guid("65FF9382-17DC-4E9F-8E93-84D6D3D8FE8C")); //Справочник контрагентов
                RowData            PartnerRow        = PartnerDictionary.Sections[new System.Guid("C78ABDED-DB1C-4217-AE0D-51A400546923")].GetRow(new System.Guid(docPartnerRow["SenderOrg"].ToString()));
                oApplication.Selection.Find.ClearFormatting();
                oApplication.Selection.Find.Text = "&Контрагент.";
                oApplication.Selection.Find.Replacement.ClearFormatting();
                oApplication.Selection.Find.Replacement.Text = PartnerRow.GetString("Name");
                oApplication.Selection.Find.Execute(ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                                    ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                                    ref replaceAll, ref oMissing, ref oMissing, ref oMissing, ref oMissing);

                if (row["StatusId"] != null)
                {
                    CardData    dictionaryCard    = this.Session.CardManager.GetCardData(new System.Guid("4538149D-1FC7-4D41-A104-890342C6B4F8"));
                    SectionData dictionarySection = dictionaryCard.Sections[new System.Guid("A1DCE6C1-DB96-4666-B418-5A075CDB02C9")];
                    RowData     rdItemTypesNuno   = dictionarySection.GetRow(new System.Guid("10630364-D63F-4249-83E8-5DE95B2CD385"));       //виды бухгалтерских документов
                    foreach (RowData rdItems in rdItemTypesNuno.ChildSections[new System.Guid("1B1A44FB-1FB1-4876-83AA-95AD38907E24")].Rows)
                    {
                        if (row["StatusId"].ToString().ToUpper() == "{" + rdItems.Id.ToString().ToUpper() + "}")
                        {
                            temp = rdItems.GetString("Name");
                        }
                    }
                }
                else
                {
                    temp = String.Empty;
                }
                oApplication.Selection.Find.ClearFormatting();
                oApplication.Selection.Find.Text = "&Вид документа.";
                oApplication.Selection.Find.Replacement.ClearFormatting();
                oApplication.Selection.Find.Replacement.Text = temp;
                oApplication.Selection.Find.Execute(ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                                    ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                                    ref replaceAll, ref oMissing, ref oMissing, ref oMissing, ref oMissing);

                BaseCardSectionRow contractRow = (BaseCardSectionRow)Document.GetSection(new System.Guid("3997861D-4FF5-496A-B8A2-D16617DE91D7"))[0];
                temp = contractRow["AddAgreementNumber"] + "";

                oApplication.Selection.Find.ClearFormatting();
                oApplication.Selection.Find.Text = "&Номер.";
                oApplication.Selection.Find.Replacement.ClearFormatting();
                oApplication.Selection.Find.Replacement.Text = temp;
                oApplication.Selection.Find.Execute(ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                                    ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                                    ref replaceAll, ref oMissing, ref oMissing, ref oMissing, ref oMissing);

                oApplication.Selection.Find.ClearFormatting();
                oApplication.Selection.Find.Text = "&Дата.";
                oApplication.Selection.Find.Replacement.ClearFormatting();
                oApplication.Selection.Find.Replacement.Text = Convert.ToDateTime(contractRow["AttachmentDate"] + "").ToShortDateString();
                oApplication.Selection.Find.Execute(ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                                    ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                                    ref replaceAll, ref oMissing, ref oMissing, ref oMissing, ref oMissing);

                oApplication.Selection.Find.ClearFormatting();
                oApplication.Selection.Find.Text = "&Сумма.";
                oApplication.Selection.Find.Replacement.ClearFormatting();
                oApplication.Selection.Find.Replacement.Text = contractRow["MySum"] + "";
                oApplication.Selection.Find.Execute(ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                                    ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                                    ref replaceAll, ref oMissing, ref oMissing, ref oMissing, ref oMissing);

                string partially;
                if (row["WasSent"] + "" == "False")
                {
                    temp      = contractRow["MySum"] + "";
                    partially = "Нет";
                }
                else
                {
                    temp      = row["Sum"] + "";
                    partially = "Да";
                }

                oApplication.Selection.Find.ClearFormatting();
                oApplication.Selection.Find.Text = "&К оплате.";
                oApplication.Selection.Find.Replacement.ClearFormatting();
                oApplication.Selection.Find.Replacement.Text = temp;
                oApplication.Selection.Find.Execute(ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                                    ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                                    ref replaceAll, ref oMissing, ref oMissing, ref oMissing, ref oMissing);

                if (row["SLA"] != null)
                {
                    //MessageBox.Show("якобы условия оплаты заполнены"+row["SLA"]);
                    CardData    dictionaryCard    = this.Session.CardManager.GetCardData(new System.Guid("4538149D-1FC7-4D41-A104-890342C6B4F8"));
                    SectionData dictionarySection = dictionaryCard.Sections[new System.Guid("A1DCE6C1-DB96-4666-B418-5A075CDB02C9")];
                    RowData     rdItemTypesNuno   = dictionarySection.GetRow(new System.Guid("305EF160-0CBA-41B7-8187-E6383A471849"));       //условия оплаты
                    foreach (RowData rdItems in rdItemTypesNuno.ChildSections[new System.Guid("1B1A44FB-1FB1-4876-83AA-95AD38907E24")].Rows)
                    {
                        if (row["StatusId"].ToString().ToUpper() == "{" + rdItems.Id.ToString().ToUpper() + "}")
                        {
                            temp = rdItems.GetString("Name");
                        }
                    }
                }
                else
                {
                    //MessageBox.Show("условия оплаты не заполнены");
                    temp = String.Empty;
                }
                oApplication.Selection.Find.ClearFormatting();
                oApplication.Selection.Find.Text = "&Условия.";
                oApplication.Selection.Find.Replacement.ClearFormatting();
                oApplication.Selection.Find.Replacement.Text = temp;
                oApplication.Selection.Find.Execute(ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                                    ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                                    ref replaceAll, ref oMissing, ref oMissing, ref oMissing, ref oMissing);

                oApplication.Selection.Find.ClearFormatting();
                oApplication.Selection.Find.Text = "&Валюта.";
                oApplication.Selection.Find.Replacement.ClearFormatting();
                oApplication.Selection.Find.Replacement.Text = contractRow["ContractCurrency"] + "";
                oApplication.Selection.Find.Execute(ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                                    ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                                    ref replaceAll, ref oMissing, ref oMissing, ref oMissing, ref oMissing);

                oApplication.Selection.Find.ClearFormatting();
                oApplication.Selection.Find.Text = "&Частично.";
                oApplication.Selection.Find.Replacement.ClearFormatting();
                oApplication.Selection.Find.Replacement.Text = partially;
                oApplication.Selection.Find.Execute(ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                                    ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                                    ref replaceAll, ref oMissing, ref oMissing, ref oMissing, ref oMissing);

                Microsoft.Office.Interop.Word.Table newTable;
                Microsoft.Office.Interop.Word.Range myRange = oMainFileWord.Range();
                //object startOfRange = myRange.Text.IndexOf("&Таблица.");
                //object endOfRange = myRange.Text.IndexOf("&Таблица.") + 9;
                //Microsoft.Office.Interop.Word.Range wrdRng = oMainFileWord.Range(ref startOfRange, ref endOfRange);
                object oEndOfDoc = "\\endofdoc";
                Microsoft.Office.Interop.Word.Range wrdRng = oMainFileWord.Bookmarks.get_Item(ref oEndOfDoc).Range;
                //MessageBox.Show("range is determined");
                newTable = oMainFileWord.Tables.Add(wrdRng, 1, 4, ref oMissing, ref oMissing);
                //MessageBox.Show("table added");
                newTable.Borders.InsideLineStyle    = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
                newTable.Borders.OutsideLineStyle   = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
                newTable.AllowAutoFit               = true;
                newTable.Cell(1, 1).Range.Text      = "Сотрудник";
                newTable.Cell(1, 1).Range.Font.Bold = 1;
                newTable.Cell(1, 2).Range.Text      = "Дата согласования";
                newTable.Cell(1, 2).Range.Bold      = 1;
                newTable.Cell(1, 3).Range.Text      = "Результат";
                newTable.Cell(1, 3).Range.Bold      = 1;
                newTable.Cell(1, 4).Range.Text      = "Комментарий";
                newTable.Cell(1, 4).Range.Bold      = 1;

                int i = 1;
                while (i <= Document.GetSection(new System.Guid("AACEF937-EAD2-4AFD-A64C-DC42D7846B80")).Count)
                {
                    newTable.Rows.Add();
                    BaseCardSectionRow commentTable = (BaseCardSectionRow)Document.GetSection(new System.Guid("AACEF937-EAD2-4AFD-A64C-DC42D7846B80"))[i - 1];
                    string             employeeId   = commentTable["Employee"].ToString();
                    StaffEmployee      employee     = Context.GetObject <StaffEmployee>(new System.Guid(employeeId));
                    newTable.Cell(i + 1, 1).Range.Text = employee.DisplayString;
                    newTable.Cell(i + 1, 1).Range.Bold = 0;
                    newTable.Cell(i + 1, 2).Range.Text = Convert.ToDateTime(commentTable["Date"] + "").ToShortDateString();
                    if (commentTable["Result"] + "" == "0")
                    {
                        temp = "Согласовано";
                    }
                    else
                    {
                        temp = "Не согласовано";
                    }
                    newTable.Cell(i + 1, 2).Range.Bold = 0;
                    newTable.Cell(i + 1, 3).Range.Text = temp;
                    newTable.Cell(i + 1, 3).Range.Bold = 0;
                    newTable.Cell(i + 1, 4).Range.Text = commentTable["Comment"] + "";
                    newTable.Cell(i + 1, 4).Range.Bold = 0;
                    i++;
                }
            }
            catch (Exception ex) {
                UIService.ShowError(ex, "Во время создания файла произошла ошибка");
            }

            /*удал¤ем временный файл
             * if (System.IO.File.Exists(oFilePath))
             * System.IO.File.Delete(oFilePath);*/

            //закрываем ворд
            //oApplication.Quit(ref oMissing, ref oMissing, ref oMissing);
        }
Esempio n. 15
0
        /// <summary>
        /// Осуществляет обновление доработки в Паспорте прибора на основании данных Конструктора справочников
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BindImprov_Click(object sender, EventArgs e)
        {
            if (this.TypeName.Text == "")
            {
                MessageBox.Show("Укажите тип прибора!");
                return;
            }

            if (this.DocName.Text == "")
            {
                MessageBox.Show("Укажите документ-основание!");
                return;
            }

            StatusStrip.Items["StatusText"].Text = "Процесс начат...";
            StatusStrip.Update();

            // Получение записи справочника ремонтных работ и доработок
            //ObjectContext Context = Session.CreateContext();
            // Получение справочника "Ремонтные работы и доработки"
            //IBaseUniversalService baseUniversalService = Context.GetService<IBaseUniversalService>();
            //BaseUniversal baseUniversal = Context.GetObject<BaseUniversal>(RefBaseUniversal.ID);

            CardData baseUniversal = Session.CardManager.GetCardData(new Guid("{4538149D-1FC7-4D41-A104-890342C6B4F8}"));

            if (!baseUniversal.Sections[new Guid("{A1DCE6C1-DB96-4666-B418-5A075CDB02C9}")].GetAllRows().Any(r => r.Id == new Guid("{43A6DA44-899C-47D8-9567-2185E05D8524}")))
            {
                StatusStrip.Items["StatusText"].Text = "Ошибка! Не найден справочник ремонтных работ и доработок...";
                StatusStrip.Update();
                return;
            }

            // Поиск записей справочника
            SearchQuery searchQuery = Session.CreateSearchQuery();

            searchQuery.CombineResults = ConditionGroupOperation.And;

            CardTypeQuery typeQuery = searchQuery.AttributiveSearch.CardTypeQueries.AddNew(DocsVision.BackOffice.CardLib.CardDefs.CardBaseUniversalItem.ID);

            SectionQuery sectionQuery = typeQuery.SectionQueries.AddNew(DocsVision.BackOffice.CardLib.CardDefs.CardBaseUniversalItem.System.ID);

            sectionQuery.Operation = SectionQueryOperation.And;

            sectionQuery.ConditionGroup.Operation = ConditionGroupOperation.And;
            ConditionGroup ConditionGroup = sectionQuery.ConditionGroup.ConditionGroups.AddNew();

            ConditionGroup.Operation = ConditionGroupOperation.And;
            ConditionGroup.Conditions.AddNew(DocsVision.BackOffice.CardLib.CardDefs.CardBaseUniversalItem.System.Kind, FieldType.RefId, ConditionOperation.Equals, new Guid("{F4650B71-B131-41D2-AAFA-8DA1101ACA52}"));

            SectionQuery sectionQuery2 = typeQuery.SectionQueries.AddNew(new Guid("{3F9F3C1D-1CF1-4E71-BBE4-31D6AAD94EF7}"));

            sectionQuery2.Operation = SectionQueryOperation.And;

            sectionQuery2.ConditionGroup.Operation = ConditionGroupOperation.And;
            ConditionGroup ConditionGroup2 = sectionQuery2.ConditionGroup.ConditionGroups.AddNew();

            ConditionGroup2.Operation = ConditionGroupOperation.And;
            ConditionGroup2.Conditions.AddNew("BaseDocument", FieldType.RefId, ConditionOperation.Equals, Document.Id);
            ConditionGroup2.Conditions.AddNew("Status", FieldType.Int, ConditionOperation.Equals, 0);

            SectionQuery sectionQuery3 = typeQuery.SectionQueries.AddNew(new Guid("{E6DB53B7-7677-4978-8562-6B17917516A6}"));

            sectionQuery3.Operation = SectionQueryOperation.And;

            sectionQuery3.ConditionGroup.Operation = ConditionGroupOperation.And;
            ConditionGroup ConditionGroup3 = sectionQuery3.ConditionGroup.ConditionGroups.AddNew();

            ConditionGroup3.Operation = ConditionGroupOperation.And;
            ConditionGroup3.Conditions.AddNew("DeviceID", FieldType.RefId, ConditionOperation.Equals, DeviceType.Id);

            searchQuery.Limit = 0;
            string             query = searchQuery.GetXml();
            CardDataCollection CardBaseUniversalItems = Session.CardManager.FindCards(query);
            CardData           ItemCard = null;
            RowData            ItemRow  = null;

            if (CardBaseUniversalItems.Count() == 0)
            {
                StatusStrip.Items["StatusText"].Text = "Ошибка! Не найдена соответствующая карточка ремонтных работ и доработок...";
                StatusStrip.Update();
                return;
            }
            if (CardBaseUniversalItems.Count() > 1)
            {
                StatusStrip.Items["StatusText"].Text = "Ошибка! Найдено несколько подходящих карточек ремонтных работ и доработок...";
                StatusStrip.Update();
                return;
            }
            if (CardBaseUniversalItems.Count() == 1)
            {
                ItemCard = CardBaseUniversalItems.First();
                RowData ItemType = baseUniversal.Sections[new Guid("{A1DCE6C1-DB96-4666-B418-5A075CDB02C9}")].GetAllRows().First(r => r.Id == new Guid("{43A6DA44-899C-47D8-9567-2185E05D8524}"));
                ItemRow = ItemType.ChildSections[new Guid("{1B1A44FB-1FB1-4876-83AA-95AD38907E24}")].Rows.First(r => (Guid)r.GetGuid("ItemCard") == ItemCard.Id);
                if (ItemRow.IsNull())
                {
                    StatusStrip.Items["StatusText"].Text = "Ошибка! Не найдена соответствующая запись справочника ремонтных работ и доработок...";
                    StatusStrip.Update();
                    return;
                }
                else
                {
                    StatusStrip.Items["StatusText"].Text = "Запись найдена: " + ItemRow.GetString("Name") + "...";
                    StatusStrip.Update();
                }
            }


            Guid              DevicePassportTypeID     = new Guid("{42826E25-AD0E-4D9C-8B18-CD88E6796972}");
            CardData          CardTypeDictionary       = Session.CardManager.GetDictionaryData(RefTypes.ID);
            SectionData       DocumentTypes            = CardTypeDictionary.Sections[RefTypes.DocumentTypes.ID];
            RowData           DevicePassportType       = DocumentTypes.GetRow(DevicePassportTypeID);
            RowDataCollection DevicePassportProperties = DevicePassportType.ChildSections[RefTypes.Properties.ID].Rows;

            SearchQuery searchQuery2 = Session.CreateSearchQuery();

            searchQuery2.CombineResults = ConditionGroupOperation.And;

            CardTypeQuery typeQuery2    = searchQuery2.AttributiveSearch.CardTypeQueries.AddNew(CardOrd.ID);
            SectionQuery  sectionQuery4 = typeQuery2.SectionQueries.AddNew(CardOrd.MainInfo.ID);

            sectionQuery4.Operation = SectionQueryOperation.And;
            sectionQuery4.ConditionGroup.Operation = ConditionGroupOperation.And;
            sectionQuery4.ConditionGroup.Conditions.AddNew("Type", FieldType.RefId, ConditionOperation.Equals, DevicePassportTypeID);

            sectionQuery4           = typeQuery2.SectionQueries.AddNew(CardOrd.Properties.ID);
            sectionQuery4.Operation = SectionQueryOperation.And;
            sectionQuery4.ConditionGroup.Operation = ConditionGroupOperation.And;
            sectionQuery4.ConditionGroup.Conditions.AddNew("Name", FieldType.String, ConditionOperation.Equals, "Прибор");
            sectionQuery4.ConditionGroup.Conditions.AddNew("Value", FieldType.RefId, ConditionOperation.Equals, DeviceType.Id);

            sectionQuery4           = typeQuery2.SectionQueries.AddNew(CardOrd.SelectedValues.ID);
            sectionQuery4.Operation = SectionQueryOperation.And;
            sectionQuery4.ConditionGroup.Operation = ConditionGroupOperation.And;
            sectionQuery4.ConditionGroup.Conditions.AddNew("SelectedValue", FieldType.RefCardId, ConditionOperation.Equals, Document.Id);

            // Получение текста запроса
            searchQuery2.Limit = 0;
            string query2 = searchQuery2.GetXml();

            Console.WriteLine(query2);
            Console.ReadLine();
            CardDataCollection coll = Session.CardManager.FindCards(query2);

            Clear();

            StatusStrip.Items["StatusText"].Text = "Найдено паспортов: " + coll.Count.ToString() + "...";
            StatusStrip.Update();

            int i = 0;

            for (i = 0; i < coll.Count; i++)
            {
                CardData Card = coll[i];
                Card.ForceUnlock();
                StatusStrip.Items["StatusText"].Text = i.ToString() + " из " + coll.Count + ". " + Card.Description;
                StatusStrip.Update();


                SectionData       Properties  = Card.Sections[CardOrd.Properties.ID];
                RowDataCollection DocumentCol = Properties.FindRow("@Name = 'Документ'").ChildSections[CardOrd.SelectedValues.ID].Rows;
                RowData           DocumentRow = DocumentCol.First(r => new Guid(r.GetString("SelectedValue")).Equals(Document.Id));
                if (DocumentRow != null)
                {
                    RowDataCollection Assembly   = Properties.FindRow("@Name = 'Сборочный узел'").ChildSections[CardOrd.SelectedValues.ID].Rows;
                    RowDataCollection RepareItem = Properties.FindRow("@Name = 'Запись справочника ремонтных работ и доработок'").ChildSections[CardOrd.SelectedValues.ID].Rows;
                    RowDataCollection Indication = Properties.FindRow("@Name = 'Указание'").ChildSections[CardOrd.SelectedValues.ID].Rows;
                    RowDataCollection Check      = Properties.FindRow("@Name = 'Выполнено'").ChildSections[CardOrd.SelectedValues.ID].Rows;
                    RowDataCollection CheckDate  = Properties.FindRow("@Name = 'Дата выполнения'").ChildSections[CardOrd.SelectedValues.ID].Rows;
                    RowDataCollection Comments   = Properties.FindRow("@Name = 'Комментарии'").ChildSections[CardOrd.SelectedValues.ID].Rows;

                    if (DocumentCol.Count != Assembly.Count)
                    {
                        foreach (RowData Doc in DocumentCol)
                        {
                            int Order = (int)Doc.GetInt32("Order");
                            if (Assembly.FirstOrDefault(r => r.GetInt32("Order") == Order).IsNull())
                            {
                                RowData NewRow = Assembly.AddNew();
                                NewRow.SetInt32("Order", Order);
                            }
                        }
                    }

                    if (DocumentCol.Count != RepareItem.Count)
                    {
                        foreach (RowData Doc in DocumentCol)
                        {
                            int Order = (int)Doc.GetInt32("Order");
                            if (RepareItem.FirstOrDefault(r => r.GetInt32("Order") == Order).IsNull())
                            {
                                RowData NewRow = RepareItem.AddNew();
                                NewRow.SetInt32("Order", Order);
                            }
                        }
                    }

                    if (DocumentCol.Count != Indication.Count)
                    {
                        foreach (RowData Doc in DocumentCol)
                        {
                            int Order = (int)Doc.GetInt32("Order");
                            if (Indication.FirstOrDefault(r => r.GetInt32("Order") == Order).IsNull())
                            {
                                RowData NewRow = Indication.AddNew();
                                NewRow.SetInt32("Order", Order);
                            }
                        }
                    }

                    if (DocumentCol.Count != Check.Count)
                    {
                        foreach (RowData Doc in DocumentCol)
                        {
                            int Order = (int)Doc.GetInt32("Order");
                            if (Check.FirstOrDefault(r => r.GetInt32("Order") == Order).IsNull())
                            {
                                RowData NewRow = Check.AddNew();
                                NewRow.SetInt32("Order", Order);
                            }
                        }
                    }

                    if (DocumentCol.Count != CheckDate.Count)
                    {
                        foreach (RowData Doc in DocumentCol)
                        {
                            int Order = (int)Doc.GetInt32("Order");
                            if (CheckDate.FirstOrDefault(r => r.GetInt32("Order") == Order).IsNull())
                            {
                                RowData NewRow = CheckDate.AddNew();
                                NewRow.SetInt32("Order", Order);
                            }
                        }
                    }

                    if (DocumentCol.Count != Comments.Count)
                    {
                        foreach (RowData Doc in DocumentCol)
                        {
                            int Order = (int)Doc.GetInt32("Order");
                            if (Comments.FirstOrDefault(r => r.GetInt32("Order") == Order).IsNull())
                            {
                                RowData NewRow = Comments.AddNew();
                                NewRow.SetInt32("Order", Order);
                            }
                        }
                    }

                    int CurrentOrder = (int)DocumentRow.GetInt32("Order");

                    RepareItem.First(r => r.GetInt32("Order") == CurrentOrder).SetGuid("SelectedValue", ItemRow.Id);

                    if (!ItemCard.Sections[new Guid("{3F9F3C1D-1CF1-4E71-BBE4-31D6AAD94EF7}")].FirstRow.GetGuid("AssemblyUnit").IsNull())
                    {
                        Assembly.First(r => r.GetInt32("Order") == CurrentOrder).SetGuid("SelectedValue", (Guid)ItemCard.Sections[new Guid("{3F9F3C1D-1CF1-4E71-BBE4-31D6AAD94EF7}")].FirstRow.GetGuid("AssemblyUnit"));
                    }
                    if (!ItemRow.GetString("Description").IsNull())
                    {
                        Indication.First(r => r.GetInt32("Order") == CurrentOrder).SetString("SelectedValue", ItemRow.GetString("Description"));
                    }
                }
                Clear();
            }

            StatusStrip.Items["StatusText"].Text = i.ToString() + " карточек успешно обработано.";
            StatusStrip.Update();
        }
Esempio n. 16
0
        /// <summary>
        /// Новый прибор.
        /// </summary>
        public Device(MyBaseCard Card, string DNID, string DTID, bool OA, bool R, bool C, bool V, bool WR, string A, string Com, string PL, bool W, string S, string WO)
        {
            this.Card    = Card;
            DeviceItemID = DNID;

            if (OA == false)
            {
                DevicePassportID  = DNID == "" ? "" : ApplicationCard.UniversalCard.GetItemPropertyValue(DNID.ToGuid(), "Паспорт прибора").ToString();
                DeviceNumber      = DNID == "" ? "" : ApplicationCard.UniversalCard.GetItemName(DNID.ToGuid());
                ShortDeviceNumber = DNID == "" ? "" : ApplicationCard.UniversalCard.GetItemPropertyValue(DNID.ToGuid(), "Номер прибора").ToString();
                string Year = DNID == "" ? "" : ApplicationCard.UniversalCard.GetItemPropertyValue(DNID.ToGuid(), "Год прибора").ToString();
                ShortDeviceNumber = ShortDeviceNumber.Length == 4 ? ShortDeviceNumber : ShortDeviceNumber + "/" + Year;
                RowData SpecConditions = Card.CardScript.Session.CardManager.GetCardData(new Guid(DevicePassportID)).Sections[CardOrd.Properties.ID].FindRow("@Name = 'Особые условия по СО и ГО'");
                SpecialConditions = SpecConditions.GetString("Value") != null?SpecConditions.GetString("Value") : "";
            }
            else
            {
                DevicePassportID = "";
                DeviceNumber     = "";
            }

            DeviceTypeID    = DTID == "" ? "" : DTID;
            DeviceType      = DTID == "" ? "" : ApplicationCard.UniversalCard.GetItemName(DTID.ToGuid());
            OnlyAccessories = OA;
            Repair          = R;
            Calibrate       = C;
            Verify          = V;
            WarrantyRepair  = WR;
            Wash            = W;
            Accessories     = A == "" ? "" : A;
            Comments        = Com == "" ? "" : Com;
            Services        = FormattingService(this.Repair, this.Calibrate, this.Verify);
            PackedListData  = PL == "" ? "" : PL;
            PackedListID    = "";
            Sensors         = S == "" ? "" : S;
            ServiceCardID   = WO;
            DeviceName      = this.DeviceNumber == "" ? "Комплектующие для " + this.DeviceType : this.DeviceType + " №" + this.ShortDeviceNumber;

            if (Sensors != "")
            {
                List <String> SelectedSensors = Sensors.Split(';').Where(s => !String.IsNullOrEmpty(s.Trim())).ToList();
                for (Int32 j = 0; j < SelectedSensors.Count; j++)
                {
                    String[] Sensor = SelectedSensors[j].Trim().Split(' ');
                    if (Sensor.Length >= 2)
                    {
                        RowData        CurrentDeviceRow      = GetDeviceRow(Sensor[1], Sensor[0]);
                        string         CurrentPassportId     = CurrentDeviceRow.ChildSections[0].FindRow("@Name = 'Паспорт прибора'").GetString("Value");
                        string         CurrentDeviceTypeID   = CurrentDeviceRow.ChildSections[0].FindRow("@Name = 'Наименование прибора'").GetString("Value");
                        string         CurrentDeviceTypeName = ApplicationCard.UniversalCard.GetItemName(CurrentDeviceTypeID);
                        AdditionalWare NewWare = new AdditionalWare(Card.CardScript, SelectedSensors[j], CurrentPassportId, CurrentDeviceRow.Id.ToString(), CurrentDeviceTypeID, CurrentDeviceTypeName);
                        AdditionalWaresList.Add(NewWare);
                    }
                }
            }

            if (ServiceCardID != "")
            {
                CardData ServiceCard = Card.CardScript.Session.CardManager.GetCardData(new Guid(ServiceCardID));
                RowData  Adjustment  = ServiceCard.Sections[RefServiceCard.Adjustment.ID].FirstRow;
                RowData  MainInfo    = ServiceCard.Sections[RefServiceCard.MainInfo.ID].FirstRow;
                this.VoidWarranty        = Adjustment.GetBoolean(RefServiceCard.Adjustment.VoidWarranty) == null ? false : (bool)Adjustment.GetBoolean(RefServiceCard.Adjustment.VoidWarranty);
                this.DoubleCost          = Adjustment.GetBoolean(RefServiceCard.Adjustment.DoubleCost) == null ? false : (bool)Adjustment.GetBoolean(RefServiceCard.Adjustment.DoubleCost);
                this.DescriptionOfReason = Adjustment.GetString(RefServiceCard.Adjustment.DescriptionOfReason) == null ? "" : Adjustment.GetString(RefServiceCard.Adjustment.DescriptionOfReason).ToString();
                this.RefusalToRepair     = (int)MainInfo.GetInt32(RefServiceCard.MainInfo.Status) == (int)RefServiceCard.MainInfo.State.Failure ? true : false;
            }
        }
Esempio n. 17
0
        public static Boolean Synchronize(UserSession Session, String CardID)
        {
            logger.Info("cardId='{0}'", CardID);
            using (new Impersonator(ServerExtension.Domain, ServerExtension.User, ServerExtension.SecurePassword))
            {
                Guid CardId = new Guid(CardID);
                switch (Session.CardManager.GetCardState(CardId))
                {
                case ObjectState.Existing:
                    CardData Card = Session.CardManager.GetCardData(CardId);

                    Card.UnlockCard();

                    ExtraCard Extra = Card.GetExtraCard();
                    if (Extra.IsNull())
                    {
                        logger.Info("Синхронизация не производилась, неверный тип карточки.");
                        return(false);
                    }

                    if (String.IsNullOrEmpty(Extra.Name) || String.IsNullOrEmpty(Extra.ShortCategory) || (String.IsNullOrEmpty(Extra.Code) && !(Extra is ExtraCardMarketingFiles)))
                    {
                        logger.Info("Синхронизация не производилась, не заполнены обязательные поля.");
                        return(false);
                    }


                    String  Digest    = Extra.ToString();
                    Boolean FileSynch = false;

                    /*Синхронизация с реестром только для КД и ТД*/
                    if (Extra is ExtraCardCD || Extra is ExtraCardTD)
                    {
                        Guid RegItemId = Extra.RegID ?? Guid.Empty;
                        if (RegItemId != Guid.Empty)
                        {
                            try
                            {
                                RowData RegItem = Session.CardManager.GetDictionaryData(RefUniversal.ID).Sections[RefUniversal.Item.ID].GetRow(RegItemId);
                                if (RegItem.GetString(RefUniversal.Item.Name) != Digest)
                                {
                                    logger.Info("Требуется синхронизация...");
                                    RegItem.SetString(RefUniversal.Item.Name, Digest);
                                    foreach (RowData rowData in RegItem.ChildSections[0].Rows)
                                    {
                                        String PropertyName = rowData.GetString(RefUniversal.TypeProperties.Name);
                                        if ((PropertyName == "Код СКБ" && Extra is ExtraCardCD) || (PropertyName == "Обозначение документа" && Extra is ExtraCardTD))
                                        {
                                            rowData.SetString(RefUniversal.TypeProperties.Value, Extra.CodeId);
                                            rowData.SetString(RefUniversal.TypeProperties.DisplayValue, Extra.Code);
                                        }
                                        else if (PropertyName == "Тип документа")
                                        {
                                            rowData.SetString(RefUniversal.TypeProperties.Value, Extra.Category);
                                            rowData.SetString(RefUniversal.TypeProperties.DisplayValue, Extra.Category);
                                        }
                                        else if (PropertyName == "Версия")
                                        {
                                            rowData.SetString(RefUniversal.TypeProperties.Value, Extra.Version);
                                            rowData.SetString(RefUniversal.TypeProperties.DisplayValue, Extra.Version);
                                        }
                                    }
                                    logger.Info("Синхронизация с реестром выполнена.");
                                    FileSynch = true;
                                }
                                else
                                {
                                    logger.Info("Синхронизация не требуется.");
                                }
                            }
                            catch (Exception Ex) { logger.WarnException("Не удалось синхронизировать с записью реестра: " + RegItemId, Ex); }
                        }
                        else
                        {
                            logger.Info("Регистрация в реестре");
                            RowData RegisterRow = Session.CardManager.GetDictionaryData(RefUniversal.ID).GetItemTypeRow(MyHelper.RefItem_TechDocRegister);

                            SubSectionData RegisterTypeProperties = RegisterRow.ChildSections[RefUniversal.TypeProperties.ID];

                            RowData RegistrarUnit = Card.Sections[CardOrd.Properties.ID].GetProperty("Подразделение регистратора");
                            RowData Device        = Card.Sections[CardOrd.Properties.ID].GetProperty("Прибор");

                            RowData RegItem = RegisterRow.ChildSections[RefUniversal.Item.ID].Rows.AddNew();
                            RegItem.SetString(RefUniversal.Item.Name, Card.Description);
                            RegItem.SetString(RefUniversal.Item.Comments, Extra.Number);

                            RowDataCollection PropertiesSubSectionRows = RegItem.ChildSections[RefUniversal.Properties.ID].Rows;
                            RowData           ItemPropertyRow          = PropertiesSubSectionRows.AddNew();
                            ItemPropertyRow.SetGuid(RefUniversal.Properties.Property, RegisterTypeProperties.FindRow("@Name='" + (Extra is ExtraCardCD ? "Код СКБ" : "Обозначение документа") + "'").Id);
                            ItemPropertyRow.SetString(RefUniversal.Properties.DisplayValue, Extra.Code);
                            ItemPropertyRow.SetValue(RefUniversal.Properties.Value, Extra.CodeId, FieldType.Variant);
                            ItemPropertyRow = PropertiesSubSectionRows.AddNew();
                            ItemPropertyRow.SetGuid(RefUniversal.Properties.Property, RegisterTypeProperties.FindRow("@Name='Тип документа'").Id);
                            ItemPropertyRow.SetString(RefUniversal.Properties.DisplayValue, Extra.Category);
                            ItemPropertyRow.SetValue(RefUniversal.Properties.Value, Extra.Category, FieldType.Variant);
                            ItemPropertyRow = PropertiesSubSectionRows.AddNew();
                            ItemPropertyRow.SetGuid(RefUniversal.Properties.Property, RegisterTypeProperties.FindRow("@Name='Версия'").Id);
                            ItemPropertyRow.SetString(RefUniversal.Properties.DisplayValue, Extra.Version);
                            ItemPropertyRow.SetValue(RefUniversal.Properties.Value, Extra.Version, FieldType.Variant);
                            ItemPropertyRow = PropertiesSubSectionRows.AddNew();
                            ItemPropertyRow.SetGuid(RefUniversal.Properties.Property, RegisterTypeProperties.FindRow("@Name='Статус'").Id);
                            ItemPropertyRow.SetString(RefUniversal.Properties.DisplayValue, ((DocumentState)Extra.Status).GetDescription());
                            ItemPropertyRow.SetValue(RefUniversal.Properties.Value, (Int32)(DocumentState)Extra.Status, FieldType.Variant);
                            ItemPropertyRow = PropertiesSubSectionRows.AddNew();
                            ItemPropertyRow.SetGuid(RefUniversal.Properties.Property, RegisterTypeProperties.FindRow("@Name='Подразделение регистратора'").Id);
                            ItemPropertyRow.SetString(RefUniversal.Properties.DisplayValue, RegistrarUnit.GetString(CardOrd.Properties.DisplayValue));
                            ItemPropertyRow.SetValue(RefUniversal.Properties.Value, RegistrarUnit.GetString(CardOrd.Properties.Value), FieldType.Variant);
                            ItemPropertyRow = PropertiesSubSectionRows.AddNew();
                            ItemPropertyRow.SetGuid(RefUniversal.Properties.Property, RegisterTypeProperties.FindRow("@Name='Прибор'").Id);
                            ItemPropertyRow.SetString(RefUniversal.Properties.DisplayValue, Device.GetString(CardOrd.Properties.DisplayValue));
                            ItemPropertyRow.SetValue(RefUniversal.Properties.Value, Device.ChildSections[CardOrd.SelectedValues.ID].FirstRow.GetString(CardOrd.SelectedValues.SelectedValue), FieldType.Variant);
                            ItemPropertyRow = PropertiesSubSectionRows.AddNew();
                            ItemPropertyRow.SetGuid(RefUniversal.Properties.Property, RegisterTypeProperties.FindRow("@Name='Ссылка на карточку документа'").Id);
                            ItemPropertyRow.SetString(RefUniversal.Properties.DisplayValue, Extra.Card.Description);
                            ItemPropertyRow.SetValue(RefUniversal.Properties.Value, Extra.Card.Id, FieldType.Variant);
                            ItemPropertyRow = PropertiesSubSectionRows.AddNew();
                            ItemPropertyRow.SetGuid(RefUniversal.Properties.Property, RegisterTypeProperties.FindRow("@Name='Файлы документа'").Id);
                            ItemPropertyRow.SetString(RefUniversal.Properties.DisplayValue, Extra.Path);
                            ItemPropertyRow.SetValue(RefUniversal.Properties.Value, Extra.Card.Id, FieldType.Variant);

                            Extra.RegID = RegItem.Id;
                            logger.Info("В реестр добавлена запись: " + Card.Description);
                        }
                    }
                    else
                    {
                        FileSynch = true;
                    }

                    if (FileSynch)
                    {
                        logger.Info("Синхронизация пути...");
                        String OldPath = Extra.Path;
                        logger.Info("Старый путь: " + OldPath);
                        String NewPath = String.Empty;
                        logger.Info("Новый путь: " + NewPath);
                        if (Directory.Exists(OldPath))
                        {
                            DirectoryInfo OldFolder    = new DirectoryInfo(OldPath);
                            DirectoryInfo ParentFolder = OldFolder.Parent;
                            if (ParentFolder != null)
                            {
                                logger.Info("Старый путь:" + OldPath);
                                NewPath = MyHelper.RemoveInvalidFileNameChars(Digest);
                                if (NewPath != Digest)
                                {
                                    logger.Info("Удалены недопустимые символы: " + Digest);
                                }
                                NewPath = Path.Combine(ParentFolder.FullName, NewPath);
                                String TempPath = Path.Combine(ParentFolder.FullName, Path.GetRandomFileName());
                                logger.Info("Временный путь:" + TempPath);
                                logger.Info("Новый путь:" + NewPath + @"\");
                                try
                                {
                                    logger.Info("Перемещение во временную папку");
                                    Directory.Move(OldPath, TempPath);
                                    try
                                    {
                                        logger.Info("Перемещение в новую папку");
                                        Directory.Move(TempPath, NewPath);
                                    }
                                    catch (Exception Ex)
                                    {
                                        logger.WarnException("Перемещение не удалось!", Ex);
                                        try
                                        {
                                            logger.Info("Перемещение в старую папку");
                                            Directory.Move(TempPath, OldPath);
                                        }
                                        catch (Exception SubEx)
                                        {
                                            logger.Warn("Перемещение не удалось!");
                                            logger.ErrorException("Перемещение не удалось!", SubEx);
                                            NewPath = String.Empty;
                                        }
                                    }
                                }
                                catch (Exception Ex)
                                {
                                    logger.WarnException("Перемещение не удалось!", Ex);
                                    NewPath = String.Empty;
                                }

                                if (!String.IsNullOrWhiteSpace(NewPath))
                                {
                                    if (!(Extra is ExtraCardMarketingFiles))
                                    {
                                        Extra.Path = NewPath + @"\";
                                    }
                                    logger.Info("Синхронизация пути выполнена");
                                }
                                else
                                {
                                    logger.Warn("Синхронизация пути не выполнена");
                                }
                            }
                            else
                            {
                                logger.Warn("Отсутствует родительская папка!");
                            }
                        }
                        else
                        {
                            logger.Info("Отсутствует путь для синхронизации!");
                        }
                    }
                    return(true);

                default:
                    return(false);
                }
            }
        }
Esempio n. 18
0
        private void AddImprov_Click(object sender, EventArgs e)
        {
            RowData           PartyRow            = null;
            CardData          UniversalDictionary = Session.CardManager.GetCardData(new Guid("{B2A438B7-8BB3-4B13-AF6E-F2F8996E148B}"));
            List <RowData>    PartyItemRows       = new List <RowData>();
            RowDataCollection PartyRowsCollection;

            if (!Document.Sections.Any(r => r.Id == new Guid("{A8F93D97-496B-4675-B520-058B919146B7}")))
            {
                PartyRowsCollection = Document.Sections[new Guid("{5B6B407E-3D72-49E7-97D9-8E1E028C7274}")].Rows.First(r => r.GetString("Name") == "Партия").ChildSections[new Guid("{E6F5105F-8BD8-4500-9780-60D7C1402DDB}")].Rows;
                foreach (RowData CurrentRow in PartyRowsCollection)
                {
                    PartyItemRows.Add(UniversalDictionary.GetItemRow((Guid)CurrentRow.GetGuid("SelectedValue")));
                }
            }
            else
            {
                PartyRowsCollection = Document.Sections[new Guid("{A8F93D97-496B-4675-B520-058B919146B7}")].Rows;
                foreach (RowData CurrentRow in PartyRowsCollection)
                {
                    PartyItemRows.Add(UniversalDictionary.GetItemRow((Guid)CurrentRow.GetGuid("PartyId")));
                }
            }


            //List<RowData> PartyItemRows = PartyRowsCollection.Select(r => UniversalDictionary.GetItemRow((Guid)r.GetGuid("Id"))).ToList();

            if (PartyItemRows.Any(r => UniversalDictionary.GetItemPropertyValue(r.Id, "Наименование прибора").ToGuid() == DeviceType.Id))
            {
                PartyRow = PartyItemRows.FirstOrDefault(r => UniversalDictionary.GetItemPropertyValue(r.Id, "Наименование прибора").ToGuid() == DeviceType.Id);
            }
            else
            {
                StatusStrip.Items["StatusText"].Text = "Ошибка! В Разрешении не указана партия для текущего прибора.";
                StatusStrip.Update();
                switch (MessageBox.Show("Внести доработку во все приборы в эксплуатации?", "Ошибка", MessageBoxButtons.YesNo))
                {
                case DialogResult.Yes:
                    StatusStrip.Items["StatusText"].Text = "Продолжение работы...";
                    StatusStrip.Update();
                    break;

                case DialogResult.No:
                    return;

                    break;
                }
            }
            List <Guid> ImprovPartiesGuid = new List <Guid>();

            if (!PartyRow.IsNull())
            {
                RowData PartyDicType                = UniversalDictionary.Sections[new Guid("{5E3ED23A-2B5E-47F2-887C-E154ACEAFB97}")].Rows.First(r => r.GetString("Name") == "Справочник партий");
                IEnumerable <RowData> AllParties    = PartyDicType.ChildSections[new Guid("{DD20BF9B-90F8-4D9A-9553-5B5F17AD724E}")].Rows.Where(r => (UniversalDictionary.GetItemPropertyValue(r.Id, "Наименование прибора").ToGuid() == DeviceType.Id) && (!UniversalDictionary.GetItemPropertyValue(r.Id, "Год начала выпуска").IsNull()));
                PartyComparer         PC            = new PartyComparer();
                List <RowData>        ImprovParties = AllParties.Where(r => PC.Compare(r.GetString("Name"), PartyRow.GetString("Name")) == 1).ToList();
                foreach (RowData CurrentParty in ImprovParties)
                {
                    ImprovPartiesGuid.Add(CurrentParty.Id);
                }
            }



            CardData baseUniversal = Session.CardManager.GetCardData(new Guid("{4538149D-1FC7-4D41-A104-890342C6B4F8}"));

            if (!baseUniversal.Sections[new Guid("{A1DCE6C1-DB96-4666-B418-5A075CDB02C9}")].GetAllRows().Any(r => r.Id == new Guid("{43A6DA44-899C-47D8-9567-2185E05D8524}")))
            {
                StatusStrip.Items["StatusText"].Text = "Ошибка! Не найден справочник ремонтных работ и доработок...";
                StatusStrip.Update();
                return;
            }

            // Поиск записей справочника
            SearchQuery searchQuery = Session.CreateSearchQuery();

            searchQuery.CombineResults = ConditionGroupOperation.And;

            CardTypeQuery typeQuery = searchQuery.AttributiveSearch.CardTypeQueries.AddNew(DocsVision.BackOffice.CardLib.CardDefs.CardBaseUniversalItem.ID);

            SectionQuery sectionQuery = typeQuery.SectionQueries.AddNew(DocsVision.BackOffice.CardLib.CardDefs.CardBaseUniversalItem.System.ID);

            sectionQuery.Operation = SectionQueryOperation.And;

            sectionQuery.ConditionGroup.Operation = ConditionGroupOperation.And;
            ConditionGroup ConditionGroup = sectionQuery.ConditionGroup.ConditionGroups.AddNew();

            ConditionGroup.Operation = ConditionGroupOperation.And;
            ConditionGroup.Conditions.AddNew(DocsVision.BackOffice.CardLib.CardDefs.CardBaseUniversalItem.System.Kind, FieldType.RefId, ConditionOperation.Equals, new Guid("{F4650B71-B131-41D2-AAFA-8DA1101ACA52}"));

            SectionQuery sectionQuery2 = typeQuery.SectionQueries.AddNew(new Guid("{3F9F3C1D-1CF1-4E71-BBE4-31D6AAD94EF7}"));

            sectionQuery2.Operation = SectionQueryOperation.And;

            sectionQuery2.ConditionGroup.Operation = ConditionGroupOperation.And;
            ConditionGroup ConditionGroup2 = sectionQuery2.ConditionGroup.ConditionGroups.AddNew();

            ConditionGroup2.Operation = ConditionGroupOperation.And;
            ConditionGroup2.Conditions.AddNew("BaseDocument", FieldType.RefId, ConditionOperation.Equals, Document.Id);
            ConditionGroup2.Conditions.AddNew("Status", FieldType.Int, ConditionOperation.Equals, 0);

            SectionQuery sectionQuery3 = typeQuery.SectionQueries.AddNew(new Guid("{E6DB53B7-7677-4978-8562-6B17917516A6}"));

            sectionQuery3.Operation = SectionQueryOperation.And;

            sectionQuery3.ConditionGroup.Operation = ConditionGroupOperation.And;
            ConditionGroup ConditionGroup3 = sectionQuery3.ConditionGroup.ConditionGroups.AddNew();

            ConditionGroup3.Operation = ConditionGroupOperation.And;
            ConditionGroup3.Conditions.AddNew("DeviceID", FieldType.RefId, ConditionOperation.Equals, DeviceType.Id);

            searchQuery.Limit = 0;
            string             query = searchQuery.GetXml();
            CardDataCollection CardBaseUniversalItems = Session.CardManager.FindCards(query);
            CardData           ItemCard = null;
            RowData            ItemRow  = null;

            if (CardBaseUniversalItems.Count() == 0)
            {
                StatusStrip.Items["StatusText"].Text = "Ошибка! Не найдена соответствующая карточка ремонтных работ и доработок...";
                StatusStrip.Update();
                return;
            }
            if (CardBaseUniversalItems.Count() > 1)
            {
                StatusStrip.Items["StatusText"].Text = "Ошибка! Найдено несколько подходящих карточек ремонтных работ и доработок...";
                StatusStrip.Update();
                return;
            }
            if (CardBaseUniversalItems.Count() == 1)
            {
                ItemCard = CardBaseUniversalItems.First();
                RowData ItemType = baseUniversal.Sections[new Guid("{A1DCE6C1-DB96-4666-B418-5A075CDB02C9}")].GetAllRows().First(r => r.Id == new Guid("{43A6DA44-899C-47D8-9567-2185E05D8524}"));
                ItemRow = ItemType.ChildSections[new Guid("{1B1A44FB-1FB1-4876-83AA-95AD38907E24}")].Rows.First(r => (Guid)r.GetGuid("ItemCard") == ItemCard.Id);
                if (ItemRow.IsNull())
                {
                    StatusStrip.Items["StatusText"].Text = "Ошибка! Не найдена соответствующая запись справочника ремонтных работ и доработок...";
                    StatusStrip.Update();
                    return;
                }
                else
                {
                    StatusStrip.Items["StatusText"].Text = "Запись найдена: " + ItemRow.GetString("Name") + "...";
                    StatusStrip.Update();
                }
            }

            Guid              DevicePassportTypeID     = new Guid("{42826E25-AD0E-4D9C-8B18-CD88E6796972}");
            CardData          CardTypeDictionary       = Session.CardManager.GetDictionaryData(RefTypes.ID);
            SectionData       DocumentTypes            = CardTypeDictionary.Sections[RefTypes.DocumentTypes.ID];
            RowData           DevicePassportType       = DocumentTypes.GetRow(DevicePassportTypeID);
            RowDataCollection DevicePassportProperties = DevicePassportType.ChildSections[RefTypes.Properties.ID].Rows;

            SearchQuery searchQuery2 = Session.CreateSearchQuery();

            searchQuery2.CombineResults = ConditionGroupOperation.And;

            CardTypeQuery typeQuery2    = searchQuery2.AttributiveSearch.CardTypeQueries.AddNew(CardOrd.ID);
            SectionQuery  sectionQuery4 = typeQuery2.SectionQueries.AddNew(CardOrd.MainInfo.ID);

            sectionQuery4.Operation = SectionQueryOperation.And;
            sectionQuery4.ConditionGroup.Operation = ConditionGroupOperation.And;
            sectionQuery4.ConditionGroup.Conditions.AddNew("Type", FieldType.RefId, ConditionOperation.Equals, DevicePassportTypeID);

            sectionQuery4           = typeQuery2.SectionQueries.AddNew(CardOrd.Properties.ID);
            sectionQuery4.Operation = SectionQueryOperation.And;
            sectionQuery4.ConditionGroup.Operation = ConditionGroupOperation.And;
            sectionQuery4.ConditionGroup.Conditions.AddNew("Name", FieldType.String, ConditionOperation.Equals, "Прибор");
            sectionQuery4.ConditionGroup.Conditions.AddNew("Value", FieldType.RefId, ConditionOperation.Equals, DeviceType.Id);

            if (ImprovPartiesGuid.Count != 0)
            {
                sectionQuery4           = typeQuery2.SectionQueries.AddNew(CardOrd.Properties.ID);
                sectionQuery4.Operation = SectionQueryOperation.And;
                sectionQuery4.ConditionGroup.Operation = ConditionGroupOperation.And;
                sectionQuery4.ConditionGroup.Conditions.AddNew("Name", FieldType.String, ConditionOperation.Equals, "№ партии");
                ConditionGroup PartyGroup = sectionQuery4.ConditionGroup.ConditionGroups.AddNew();
                PartyGroup.Operation = ConditionGroupOperation.Or;
                for (int j = 0; j < ImprovPartiesGuid.Count; j++)
                {
                    PartyGroup.Conditions.AddNew("Value", FieldType.RefId, ConditionOperation.OneOf, ImprovPartiesGuid.ToArray()[j]);
                }
            }
            else
            {
                sectionQuery4           = typeQuery2.SectionQueries.AddNew(CardOrd.Properties.ID);
                sectionQuery4.Operation = SectionQueryOperation.And;
                sectionQuery4.ConditionGroup.Operation = ConditionGroupOperation.And;
                sectionQuery4.ConditionGroup.Conditions.AddNew("Name", FieldType.String, ConditionOperation.Equals, "Состояние прибора");
                sectionQuery4.ConditionGroup.Conditions.AddNew("Value", FieldType.RefId, ConditionOperation.OneOf, new int[] { 5, 6 });
            }
            // Получение текста запроса
            searchQuery2.Limit = 0;
            string query2 = searchQuery2.GetXml();

            Console.WriteLine(query2);
            Console.ReadLine();
            CardDataCollection coll = Session.CardManager.FindCards(query2);

            Clear();

            StatusStrip.Items["StatusText"].Text = "Найдено паспортов: " + coll.Count.ToString() + "...";
            StatusStrip.Update();

            int i = 0;

            for (i = 0; i < coll.Count; i++)
            {
                CardData Card = coll[i];
                Card.ForceUnlock();
                StatusStrip.Items["StatusText"].Text = i.ToString() + " из " + coll.Count + ". " + Card.Description;
                StatusStrip.Update();

                SectionData       Properties  = Card.Sections[CardOrd.Properties.ID];
                RowDataCollection DocumentCol = Properties.FindRow("@Name = 'Документ'").ChildSections[CardOrd.SelectedValues.ID].Rows;
                RowDataCollection Assembly    = Properties.FindRow("@Name = 'Сборочный узел'").ChildSections[CardOrd.SelectedValues.ID].Rows;
                RowDataCollection RepareItem  = Properties.FindRow("@Name = 'Запись справочника ремонтных работ и доработок'").ChildSections[CardOrd.SelectedValues.ID].Rows;
                RowDataCollection Indication  = Properties.FindRow("@Name = 'Указание'").ChildSections[CardOrd.SelectedValues.ID].Rows;
                RowDataCollection Check       = Properties.FindRow("@Name = 'Выполнено'").ChildSections[CardOrd.SelectedValues.ID].Rows;
                RowDataCollection CheckDate   = Properties.FindRow("@Name = 'Дата выполнения'").ChildSections[CardOrd.SelectedValues.ID].Rows;
                RowDataCollection Comments    = Properties.FindRow("@Name = 'Комментарии'").ChildSections[CardOrd.SelectedValues.ID].Rows;

                if (DocumentCol.Count != Assembly.Count)
                {
                    foreach (RowData Doc in DocumentCol)
                    {
                        int Order = (int)Doc.GetInt32("Order");
                        if (Assembly.FirstOrDefault(r => r.GetInt32("Order") == Order).IsNull())
                        {
                            RowData NewRow = Assembly.AddNew();
                            NewRow.SetInt32("Order", Order);
                        }
                    }
                }

                if (DocumentCol.Count != RepareItem.Count)
                {
                    foreach (RowData Doc in DocumentCol)
                    {
                        int Order = (int)Doc.GetInt32("Order");
                        if (RepareItem.FirstOrDefault(r => r.GetInt32("Order") == Order).IsNull())
                        {
                            RowData NewRow = RepareItem.AddNew();
                            NewRow.SetInt32("Order", Order);
                        }
                    }
                }

                if (DocumentCol.Count != Indication.Count)
                {
                    foreach (RowData Doc in DocumentCol)
                    {
                        int Order = (int)Doc.GetInt32("Order");
                        if (Indication.FirstOrDefault(r => r.GetInt32("Order") == Order).IsNull())
                        {
                            RowData NewRow = Indication.AddNew();
                            NewRow.SetInt32("Order", Order);
                        }
                    }
                }

                if (DocumentCol.Count != Check.Count)
                {
                    foreach (RowData Doc in DocumentCol)
                    {
                        int Order = (int)Doc.GetInt32("Order");
                        if (Check.FirstOrDefault(r => r.GetInt32("Order") == Order).IsNull())
                        {
                            RowData NewRow = Check.AddNew();
                            NewRow.SetInt32("Order", Order);
                        }
                    }
                }

                if (DocumentCol.Count != CheckDate.Count)
                {
                    foreach (RowData Doc in DocumentCol)
                    {
                        int Order = (int)Doc.GetInt32("Order");
                        if (CheckDate.FirstOrDefault(r => r.GetInt32("Order") == Order).IsNull())
                        {
                            RowData NewRow = CheckDate.AddNew();
                            NewRow.SetInt32("Order", Order);
                        }
                    }
                }

                if (DocumentCol.Count != Comments.Count)
                {
                    foreach (RowData Doc in DocumentCol)
                    {
                        int Order = (int)Doc.GetInt32("Order");
                        if (Comments.FirstOrDefault(r => r.GetInt32("Order") == Order).IsNull())
                        {
                            RowData NewRow = Comments.AddNew();
                            NewRow.SetInt32("Order", Order);
                        }
                    }
                }

                if (!DocumentCol.Any(r => r.GetGuid("SelectedValue") == Document.Id))
                {
                    int     CurrentOrder = DocumentCol.Count + 1;
                    RowData NewRow2      = DocumentCol.AddNew();
                    NewRow2.SetInt32("Order", CurrentOrder);
                    NewRow2.SetGuid("SelectedValue", Document.Id);

                    NewRow2 = RepareItem.AddNew();
                    NewRow2.SetInt32("Order", CurrentOrder);
                    NewRow2.SetGuid("SelectedValue", ItemRow.Id);

                    NewRow2 = Assembly.AddNew();
                    NewRow2.SetInt32("Order", CurrentOrder);
                    if (!ItemCard.Sections[new Guid("{3F9F3C1D-1CF1-4E71-BBE4-31D6AAD94EF7}")].FirstRow.GetGuid("AssemblyUnit").IsNull())
                    {
                        NewRow2.SetGuid("SelectedValue", (Guid)ItemCard.Sections[new Guid("{3F9F3C1D-1CF1-4E71-BBE4-31D6AAD94EF7}")].FirstRow.GetGuid("AssemblyUnit"));
                    }

                    NewRow2 = Indication.AddNew();
                    NewRow2.SetInt32("Order", CurrentOrder);
                    if (!ItemCard.Sections[new Guid("{3F9F3C1D-1CF1-4E71-BBE4-31D6AAD94EF7}")].FirstRow.GetGuid("Instructions").IsNull())
                    {
                        NewRow2.SetGuid("SelectedValue", (Guid)ItemCard.Sections[new Guid("{3F9F3C1D-1CF1-4E71-BBE4-31D6AAD94EF7}")].FirstRow.GetGuid("Instructions"));
                    }

                    NewRow2 = Check.AddNew();
                    NewRow2.SetInt32("Order", CurrentOrder);

                    NewRow2 = CheckDate.AddNew();
                    NewRow2.SetInt32("Order", CurrentOrder);

                    NewRow2 = Comments.AddNew();
                    NewRow2.SetInt32("Order", CurrentOrder);
                }
                Clear();
            }

            StatusStrip.Items["StatusText"].Text = i.ToString() + " карточек успешно обработано.";
            StatusStrip.Update();
        }