コード例 #1
0
        public void ProcessFile(InboundDocumentType documentType, WaybillSource waybillSource, DownloadedFile downloadedFile)
        {
            var logs = ProcessWaybill(documentType.DocType, waybillSource, downloadedFile);

            // Обработка накладной(или отказа), помещение ее в папку клиенту
            new WaybillService().Process(logs);
        }
コード例 #2
0
        public void Get_source()
        {
            var source = new WaybillSource {
                WaybillUrl = "ftp2.yarfarma.ru/invoice/",
                RejectUrl  = "ftp2.yarfarma.ru/deny/"
            };

            Assert.AreEqual("ftp://ftp2.yarfarma.ru/deny/", source.Uri(new RejectType()).ToString());
        }
コード例 #3
0
        public void Parse_uri()
        {
            var source = new WaybillSource();

            source.WaybillUrl = "ftp.oriola-russia.ru/Nakl/";
            var uri = source.Uri(new WaybillType());

            Assert.That(uri.ToString(), Is.EqualTo("ftp://ftp.oriola-russia.ru/Nakl/"));
            Assert.That(uri.Host, Is.EqualTo("ftp.oriola-russia.ru"));
        }
コード例 #4
0
        public void Set_active_mode()
        {
            var source = new WaybillSource();
            var client = source.CreateFtpClient();

            Assert.That(client.PassiveMode, Is.True);

            source.FtpActiveMode = true;
            client = source.CreateFtpClient();
            Assert.That(client.PassiveMode, Is.False);
        }
コード例 #5
0
        private bool IsNewWaybill(WaybillSource source,
                                  uint addressId,
                                  string filename,
                                  long filesize)
        {
            using (new SessionScope(FlushAction.Never)) {
                var docs = DocumentReceiveLog.Queryable
                           .Where(d => d.Supplier.Id == source.Id &&
                                  d.FileName == filename &&
                                  d.DocumentSize == filesize &&
                                  d.Address.Id == addressId);

                return(!docs.Any());
            }
        }
コード例 #6
0
        private void LogError(Exception e, WaybillSource source, Uri uri, InboundDocumentType documentType)
        {
            var errorMessage = String.Format("Ошибка при попытке забрать документы с FTP поставщика (код поставщика: {0}).\nТип документов: {1}.\nUrl: {2}",
                                             source.Id,
                                             documentType.DocType.GetDescription(),
                                             uri);

            if (!_failedSources.Contains(source.Id))
            {
                _failedSources.Add(source.Id);
                _logger.Warn(errorMessage, e);
            }
            else
            {
                _logger.Debug(errorMessage, e);
            }
        }
コード例 #7
0
        public void Waybill_Source_Settings_Test()
        {
            var waybillSource = new WaybillSource {
                SourceType = WaybillSourceType.FtpSupplier, ReaderClassName = "testReaderClass", Supplier = supplier
            };

            session.Save(waybillSource);

            Open("Suppliers/WaybillSourceSettings?supplierId=" + supplier.Id);
            AssertText("Настройка данных для доступа к FTP");
            Css("#source_WaybillUrl").AppendText("testUrl");
            Css("#source_RejectUrl").AppendText("testUrl");
            Css("#userName").AppendText("testUser");
            Css("#source_Password").AppendText("testPassword");
            Css("#source_downloadInterval").AppendText("5");
            Click("Сохранить");
            AssertText("Сохранено");
        }
コード例 #8
0
        private List <DocumentReceiveLog> ProcessWaybill(DocType documentType, WaybillSource source, DownloadedFile downloadedFile)
        {
            var documentLogs = new List <DocumentReceiveLog>();
            var reader       = new SupplierFtpReader();

            var addressIds = With.Connection(c => reader.ParseAddressIds(c, source.Id, downloadedFile.FileName, downloadedFile.FileName));

            foreach (var addressId in addressIds)
            {
                // Если накладная - это архив, разархивируем логируем каждый файл и копируем в папку клиенту
                var waybillFiles = new[] { downloadedFile.FileName };
                try {
                    waybillFiles = FileHelper.TryExtractArchive(downloadedFile.FileName, downloadedFile.FileName + BaseSourceHandler.ExtrDirSuffix)
                                   ?? waybillFiles;
                }
                catch (ArchiveHelper.ArchiveException e) {
                    _logger.Warn($"Ошибка при извлечении файлов из архива {downloadedFile.FileName}", e);
                    WaybillService.SaveWaybill(downloadedFile.FileName);
                    continue;
                }

                foreach (var file in waybillFiles)
                {
                    var isNew = IsNewWaybill(source, (uint)addressId, Path.GetFileName(file), new FileInfo(file).Length);
                    if (!isNew)
                    {
                        _logger.DebugFormat("Файл {0} не является новой накладной, не обрабатываем его", file);
                        continue;
                    }
                    var log = DocumentReceiveLog.LogNoCommit(source.Id,
                                                             (uint)addressId,
                                                             file,
                                                             documentType,
                                                             "Получен с клиентского FTP");
                    _logger.InfoFormat("WaybillFtpSourceHandler: обработка файла {0}", file);
                    documentLogs.Add(log);
                }
            }
            return(documentLogs);
        }
コード例 #9
0
        private void ReceiveDocuments(InboundDocumentType documentType, WaybillSource waybillSource, Uri uri)
        {
            var haveErrors = false;

            if (uri == null)
            {
                return;
            }

            _logger.InfoFormat("Попытка получения документов с FTP поставщика (код поставщика: {0}).\nТип документов: {1}.\nUrl: {2}",
                               waybillSource.Id,
                               documentType.DocType.GetDescription(),
                               uri);

            try {
                using (var ftpClient = waybillSource.CreateFtpClient()) {
                    ftpClient.Connect(uri.Host, uri.Port);
                    ftpClient.Authenticate(waybillSource.UserName, waybillSource.Password);
                    ftpClient.SetCurrentDir(uri.PathAndQuery);

                    var files = ftpClient.GetList();
                    foreach (var file in files.Tables["DirInfo"].AsEnumerable())
                    {
                        if (Convert.ToBoolean(file["IsDirectory"]))
                        {
                            continue;
                        }

                        Cancellation.ThrowIfCancellationRequested();

                        var source       = file["Name"].ToString();
                        var sourceDate   = Convert.ToDateTime(file["Date"]);
                        var sourceLength = Convert.ToInt64(file["Size"]);
                        var dest         = Path.Combine(DownHandlerPath, source);
                        try {
                            ftpClient.ReceiveFile(source, dest);
                            var destLenth = new FileInfo(dest).Length;
                            if (destLenth != sourceLength)
                            {
                                _logger.WarnFormat("Не совпадает размер загруженного файла {0} {1} размер на ftp {2} полученный рамер {3}",
                                                   uri,
                                                   source,
                                                   sourceLength,
                                                   destLenth);
                                continue;
                            }

                            var downloadedFile = new DownloadedFile(dest, sourceDate);

                            ProcessFile(documentType, waybillSource, downloadedFile);

                            ftpClient.DeleteFile(source);
                        }
                        catch (Exception e) {
                            haveErrors = true;
                            LogError(e, waybillSource, uri, documentType);
                        }
                    }
                }

                if (!haveErrors && _failedSources.Contains(waybillSource.Id))
                {
                    waybillSource.LastError = DateTime.Now;
                    _failedSources.Remove(waybillSource.Id);
                    _logger.WarnFormat("После возникновения ошибок загрузка накладных прошла успешно. Код поставщика: {0}", waybillSource.Id);
                }
            }
            catch (Exception e) {
                LogError(e, waybillSource, uri, documentType);
            }
        }