Example #1
0
        private Document Parse(string file)
        {
            file = @"..\..\Data\Waybills\" + file;
            var detector = new WaybillFormatDetector();
            var parser   = detector.DetectParser(file, new DocumentReceiveLog {
                Supplier = new Supplier {
                    Id = 105
                }
            });
            var doc = new Document();

            return(parser.Parse(file, doc));
        }
        protected void Load(ProtekServiceConfig config)
        {
            WithService(config.Url, service => {
                _logger.InfoFormat("Запрос накладных, clientId = {0} instanceId = {1}", config.ClientId, config.InstanceId);
                var responce  = service.getBladingHeaders(new getBladingHeaders(config.ClientId, config.InstanceId));
                var sessionId = [email protected];

                try {
                    if ([email protected] == null)
                    {
                        return;
                    }

                    _logger.InfoFormat("Получили накладные, всего {0} для сессии {1}", [email protected], sessionId);
                    foreach (var blading in [email protected])
                    {
                        var blanding = service.getBladingBody(new getBladingBody(sessionId, config.ClientId, config.InstanceId, blading.bladingId.Value));
                        _logger.InfoFormat("Загрузил накладную {0}({1})", blading.bladingId, blading.baseId);
                        foreach (var body in [email protected])
                        {
                            using (var scope = new TransactionScope(OnDispose.Rollback)) {
                                var document = ToDocument(body, config);
                                if (document == null)
                                {
                                    continue;
                                }

                                WaybillFormatDetector.Process(document, orders);
                                document.Log.Save();
                                document.Save();
                                try {
                                    document.CreateCertificateTasks();
                                }
                                catch (Exception e) {
                                    _logger.Error(String.Format("Не удалось создать задачи для загрузки сертификатов по накладной {0}", document.Log.Id), e);
                                }

                                Exporter.SaveProtek(document);
                                scope.VoteCommit();
                            }
                            _logger.InfoFormat("Разобрана накладная {0} для заказа {1}", body.baseId, body.@uint);
                        }
                        Ping();
                    }
                }
                finally {
                    service.closeBladingSession(new closeBladingSession(sessionId, config.ClientId, config.InstanceId));
                    Ping();                     // чтобы монитор не перезапустил рабочий поток
                }
            });
        }
