Example #1
0
        /// <summary>
        /// Сохранение сущности в RX.
        /// </summary>
        /// <param name="shift">Сдвиг по горизонтали в XLSX документе. Необходим для обработки документов, составленных из элементов разных сущностей.</param>
        /// <param name="logger">Логировщик.</param>
        /// <returns>Число запрашиваемых параметров.</returns>
        public override IEnumerable <Structures.ExceptionsStruct> SaveToRX(NLog.Logger logger, bool supplementEntity, int shift = 0)
        {
            var exceptionList = new List <Structures.ExceptionsStruct>();

            using (var session = new Session())
            {
                var      regNumber     = this.Parameters[shift + 0];
                DateTime?regDate       = DateTime.MinValue;
                var      style         = NumberStyles.Number | NumberStyles.AllowCurrencySymbol;
                var      culture       = CultureInfo.CreateSpecificCulture("en-GB");
                var      regDateDouble = 0.0;
                if (!string.IsNullOrWhiteSpace(this.Parameters[shift + 1]) && !double.TryParse(this.Parameters[shift + 1].Trim(), style, culture, out regDateDouble))
                {
                    var message = string.Format("Не удалось обработать дату регистрации \"{0}\".", this.Parameters[shift + 1]);
                    exceptionList.Add(new Structures.ExceptionsStruct {
                        ErrorType = Constants.ErrorTypes.Error, Message = message
                    });
                    logger.Error(message);
                    return(exceptionList);
                }
                else
                {
                    if (!string.IsNullOrEmpty(this.Parameters[shift + 1].ToString()))
                    {
                        regDate = DateTime.FromOADate(regDateDouble);
                    }
                }

                var counterparty = BusinessLogic.GetConterparty(session, this.Parameters[shift + 2], exceptionList, logger);
                if (counterparty == null)
                {
                    var message = string.Format("Не найден контрагент \"{0}\".", this.Parameters[shift + 2]);
                    exceptionList.Add(new Structures.ExceptionsStruct {
                        ErrorType = Constants.ErrorTypes.Error, Message = message
                    });
                    logger.Error(message);
                    return(exceptionList);
                }

                var documentKind = BusinessLogic.GetDocumentKind(session, this.Parameters[shift + 3], exceptionList, logger);
                if (documentKind == null)
                {
                    var message = string.Format("Не найден вид документа \"{0}\".", this.Parameters[shift + 3]);
                    exceptionList.Add(new Structures.ExceptionsStruct {
                        ErrorType = Constants.ErrorTypes.Error, Message = message
                    });
                    logger.Error(message);
                    return(exceptionList);
                }

                var contractCategory = BusinessLogic.GetContractCategory(session, this.Parameters[shift + 4], exceptionList, logger);
                if (!string.IsNullOrEmpty(this.Parameters[shift + 4].ToString()))
                {
                    if (contractCategory == null)
                    {
                        var message = string.Format("Не найдена категория договора \"{0}\".", this.Parameters[shift + 4]);
                        exceptionList.Add(new Structures.ExceptionsStruct {
                            ErrorType = Constants.ErrorTypes.Error, Message = message
                        });
                        logger.Error(message);
                        return(exceptionList);
                    }
                }

                var subject = this.Parameters[shift + 5];

                var businessUnit = BusinessLogic.GetBusinessUnit(session, this.Parameters[shift + 6], exceptionList, logger);
                if (businessUnit == null)
                {
                    var message = string.Format("Не найдено подразделение \"{0}\".", this.Parameters[shift + 6]);
                    exceptionList.Add(new Structures.ExceptionsStruct {
                        ErrorType = Constants.ErrorTypes.Error, Message = message
                    });
                    logger.Error(message);
                    return(exceptionList);
                }

                var department = BusinessLogic.GetDepartment(session, this.Parameters[shift + 7], exceptionList, logger);
                if (department == null)
                {
                    var message = string.Format("Не найдено подразделение \"{0}\".", this.Parameters[shift + 7]);
                    exceptionList.Add(new Structures.ExceptionsStruct {
                        ErrorType = Constants.ErrorTypes.Error, Message = message
                    });
                    logger.Error(message);
                    return(exceptionList);
                }

                var filePath = this.Parameters[shift + 8];

                DateTime?validFrom       = DateTime.MinValue;
                var      validFromDouble = 0.0;
                if (!string.IsNullOrWhiteSpace(this.Parameters[shift + 9]) && !double.TryParse(this.Parameters[shift + 9].Trim(), style, culture, out validFromDouble))
                {
                    var message = string.Format("Не удалось обработать значение в поле \"Действует с\" \"{0}\".", this.Parameters[shift + 9]);
                    exceptionList.Add(new Structures.ExceptionsStruct {
                        ErrorType = Constants.ErrorTypes.Error, Message = message
                    });
                    logger.Error(message);
                    return(exceptionList);
                }
                else
                {
                    if (!string.IsNullOrEmpty(this.Parameters[shift + 9].ToString()))
                    {
                        validFrom = DateTime.FromOADate(validFromDouble);
                    }
                }

                DateTime?validTill       = DateTime.MinValue;
                var      validTillDouble = 0.0;
                if (!string.IsNullOrWhiteSpace(this.Parameters[shift + 10]) && !double.TryParse(this.Parameters[shift + 10].Trim(), style, culture, out validTillDouble))
                {
                    var message = string.Format("Не удалось обработать значение в поле \"Действует по\" \"{0}\".", this.Parameters[shift + 10]);
                    exceptionList.Add(new Structures.ExceptionsStruct {
                        ErrorType = Constants.ErrorTypes.Error, Message = message
                    });
                    logger.Error(message);
                    return(exceptionList);
                }
                else
                {
                    if (!string.IsNullOrEmpty(this.Parameters[shift + 10].ToString()))
                    {
                        validTill = DateTime.FromOADate(validTillDouble);
                    }
                }

                var totalAmount = 0.0;
                if (!string.IsNullOrWhiteSpace(this.Parameters[shift + 11]) && !double.TryParse(this.Parameters[shift + 11].Trim(), style, culture, out totalAmount))
                {
                    var message = string.Format("Не удалось обработать значение в поле \"Сумма\" \"{0}\".", this.Parameters[shift + 11]);
                    exceptionList.Add(new Structures.ExceptionsStruct {
                        ErrorType = Constants.ErrorTypes.Error, Message = message
                    });
                    logger.Error(message);
                    return(exceptionList);
                }

                var currency = BusinessLogic.GetCurrency(session, this.Parameters[shift + 12], exceptionList, logger);
                if (!string.IsNullOrEmpty(this.Parameters[shift + 12].Trim()) && currency == null)
                {
                    var message = string.Format("Не найдено соответствующее наименование валюты \"{0}\".", this.Parameters[shift + 12]);
                    exceptionList.Add(new Structures.ExceptionsStruct {
                        ErrorType = Constants.ErrorTypes.Error, Message = message
                    });
                    logger.Error(message);
                    return(exceptionList);
                }
                var lifeCycleState = BusinessLogic.GetPropertyLifeCycleState(session, this.Parameters[shift + 13]);
                if (!string.IsNullOrEmpty(this.Parameters[shift + 13].Trim()) && lifeCycleState == null)
                {
                    var message = string.Format("Не найдено соответствующее значение состояния \"{0}\".", this.Parameters[shift + 13]);
                    exceptionList.Add(new Structures.ExceptionsStruct {
                        ErrorType = Constants.ErrorTypes.Error, Message = message
                    });
                    logger.Error(message);
                    return(exceptionList);
                }
                var responsibleEmployee = BusinessLogic.GetEmployee(session, this.Parameters[shift + 14].Trim(), exceptionList, logger);
                if (!string.IsNullOrEmpty(this.Parameters[shift + 14].Trim()) && responsibleEmployee == null)
                {
                    var message = string.Format("Не найден Ответственный \"{3}\". Договор: \"{0} {1} {2}\". ", regNumber, regDate.ToString(), counterparty, this.Parameters[shift + 14].Trim());
                    exceptionList.Add(new Structures.ExceptionsStruct {
                        ErrorType = Constants.ErrorTypes.Warn, Message = message
                    });
                    logger.Warn(message);
                }
                var ourSignatory = BusinessLogic.GetEmployee(session, this.Parameters[shift + 15].Trim(), exceptionList, logger);
                if (!string.IsNullOrEmpty(this.Parameters[shift + 15].Trim()) && ourSignatory == null)
                {
                    var message = string.Format("Не найден Подписывающий \"{3}\". Договор: \"{0} {1} {2}\". ", regNumber, regDate.ToString(), counterparty, this.Parameters[shift + 15].Trim());
                    exceptionList.Add(new Structures.ExceptionsStruct {
                        ErrorType = Constants.ErrorTypes.Warn, Message = message
                    });
                    logger.Warn(message);
                }
                var note = this.Parameters[shift + 16];
                try
                {
                    var contracts = Enumerable.ToList(session.GetAll <Sungero.Contracts.IContract>().Where(x => Equals(x.RegistrationNumber, regNumber) &&
                                                                                                           Equals(x.RegistrationDate, regDate) &&
                                                                                                           Equals(x.Counterparty, counterparty)));
                    var contract = (Enumerable.FirstOrDefault <Sungero.Contracts.IContract>(contracts));
                    if (contract != null)
                    {
                        var message = string.Format("Договор не может быть импортирован. Найден дубль с такими же реквизитами \"Рег. №\" {0}, \"Дата документа\" {1}, \"Контрагент\" {2}.", regNumber, regDate.ToString(), counterparty.ToString());
                        exceptionList.Add(new Structures.ExceptionsStruct {
                            ErrorType = Constants.ErrorTypes.Error, Message = message
                        });
                        logger.Error(message);
                        return(exceptionList);
                    }
                    contract = session.Create <Sungero.Contracts.IContract>();
                    contract.Counterparty  = counterparty;
                    contract.DocumentKind  = documentKind;
                    contract.DocumentGroup = contractCategory;
                    contract.Subject       = subject;
                    contract.BusinessUnit  = businessUnit;
                    contract.Department    = department;
                    if (validFrom != DateTime.MinValue)
                    {
                        contract.ValidFrom = validFrom;
                    }
                    if (validTill != DateTime.MinValue)
                    {
                        contract.ValidTill = validTill;
                    }
                    contract.TotalAmount         = totalAmount;
                    contract.Currency            = currency;
                    contract.LifeCycleState      = lifeCycleState;
                    contract.ResponsibleEmployee = responsibleEmployee;
                    contract.OurSignatory        = ourSignatory;
                    contract.Note = note;
                    if (regDate != DateTime.MinValue)
                    {
                        contract.RegistrationDate = regDate;
                    }
                    contract.RegistrationNumber = regNumber;
                    contract.Save();
                    if (!string.IsNullOrWhiteSpace(filePath))
                    {
                        exceptionList.Add(BusinessLogic.ImportBody(session, contract, filePath, logger));
                    }
                    var documentRegisterId = 0;
                    if (ExtraParameters.ContainsKey("doc_register_id"))
                    {
                        if (int.TryParse(ExtraParameters["doc_register_id"], out documentRegisterId))
                        {
                            exceptionList.AddRange(BusinessLogic.RegisterDocument(session, contract, documentRegisterId, regNumber, regDate, Constants.RolesGuides.RoleContractResponsible, logger));
                        }
                        else
                        {
                            var message = string.Format("Не удалось обработать параметр \"doc_register_id\". Полученное значение: {0}.", ExtraParameters["doc_register_id"]);
                            exceptionList.Add(new Structures.ExceptionsStruct {
                                ErrorType = Constants.ErrorTypes.Error, Message = message
                            });
                            logger.Error(message);
                            return(exceptionList);
                        }
                    }
                }
                catch (Exception ex)
                {
                    exceptionList.Add(new Structures.ExceptionsStruct {
                        ErrorType = Constants.ErrorTypes.Error, Message = ex.Message
                    });
                    return(exceptionList);
                }
                session.SubmitChanges();
            }
            return(exceptionList);
        }