Example #3
0
        public void Parse()
        {
            var document = WaybillParser.Parse("55865(2).DBF");

            Assert.That(document.Parser, Is.EqualTo("TekoSParser"));
            Assert.That(document.ProviderDocumentId, Is.EqualTo("ЦБ01-055865"));
            Assert.That(document.DocumentDate, Is.EqualTo(new DateTime(2015, 07, 07)));

            //проверяем что для разбора данного формата файла подходит только один парсер
            var detector = new WaybillFormatDetector();
            var parsers  = detector.GetSuitableParsers(@"..\..\Data\Waybills\r_03-068.DBF", null).ToList();

            Assert.That(parsers.ToList().Count, Is.EqualTo(1));

            var line0 = document.Lines[0];

            Assert.That(line0.Product, Is.EqualTo("Медицинский антисепт-кий р-р фл. 95% 100мл"));
            Assert.That(line0.Producer, Is.EqualTo("БиоФармКомбинат/Россия"));
            Assert.That(line0.SerialNumber, Is.EqualTo("070514"));
            Assert.That(line0.Period, Is.EqualTo("01.05.2019"));
            Assert.That(line0.Certificates, Is.EqualTo("POCC RU.ФМ08.Д07626"));
            Assert.That(line0.ProducerCostWithoutNDS, Is.EqualTo(22.43));
            Assert.That(line0.SupplierCostWithoutNDS, Is.EqualTo(13.12));
            Assert.That(line0.Nds, Is.EqualTo(10));
            Assert.That(line0.SupplierCost, Is.EqualTo(14.43));
            Assert.That(line0.Quantity, Is.EqualTo(40));
            Assert.That(line0.CodeCr, Is.EqualTo("24894"));
            Assert.That(line0.VitallyImportant, Is.True);
            Assert.That(line0.NdsAmount, Is.EqualTo(52.47));
            Assert.That(line0.Amount, Is.EqualTo(577.20));
            Assert.That(line0.Unit, Is.EqualTo("уп"));
            Assert.That(line0.BillOfEntryNumber, Is.Null);
            Assert.That(line0.EAN13, Is.EqualTo(4680006520908));
            var invoice = document.Invoice;

            Assert.That(invoice.InvoiceNumber, Is.EqualTo("55865"));
            Assert.That(invoice.InvoiceDate, Is.EqualTo(new DateTime(2015, 07, 07)));
            Assert.That(invoice.SellerAddress, Is.EqualTo("410065,г.Саратов,2-ой Красноармейский тупик,д.3"));
            Assert.That(invoice.SellerINN, Is.EqualTo("6453064469"));
            Assert.That(invoice.SellerKPP, Is.EqualTo("645301001"));
            Assert.That(invoice.RecipientName, Is.EqualTo("Воронеж Поворино Золотой век ООО"));
            //в связи с переполнением - null
            Assert.That(invoice.RecipientId, Is.Null);
            Assert.That(invoice.ShipperInfo, Is.EqualTo("Воронеж Поворино Золотой век ООО,397350, г.Поворино, ул.Московская, д.53 а"));
            Assert.That(invoice.BuyerId, Is.EqualTo(23067));
            Assert.That(invoice.BuyerName, Is.EqualTo("Воронеж Поворино Золотой век ООО"));
            Assert.That(invoice.BuyerAddress, Is.EqualTo("397350, г.Поворино, ул.Советская, д.85"));
            Assert.That(invoice.BuyerINN, Is.EqualTo("3623008451"));
            Assert.That(invoice.BuyerKPP, Is.EqualTo("362301001"));
            Assert.That(line0.CertificatesEndDate, Is.EqualTo(new DateTime(2019, 05, 01)));
        }
Example #4
0
        public void GetSpecialParserTest()
        {
            var documentLog = new DocumentReceiveLog {
                Supplier = new Supplier {
                    Id = 1
                },
            };
            var detector = new WaybillFormatDetectorFake();

            detector.AddSpecParser(documentLog.Supplier.Id, typeof(ParserFake1));

            var type = detector.GetSpecialParser(@"..\..\Data\Waybills\KZ000130.dbf", documentLog);

            Assert.That(type.FullName.Contains("ParserFake1"), Is.True);

            detector = new WaybillFormatDetectorFake();

            detector.AddSpecParser(documentLog.Supplier.Id, typeof(ParserFake2));
            type = detector.GetSpecialParser(@"..\..\Data\Waybills\KZ000130.dbf", documentLog);
            Assert.That(type, Is.Null);

            detector.AddSpecParser(documentLog.Supplier.Id, typeof(ParserFake1));
            type = detector.GetSpecialParser(@"..\..\Data\Waybills\KZ000130.txt", documentLog);
            Assert.That(type, Is.Null);

            detector = new WaybillFormatDetectorFake();
            detector.AddSpecParser(documentLog.Supplier.Id, typeof(ParserFake3));
            bool fail = false;

            try {
                detector.GetSpecialParser(@"..\..\Data\Waybills\KZ000130.dbf", documentLog);
            }
            catch (Exception e) {
                fail = e.Message.Contains("реализуй метод CheckFileFormat");
            }
            Assert.That(fail, Is.True);

            detector = new WaybillFormatDetectorFake();
            detector.AddSpecParser(documentLog.Supplier.Id, typeof(ParserFake2));
            detector.AddSpecParser(documentLog.Supplier.Id, typeof(ParserFake1));
            type = detector.GetSpecialParser(@"..\..\Data\Waybills\KZ000130.dbf", documentLog);
            Assert.That(type.FullName.Contains("ParserFake1"), Is.True);

            detector = new WaybillFormatDetectorFake();

            detector.AddSpecParser(documentLog.Supplier.Id, typeof(ParserFake5));
            detector.AddSpecParser(documentLog.Supplier.Id, typeof(ParserFake7));
            detector.AddSpecParser(documentLog.Supplier.Id, typeof(ParserFake6));
            type = detector.GetSpecialParser(@"..\..\Data\Waybills\KZ000130.dbf", documentLog);
            Assert.That(type.FullName.Contains("ParserFake6"), Is.True);
        }
Example #5
0
        public void ChechForPulsFK3996Parser()
        {
            var detector = new WaybillFormatDetector();
            var filePath = "pulse1.dbf";

            if (!File.Exists(filePath))
            {
                filePath = Path.Combine(@"..\..\Data\Waybills\", filePath);
            }
            var parsers = detector.GetSuitableParsers(filePath, null).ToList();

            Assert.That(parsers.Count, Is.EqualTo(1));
            Assert.That(parsers[0].Name, Is.EqualTo("PulsFK3996Parser"));
        }
Example #6
0
        public void Parse()
        {
            var document = WaybillParser.Parse("белла-восток-F335064.DBF");

            Assert.That(document.Parser, Is.EqualTo("BellaVostokParser"));
            Assert.That(document.ProviderDocumentId.Trim(), Is.EqualTo("335064"));
            Assert.That(document.DocumentDate, Is.EqualTo(new DateTime(2016, 10, 13)));

            //проверяем что для разбора данного формата файла подходит только один парсер
            var detector = new WaybillFormatDetector();
            var parsers  = detector.GetSuitableParsers(@"..\..\Data\Waybills\белла-восток-F335064.DBF", null).ToList();

            Assert.That(parsers.ToList().Count, Is.EqualTo(1));

            var line0 = document.Lines[0];

            Assert.That(line0.Code, Is.EqualTo("190450"));
            Assert.That(line0.Product, Is.EqualTo("E.DEPIL Восков.полоски д/лица 20ш"));
            Assert.That(line0.EAN13, Is.EqualTo(8030009040075));
            Assert.That(line0.Quantity, Is.EqualTo(1));
            Assert.That(line0.Country, Is.EqualTo("Италия"));
            Assert.That(line0.Producer, Is.Null);
            Assert.That(line0.Period, Is.Null);
            Assert.That(line0.Nds, Is.EqualTo(18));
            Assert.That(line0.SupplierCost, Is.EqualTo(208.43));
            Assert.That(line0.SupplierCostWithoutNDS, Is.EqualTo(176.64));
            Assert.That(line0.VitallyImportant, Is.Null);
            Assert.That(line0.BillOfEntryNumber, Is.EqualTo("10110060/100810/0010685/0"));
            Assert.That(line0.Certificates, Is.EqualTo("РОСС IT ПК5 В36663 НИИ медицины Труда 16.12.14"));
            Assert.That(line0.CertificatesDate, Is.Null);
            Assert.That(line0.DateOfManufacture, Is.Null);
            Assert.That(line0.SerialNumber, Is.Null);

            var invoice = document.Invoice;

            Assert.That(invoice.InvoiceNumber, Is.Null);
            Assert.That(invoice.RecipientName, Is.Null);
            Assert.That(invoice.InvoiceDate, Is.Null);
        }
        public void Parse()
        {
            var document = WaybillParser.Parse("накл-беллаДон-bv006172.DBF");

            Assert.That(document.Parser, Is.EqualTo("BellaDonParser"));
            Assert.That(document.ProviderDocumentId, Is.EqualTo("В0000006172"));
            Assert.That(document.DocumentDate, Is.EqualTo(new DateTime(2015, 06, 04)));

            //проверяем что для разбора данного формата файла подходит только один парсер
            var detector = new WaybillFormatDetector();
            var parsers  = detector.GetSuitableParsers(@"..\..\Data\Waybills\r_03-068.DBF", null).ToList();

            Assert.That(parsers.ToList().Count, Is.EqualTo(1));

            var line0 = document.Lines[0];

            Assert.That(line0.Code, Is.EqualTo("SE-091-B010-J03"));
            Assert.That(line0.Product, Is.EqualTo("Гигиенические пеленки Seni Soft Basic 90*60 10 шт."));
            Assert.That(line0.EAN13, Is.EqualTo(5900516692469));
            Assert.That(line0.Quantity, Is.EqualTo(6));
            Assert.That(line0.Country, Is.EqualTo("РОССИЯ"));
            Assert.That(line0.Producer, Is.EqualTo("TZMO S.A."));
            Assert.That(line0.Period, Is.EqualTo("16.10.2016"));
            Assert.That(line0.Nds, Is.EqualTo(10));
            Assert.That(line0.SupplierCost, Is.EqualTo(175.58));
            Assert.That(line0.SupplierCostWithoutNDS, Is.EqualTo(159.62));
            Assert.That(line0.VitallyImportant, Is.False);
            Assert.That(line0.BillOfEntryNumber, Is.Null);
            Assert.That(line0.Certificates, Is.EqualTo("РОСС RU. ИМ09.Д00251"));
            Assert.That(line0.CertificatesDate, Is.EqualTo("03.12.2015"));
            Assert.That(line0.DateOfManufacture, Is.Null);
            Assert.That(line0.SerialNumber, Is.EqualTo("30999/00"));

            var invoice = document.Invoice;

            Assert.That(invoice.InvoiceNumber, Is.EqualTo("В0000006172"));
            Assert.That(invoice.RecipientName, Is.EqualTo("Фармспирт-1"));
            Assert.That(invoice.InvoiceDate, Is.EqualTo(new DateTime(2015, 06, 04)));
        }
Example #8
0
        public void Parse()
        {
            var document = WaybillParser.Parse("66426.dbf");

            Assert.That(document.Parser, Is.EqualTo("MedSnabKchrParser"));
            Assert.That(document.ProviderDocumentId.Trim(), Is.EqualTo("66426"));
            Assert.That(document.DocumentDate, Is.EqualTo(new DateTime(2016, 09, 27)));

            var detector = new WaybillFormatDetector();
            var parsers  = detector.GetSuitableParsers(@"..\..\Data\Waybills\66426.dbf", null).ToList();

            Assert.That(parsers.ToList().Count, Is.EqualTo(1));

            var line0 = document.Lines[0];

            Assert.That(line0.Code, Is.EqualTo("18036,0000"));
            Assert.That(line0.RegistryCost, Is.EqualTo(155));
            Assert.That(line0.RegistryDate, Is.EqualTo(new DateTime(2016, 04, 04)));
            Assert.That(line0.Product, Is.EqualTo("Зодак капли 10мг/мл 20мл"));
            Assert.That(line0.EAN13, Is.EqualTo(8594739055209));
            Assert.That(line0.Quantity, Is.EqualTo(2.0000));
            Assert.That(line0.SupplierCost, Is.EqualTo(183.1000));
            Assert.That(line0.SupplierCostWithoutNDS, Is.EqualTo(183.1000));
            Assert.That(line0.Producer, Is.EqualTo("Зентива/Лечива"));
            Assert.That(line0.ProducerCost, Is.EqualTo(171.1700));
            Assert.That(line0.ProducerCostWithoutNDS, Is.EqualTo(155.6100));
            Assert.That(line0.VitallyImportant, Is.True);
            Assert.That(line0.BillOfEntryNumber, Is.EqualTo("10113100/190416/0019473/5"));
            Assert.That(line0.Certificates, Is.EqualTo("РОСС CZ.ФМ08.Д21991"));
            Assert.That(line0.CertificatesEndDate, Is.EqualTo(new DateTime(2019, 02, 28)));
            Assert.That(line0.SerialNumber, Is.EqualTo("3130316"));

            var invoice = document.Invoice;

            Assert.That(invoice.InvoiceNumber, Is.EqualTo("170560,0000"));
            Assert.That(invoice.RecipientName, Is.Null);
            Assert.That(invoice.InvoiceDate, Is.Null);
        }
        public static Document Parse(string filePath, DocumentReceiveLog log = null)
        {
            var detector = new WaybillFormatDetector();

            if (!File.Exists(filePath))
            {
                filePath = Path.Combine(@"..\..\Data\Waybills\", filePath);
            }
            var parser  = detector.DetectParser(filePath, log);
            var parsers = detector.GetSuitableParsers(filePath, log).ToList();

            if (parsers.Count > 1)
            {
                throw new Exception($"Для разбора данного формата подходит более одного парсера, {parsers.Implode()}");
            }
            if (parser == null)
            {
                return(null);
            }
            log = log ??
                  new DocumentReceiveLog(new Supplier(), new Address {
                Client = new Client()
            });
            if (log.ClientCode == null)
            {
                log.ClientCode = 0;
            }
            var document = new Document(log, parser.GetType().Name);
            var doc      = parser.Parse(filePath, document);

            if (doc != null)
            {
                doc.CalculateValues();
            }
            return(doc);
        }
        public void ProcessMessage(ISession session, MimeMessage message, UniqueId messageId = default(UniqueId))
        {
            //используется промежуточный почтовый ящик для транзита
            //в поле To будет именно он, этот же ящик используется для транзита прайс-листов
            var emails =
                message.To.OfType <MailboxAddress>().Where(s => !string.IsNullOrEmpty(s.Address)).Select(a => a.Address).ToArray();

            if (emails.Length == 0)
            {
                NotifyAdmin("У сообщения не указано ни одного получателя.", message);
                return;
            }
            var attachments = message.Attachments.Where(m => !String.IsNullOrEmpty(GetFileName(m)) && m.IsAttachment);

            if (!attachments.Any())
            {
                NotifyAdmin($"Отсутствуют вложения в письме от адреса {message.To.Implode()}", message);
                return;
            }

            var dtSources = session.Connection.Query <SupplierSelector>(@"
SELECT distinct
	s.Id as FirmCode,
	st.EMailTo
FROM farm.sourcetypes
	join farm.Sources as st on st.SourceTypeId = sourcetypes.Id
		join usersettings.PriceItems pi on pi.SourceId = st.ID
			join usersettings.PricesCosts pc on pc.PriceItemId = pi.ID
				join UserSettings.PricesData  as PD on PD.PriceCode = pc.PriceCode
					join Customers.Suppliers as s on s.Id = PD.FirmCode
WHERE
	sourcetypes.Type = 'EMail'
	and s.Disabled = 0
	and pd.AgencyEnabled = 1"    ).ToList();

            var sources = emails
                          .SelectMany(x => dtSources.Where(y => y.EmailTo?.IndexOf(x, StringComparison.OrdinalIgnoreCase) >= 0))
                          .Distinct()
                          .ToList();

            if (sources.Count > 1)
            {
                NotifyAdmin(
                    $"Для получателей {emails.Implode()} определено более одного поставщика." +
                    $" Определенные поставщики {sources.Select(x => x.FirmCode).Implode()}.", message);
                return;
            }
            if (sources.Count == 0)
            {
                NotifyAdmin(
                    $"Не удалось идентифицировать ни одного поставщика по адресам получателя {emails.Implode()}." +
                    $" Количество записей в источниках - {dtSources.Count}", message);
                return;
            }

            var source     = sources.First();
            var supplierId = source.FirmCode;
            var supplier   = session.Load <Supplier>(supplierId);

            using (var cleaner = new FileCleaner()) {
                foreach (var mimeEntity in attachments)
                {
                    //получение текущей директории
                    var filename = Path.Combine(DownHandlerPath, GetFileName(mimeEntity));
                    var files    = new List <string> {
                        filename
                    };

                    //сохранение содержимого в текущую директорию
                    using (var fs = new FileStream(filename, FileMode.Create))
                        ((MimePart)mimeEntity).ContentObject.DecodeTo(fs);

                    try {
                        files = FileHelper.TryExtractArchive(filename, cleaner.RandomDir())?.ToList()
                                ?? files;
                    } catch (ArchiveHelper.ArchiveException e) {
                        _logger.Warn($"Не удалось распаковать файл {filename}", e);
                        NotifyAdmin($"Не удалось распаковать файл {filename}.", message, supplier);
                        continue;
                    }

                    var logs = new List <DocumentReceiveLog>();
                    foreach (var file in files)
                    {
                        //нам нужно считать файл что бы узнать кто его отправил, по хорошему нам и не нужен пока что клиент
                        var doc = new WaybillFormatDetector().Parse(session, file, new DocumentReceiveLog(supplier, new Address(new Client()), DocType.Waybill));
                        if (doc == null)
                        {
                            NotifyAdmin($"Не удалось разобрать документ {file} нет подходящего формата.", message, supplier);
                            continue;
                        }
                        if (doc.Invoice?.RecipientId == null)
                        {
                            if (doc.Parser == nameof(WaybillSstParser))
                            {
                                NotifyAdmin($"В файле {file} не заполнено поле Код получателя.", message, supplier);
                            }
                            else
                            {
                                NotifyAdmin($"Формат файла {file} не соответствует согласованному формату sst. " +
                                            $"Поле 'Код получателя' не заполнено, возможно выбранный формат {doc.Parser} не считывает поле либо оно не заполнено в файла. " +
                                            $"Проверьте настройки формата {doc.Parser} и заполнение поля 'Код получателя' в файле.", message, supplier);
                            }
                            continue;
                        }

                        var result = session.Connection.Query <uint?>(@"
select ai.AddressId
from Customers.Intersection i
	join Customers.AddressIntersection ai on ai.IntersectionId = i.Id
	join Usersettings.Pricesdata pd on pd.PriceCode = i.PriceId
		join Customers.Suppliers s on s.Id = pd.FirmCode
where ai.SupplierDeliveryId = @supplierDeliveryId
	and s.Id  = @supplierId
group by ai.AddressId", new { @supplierDeliveryId = doc.Invoice.RecipientId, @supplierId = supplierId })
                                     .FirstOrDefault();

                        if (result == null)
                        {
                            NotifyAdmin($"Не удалось обработать документ {file} для кода получателя {doc.Invoice.RecipientId} не найден адрес доставки. " +
                                        $"Проверьте заполнение поля 'Код адреса доставки' в личном кабинете поставщика {supplierId}.",
                                        message, supplier);
                            continue;
                        }

                        _logger.InfoFormat($"Файл {file} обработан для кода получателя {doc.Invoice.RecipientId} выбран адрес {result.Value}");
                        logs.Add(DocumentReceiveLog.LogNoCommit(supplierId, result.Value, file, DocType.Waybill, "Получен по Email",
                                                                (int?)messageId.Id));
                    }
                    //если логи есть, значит файл распознан и найден соответствующий адрес доставки
                    if (logs.Count > 0)
                    {
                        var service = new WaybillService();
                        service.Process(logs);
                        if (service.Exceptions.Count > 0)
                        {
                            NotifyAdmin(service.Exceptions.First().Message, message, supplier);
                        }
                    }
                }
            }
        }
Example #11
0
 public void Setup()
 {
     detector = new WaybillFormatDetector();
 }