Example #2
0
        /// <summary>
        /// Сохранение сущности в RX.
        /// </summary>
        /// <param name="shift">Сдвиг по горизонтали в XLSX документе. Необходим для обработки документов, составленных из элементов разных сущностей.</param>
        /// <param name="logger">Логировщик.</param>
        /// <returns>Число запрашиваемых параметров.</returns>
        public override IEnumerable <Structures.ExceptionsStruct> SaveToRX(NLog.Logger logger, int shift = 0)
        {
            var exceptionList = new List <Structures.ExceptionsStruct>();

            using (var session = new Session())
            {
                var lastName = this.Parameters[shift + 0].Trim();
                if (string.IsNullOrEmpty(lastName))
                {
                    var message = string.Format("Не заполнено поле \"Фамилия\".");
                    exceptionList.Add(new Structures.ExceptionsStruct {
                        ErrorType = "Error", Message = message
                    });
                    logger.Error(message);
                    return(exceptionList);
                }
                var firstName = this.Parameters[shift + 1].Trim();
                if (string.IsNullOrEmpty(firstName))
                {
                    var message = string.Format("Не заполнено поле \"Имя\".");
                    exceptionList.Add(new Structures.ExceptionsStruct {
                        ErrorType = "Error", Message = message
                    });
                    logger.Error(message);
                    return(exceptionList);
                }
                var middleName        = this.Parameters[shift + 2].Trim();
                var sex               = BusinessLogic.GetPropertySex(session, this.Parameters[shift + 3].Trim());
                var dateOfBirth       = DateTime.MinValue;
                var style             = NumberStyles.Number | NumberStyles.AllowCurrencySymbol;
                var culture           = CultureInfo.CreateSpecificCulture("en-GB");
                var dateOfBirthDouble = 0.0;
                if (!string.IsNullOrWhiteSpace(this.Parameters[shift + 4]))
                {
                    if (double.TryParse(this.Parameters[shift + 4].Trim(), style, culture, out dateOfBirthDouble))
                    {
                        dateOfBirth = DateTime.FromOADate(dateOfBirthDouble);
                    }
                    else
                    {
                        var message = string.Format("Не удалось обработать значение в поле \"Дата рождения\" \"{0}\".", this.Parameters[shift + 4]);
                        exceptionList.Add(new Structures.ExceptionsStruct {
                            ErrorType = Constants.ErrorTypes.Warn, Message = message
                        });
                        logger.Warn(message);
                    }
                }
                var tin          = this.Parameters[shift + 5].Trim();
                var inila        = this.Parameters[shift + 6].Trim();
                var city         = BusinessLogic.GetCity(session, this.Parameters[shift + 7].Trim(), exceptionList, logger);
                var region       = BusinessLogic.GetRegion(session, this.Parameters[shift + 8].Trim(), exceptionList, logger);
                var legalAdress  = this.Parameters[shift + 9].Trim();
                var postalAdress = this.Parameters[shift + 10].Trim();
                var phones       = this.Parameters[shift + 11].Trim();
                var email        = this.Parameters[shift + 12].Trim();
                var homepage     = this.Parameters[shift + 13].Trim();
                var bank         = BusinessLogic.GetBank(session, this.Parameters[shift + 14], exceptionList, logger);
                if (!string.IsNullOrEmpty(this.Parameters[shift + 14]))
                {
                    if (bank == null)
                    {
                        var message = $"Не найден банк \"{this.Parameters[shift + 14]}\".";
                        exceptionList.Add(new Structures.ExceptionsStruct {
                            ErrorType = Constants.ErrorTypes.Error, Message = message
                        });
                        logger.Error(message);
                        return(exceptionList);
                    }
                }
                var account = this.Parameters[shift + 15].Trim();
                var note    = this.Parameters[shift + 16].Trim();

                try
                {
                    var persons = Enumerable.ToList(session.GetAll <Sungero.Parties.IPerson>().Where(x => x.LastName == lastName && x.FirstName == firstName));
                    var person  = (Enumerable.FirstOrDefault <Sungero.Parties.IPerson>(persons));
                    if (person != null)
                    {
                        var message = string.Format("Персона не может быть импортирована. Найден дубль по реквизитам Фамилия: \"{0}\", Имя: {1}.", lastName, firstName);
                        exceptionList.Add(new Structures.ExceptionsStruct {
                            ErrorType = "Error", Message = message
                        });
                        logger.Error(message);
                        return(exceptionList);
                    }
                    person = session.Create <Sungero.Parties.IPerson>();

                    person.LastName   = lastName;
                    person.FirstName  = firstName;
                    person.MiddleName = middleName;
                    person.Sex        = sex;
                    if (dateOfBirth != DateTime.MinValue)
                    {
                        person.DateOfBirth = dateOfBirth;
                    }
                    person.TIN   = tin;
                    person.INILA = inila;
                    if (city != null)
                    {
                        person.City = city;
                    }
                    if (region != null)
                    {
                        person.Region = region;
                    }
                    person.LegalAddress  = legalAdress;
                    person.PostalAddress = postalAdress;
                    person.Phones        = phones;
                    person.Email         = email;
                    person.Homepage      = homepage;
                    person.Bank          = bank;
                    person.Account       = account;
                    person.Note          = note;
                    person.Save();
                }
                catch (Exception ex)
                {
                    exceptionList.Add(new Structures.ExceptionsStruct {
                        ErrorType = "Error", Message = ex.Message
                    });
                    return(exceptionList);
                }
                session.SubmitChanges();
            }
            return(exceptionList);
        }
        /// <summary>
        /// Сохранение сущности в RX.
        /// </summary>
        /// <param name="shift">Сдвиг по горизонтали в XLSX документе. Необходим для обработки документов, составленных из элементов разных сущностей.</param>
        /// <param name="logger">Логировщик.</param>
        /// <returns>Число запрашиваемых параметров.</returns>
        public override IEnumerable <Structures.ExceptionsStruct> SaveToRX(NLog.Logger logger, int shift = 0)
        {
            var exceptionList = new List <Structures.ExceptionsStruct>();

            using (var session = new Session())
            {
                var name = this.Parameters[shift + 0].Trim();
                if (string.IsNullOrEmpty(name))
                {
                    var message = string.Format("Не заполнено поле \"Наименование\".");
                    exceptionList.Add(new Structures.ExceptionsStruct {
                        ErrorType = "Error", Message = message
                    });
                    logger.Error(message);
                    return(exceptionList);
                }
                var legalName    = this.Parameters[shift + 1].Trim();
                var headCompany  = BusinessLogic.GetBusinessUnit(session, this.Parameters[shift + 2].Trim(), exceptionList, logger);
                var ceo          = BusinessLogic.GetEmployee(session, this.Parameters[shift + 3].Trim(), exceptionList, logger);
                var tin          = this.Parameters[shift + 4].Trim();
                var trrc         = this.Parameters[shift + 5].Trim();
                var psrn         = this.Parameters[shift + 6].Trim();
                var nceo         = this.Parameters[shift + 7].Trim();
                var ncea         = this.Parameters[shift + 8].Trim();
                var city         = BusinessLogic.GetCity(session, this.Parameters[shift + 9].Trim(), exceptionList, logger);
                var region       = BusinessLogic.GetRegion(session, this.Parameters[shift + 10].Trim(), exceptionList, logger);
                var legalAdress  = this.Parameters[shift + 11].Trim();
                var postalAdress = this.Parameters[shift + 12].Trim();
                var phones       = this.Parameters[shift + 13].Trim();
                var email        = this.Parameters[shift + 14].Trim();
                var homepage     = this.Parameters[shift + 15].Trim();
                var note         = this.Parameters[shift + 16].Trim();
                var account      = this.Parameters[shift + 17].Trim();
                var bank         = BusinessLogic.GetBank(session, this.Parameters[shift + 18].Trim(), exceptionList, logger);
                if (!string.IsNullOrEmpty(this.Parameters[shift + 18]))
                {
                    if (bank == null)
                    {
                        var message = $"Не найден банк \"{this.Parameters[shift + 18]}\".";
                        exceptionList.Add(new Structures.ExceptionsStruct {
                            ErrorType = Constants.ErrorTypes.Error, Message = message
                        });
                        logger.Error(message);
                        return(exceptionList);
                    }
                }

                try
                {
                    var businessUnits = Enumerable.ToList(session.GetAll <Sungero.Company.IBusinessUnit>().Where(x => x.Name == name ||
                                                                                                                 !string.IsNullOrEmpty(tin) && x.TIN == tin ||
                                                                                                                 !string.IsNullOrEmpty(psrn) && x.PSRN == psrn));
                    var businessUnit = (Enumerable.FirstOrDefault <Sungero.Company.IBusinessUnit>(businessUnits));
                    if (businessUnit != null)
                    {
                        var message = string.Format("НОР не может быть импортирована. Найден дубль по реквизитам Наименование: \"{0}\", ИНН: {1}, ОГРН: {2}.", name, tin, psrn);
                        exceptionList.Add(new Structures.ExceptionsStruct {
                            ErrorType = Constants.ErrorTypes.Error, Message = message
                        });
                        logger.Error(message);
                        return(exceptionList);
                    }
                    businessUnit               = session.Create <Sungero.Company.IBusinessUnit>();
                    businessUnit.Name          = name;
                    businessUnit.LegalName     = legalName;
                    businessUnit.HeadCompany   = headCompany;
                    businessUnit.CEO           = ceo;
                    businessUnit.TIN           = tin;
                    businessUnit.TRRC          = trrc;
                    businessUnit.PSRN          = psrn;
                    businessUnit.NCEO          = nceo;
                    businessUnit.NCEA          = ncea;
                    businessUnit.City          = city;
                    businessUnit.Region        = region;
                    businessUnit.LegalAddress  = legalAdress;
                    businessUnit.PostalAddress = postalAdress;
                    businessUnit.Phones        = phones;
                    businessUnit.Email         = email;
                    businessUnit.Homepage      = homepage;
                    businessUnit.Note          = note;
                    businessUnit.Account       = account;
                    businessUnit.Bank          = bank;
                    businessUnit.Save();
                }
                catch (Exception ex)
                {
                    exceptionList.Add(new Structures.ExceptionsStruct {
                        ErrorType = Constants.ErrorTypes.Error, Message = ex.Message
                    });
                    return(exceptionList);
                }
                session.SubmitChanges();
            }
            return(exceptionList);
        }
Example #4
0
        /// <summary>
        /// Сохранение сущности в RX.
        /// </summary>
        /// <param name="shift">Сдвиг по горизонтали в XLSX документе. Необходим для обработки документов, составленных из элементов разных сущностей.</param>
        /// <param name="logger">Логировщик.</param>
        /// <returns>Число запрашиваемых параметров.</returns>
        public override IEnumerable <Structures.ExceptionsStruct> SaveToRX(NLog.Logger logger, int shift = 0)
        {
            var exceptionList = new List <Structures.ExceptionsStruct>();

            using (var session = new Session())
            {
                var name = this.Parameters[shift + 0].Trim();
                if (string.IsNullOrEmpty(name))
                {
                    var message = string.Format("Не заполнено поле \"Наименование\".");
                    exceptionList.Add(new Structures.ExceptionsStruct {
                        ErrorType = "Error", Message = message
                    });
                    logger.Error(message);
                    return(exceptionList);
                }
                var legalName    = this.Parameters[shift + 1].Trim();
                var headCompany  = BusinessLogic.GetConterparty(session, this.Parameters[shift + 2].Trim(), exceptionList, logger);
                var nonresident  = this.Parameters[shift + 3] == "Да" ? true : false;
                var tin          = this.Parameters[shift + 4].Trim();
                var trrc         = this.Parameters[shift + 5].Trim();
                var psrn         = this.Parameters[shift + 6].Trim();
                var nceo         = this.Parameters[shift + 7].Trim();
                var ncea         = this.Parameters[shift + 8].Trim();
                var city         = BusinessLogic.GetCity(session, this.Parameters[shift + 9].Trim(), exceptionList, logger);
                var region       = BusinessLogic.GetRegion(session, this.Parameters[shift + 10].Trim(), exceptionList, logger);
                var legalAdress  = this.Parameters[shift + 11].Trim();
                var postalAdress = this.Parameters[shift + 12].Trim();
                var phones       = this.Parameters[shift + 13].Trim();
                var email        = this.Parameters[shift + 14].Trim();
                var homepage     = this.Parameters[shift + 15].Trim();
                var note         = this.Parameters[shift + 16].Trim();
                var account      = this.Parameters[shift + 17].Trim();
                var bank         = BusinessLogic.GetBank(session, this.Parameters[shift + 18].Trim(), exceptionList, logger);
                if (!string.IsNullOrEmpty(this.Parameters[shift + 18]))
                {
                    if (bank == null)
                    {
                        var message = $"Не найден банк \"{this.Parameters[shift + 18]}\".";
                        exceptionList.Add(new Structures.ExceptionsStruct {
                            ErrorType = Constants.ErrorTypes.Error, Message = message
                        });
                        logger.Error(message);
                        return(exceptionList);
                    }
                }
                try
                {
                    string regex = @"^([0-9]{10}|[0-9]{12})$";
                    if (!string.IsNullOrEmpty(tin))
                    {
                        if (!Regex.IsMatch(tin, regex))
                        {
                            var message = string.Format("Компания не может быть импортирована. Некорректный ИНН. Наименование: \"{0}\", ИНН: {1}. ", name, tin);
                            exceptionList.Add(new Structures.ExceptionsStruct {
                                ErrorType = Constants.ErrorTypes.Error, Message = message
                            });
                            logger.Error(message);
                            return(exceptionList);
                        }
                    }

                    var companies = Enumerable.ToList(session.GetAll <Sungero.Parties.ICompany>().Where(x => x.Name == name ||
                                                                                                        (!string.IsNullOrEmpty(tin) && x.TIN == tin && !string.IsNullOrEmpty(trrc) && x.TRRC == trrc) ||
                                                                                                        !string.IsNullOrEmpty(psrn) && x.PSRN == psrn));
                    var company = (Enumerable.FirstOrDefault <Sungero.Parties.ICompany>(companies));

                    if (company != null)
                    {
                        var message = string.Format("Компания не может быть импортирована. Найден дубль по реквизитам Наименование: \"{0}\", ИНН: {1} + КПП {2}, ОГРН: {3}.", name, tin, trrc, psrn);
                        exceptionList.Add(new Structures.ExceptionsStruct {
                            ErrorType = Constants.ErrorTypes.Error, Message = message
                        });
                        logger.Error(message);
                        return(exceptionList);
                    }
                    company               = session.Create <Sungero.Parties.ICompany>();
                    company.Name          = name;
                    company.LegalName     = legalName;
                    company.HeadCompany   = headCompany;
                    company.Nonresident   = nonresident;
                    company.TIN           = tin;
                    company.TRRC          = trrc;
                    company.PSRN          = psrn;
                    company.NCEO          = nceo;
                    company.NCEA          = ncea;
                    company.City          = city;
                    company.Region        = region;
                    company.LegalAddress  = legalAdress;
                    company.PostalAddress = postalAdress;
                    company.Phones        = phones;
                    company.Email         = email;
                    company.Homepage      = homepage;
                    company.Note          = note;
                    company.Account       = account;
                    company.Bank          = bank;
                    company.Save();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    exceptionList.Add(new Structures.ExceptionsStruct {
                        ErrorType = Constants.ErrorTypes.Error, Message = ex.Message
                    });
                    return(exceptionList);
                }
                session.SubmitChanges();
            }
            return(exceptionList);
        }