| | | 1 | | using Microsoft.AspNetCore.Http; |
| | | 2 | | using SVETA.Api.Services.Interfaces; |
| | | 3 | | using SVETA.Api.Services.Interfaces.ImportingExporting; |
| | | 4 | | using System; |
| | | 5 | | using System.Collections.Generic; |
| | | 6 | | using System.Data; |
| | | 7 | | using System.IO; |
| | | 8 | | using System.Linq; |
| | | 9 | | using System.Reflection; |
| | | 10 | | using System.Threading.Tasks; |
| | | 11 | | using WinSolutions.Sveta.Common.Extensions; |
| | | 12 | | using SVETA.Api.Services.Implements.ImportingExporting.Importers; |
| | | 13 | | using WinSolutions.Sveta.Server.Data.DataModel.Entities; |
| | | 14 | | using WinSolutions.Sveta.Server.Data.DataModel.Contexts; |
| | | 15 | | using WinSolutions.Sveta.Server.Services.Implements; |
| | | 16 | | using WinSolutions.Sveta.Common; |
| | | 17 | | using SVETA.Api.Data.Domain; |
| | | 18 | | using Microsoft.Extensions.Options; |
| | | 19 | | |
| | | 20 | | namespace SVETA.Api.Services.Implements.ImportingExporting |
| | | 21 | | { |
| | | 22 | | public class ImportService : SvetaServiceBase, IImportService |
| | | 23 | | { |
| | | 24 | | private readonly IRecordImporter<GoodSettingRecord> _goodSettingImporter; |
| | | 25 | | private readonly IRecordImporter<RestRecord> _restImporter; |
| | | 26 | | private readonly IDiskStorageService _diskStorageService; |
| | | 27 | | private readonly SvetaDbContext _db; |
| | | 28 | | CommonSettings _commonSettings; |
| | | 29 | | |
| | | 30 | | public ImportService(IAuthenticationService authenticationService, IRecordImporter<GoodSettingRecord> goodSettin |
| | | 31 | | IRecordImporter<RestRecord> restImporter, |
| | 0 | 32 | | IDiskStorageService diskStorageService, SvetaDbContext db, IOptions<CommonSettings> commonSettings) : base(a |
| | 0 | 33 | | { |
| | 0 | 34 | | _restImporter = restImporter; |
| | 0 | 35 | | _goodSettingImporter = goodSettingImporter; |
| | 0 | 36 | | _diskStorageService = diskStorageService; |
| | 0 | 37 | | _db = db; |
| | 0 | 38 | | _commonSettings = commonSettings.Value; |
| | 0 | 39 | | } |
| | | 40 | | |
| | | 41 | | public async Task<MemoryStream> GetGoodSettingsTemplate() |
| | 0 | 42 | | { |
| | 0 | 43 | | var records = new List<GoodSettingRecord> |
| | 0 | 44 | | { |
| | 0 | 45 | | new GoodSettingRecord() |
| | 0 | 46 | | { |
| | 0 | 47 | | UniqueCode = "DD00007762", |
| | 0 | 48 | | VendorCode = "1234578", |
| | 0 | 49 | | BarCode = "4005900487582", |
| | 0 | 50 | | GoodName = "3в1 Черная Пенка для умывания для жирной кожи, склонной к несовершенствам", |
| | 0 | 51 | | MinQuantity = "1", |
| | 0 | 52 | | PickingQuantum = "1", |
| | 0 | 53 | | ShowcaseVisible = "0" |
| | 0 | 54 | | } |
| | 0 | 55 | | }; |
| | 0 | 56 | | var template = TemplateHelper.GetTemplate(records); |
| | 0 | 57 | | return CsvUtil.ToExcelStream(template); |
| | 0 | 58 | | } |
| | | 59 | | |
| | | 60 | | public Task<MemoryStream> GetGoodsTemplate() |
| | 0 | 61 | | { |
| | 0 | 62 | | throw new NotImplementedException(); |
| | | 63 | | } |
| | | 64 | | |
| | | 65 | | public Task<MemoryStream> GetPricesTemplate() |
| | 0 | 66 | | { |
| | 0 | 67 | | throw new NotImplementedException(); |
| | | 68 | | } |
| | | 69 | | |
| | | 70 | | public async Task<MemoryStream> GetRestsTemplate() |
| | 0 | 71 | | { |
| | 0 | 72 | | var records = new List<RestRecord> |
| | 0 | 73 | | { |
| | 0 | 74 | | new RestRecord() |
| | 0 | 75 | | { |
| | 0 | 76 | | UniqueCode = "DD00007762", |
| | 0 | 77 | | VendorCode = "1234578", |
| | 0 | 78 | | BarCode = "4005900487582", |
| | 0 | 79 | | GoodName = "3в1 Черная Пенка для умывания для жирной кожи, склонной к несовершенствам", |
| | 0 | 80 | | Quantity = "1" |
| | 0 | 81 | | } |
| | 0 | 82 | | }; |
| | 0 | 83 | | var template = TemplateHelper.GetTemplate(records); |
| | 0 | 84 | | return CsvUtil.ToExcelStream(template); |
| | 0 | 85 | | } |
| | | 86 | | |
| | | 87 | | public Task<MemoryStream> GetWorkSchedulesTemplate() |
| | 0 | 88 | | { |
| | 0 | 89 | | throw new NotImplementedException(); |
| | | 90 | | } |
| | | 91 | | |
| | | 92 | | public async Task<IImportResult> ImportGoodSettings(long departmentId, IFormFile file) |
| | 0 | 93 | | { |
| | 0 | 94 | | return await ImportFromExcel(file, _goodSettingImporter, new Dictionary<string, object> { { nameof(departmen |
| | 0 | 95 | | } |
| | | 96 | | |
| | | 97 | | public Task<IImportResult> ImportPhotos(IFormFile file) |
| | 0 | 98 | | { |
| | | 99 | | //Importer.FromZip<GoodSettingRecord>(file); |
| | 0 | 100 | | throw new NotImplementedException(); |
| | | 101 | | } |
| | | 102 | | |
| | | 103 | | public Task<IImportResult> ImportPrices(long priceTrendId, IFormFile file) |
| | 0 | 104 | | { |
| | 0 | 105 | | throw new NotImplementedException(); |
| | | 106 | | } |
| | | 107 | | |
| | | 108 | | public async Task<IImportResult> ImportRests(long departmentId, IFormFile file) |
| | 0 | 109 | | { |
| | 0 | 110 | | return await ImportFromExcel(file, _restImporter, new Dictionary<string, object> { { nameof(departmentId), d |
| | 0 | 111 | | } |
| | | 112 | | |
| | | 113 | | public Task<IImportResult> ImportWorkSchedules(long departmentId, IFormFile file) |
| | 0 | 114 | | { |
| | 0 | 115 | | throw new NotImplementedException(); |
| | | 116 | | } |
| | | 117 | | |
| | | 118 | | async Task<IImportResult> ImportFromExcel<TRecord>(IFormFile file, IRecordImporter<TRecord> importer, Dictionary |
| | 0 | 119 | | { |
| | 0 | 120 | | importer.Context = context ?? new Dictionary<string, object>(); |
| | | 121 | | |
| | 0 | 122 | | var upload = new Upload(); |
| | | 123 | | DataTable dataTable; |
| | | 124 | | string fileName; |
| | 0 | 125 | | using (var stream = _diskStorageService.SaveUpload(file, out fileName)) |
| | 0 | 126 | | { |
| | 0 | 127 | | dataTable = FileReader.ReadFromExcel(stream, file.ContentType); |
| | 0 | 128 | | } |
| | 0 | 129 | | upload.SourceFileName = fileName; |
| | 0 | 130 | | upload.CreatedByUserId = CurrentUserId; |
| | 0 | 131 | | upload.CreationDateTime = DateTime.UtcNow; |
| | 0 | 132 | | _db.Add(upload); |
| | 0 | 133 | | _db.SaveChanges(); |
| | | 134 | | |
| | | 135 | | // проверяем структуру таблицы на наличие всех полей |
| | 0 | 136 | | var props = TemplateHelper.GetMappedProperties<TRecord>(); |
| | 0 | 137 | | foreach(var prop in props) |
| | 0 | 138 | | { |
| | 0 | 139 | | if(!dataTable.Columns.Contains(prop.Name)) |
| | 0 | 140 | | { |
| | 0 | 141 | | throw new Exception($"Поле {prop.Name} не найдено"); |
| | | 142 | | } |
| | 0 | 143 | | } |
| | | 144 | | |
| | | 145 | | // событие перед валидацией |
| | 0 | 146 | | importer.BeforeValidation(); |
| | | 147 | | |
| | | 148 | | // достаем все записи в DTO объект, валидируем каждый объект |
| | 0 | 149 | | List<TRecord> records = new List<TRecord>(); |
| | 0 | 150 | | Dictionary<TRecord, Exception> invalidRecords = new Dictionary<TRecord, Exception>(); |
| | 0 | 151 | | foreach (DataRow row in dataTable.Rows) |
| | 0 | 152 | | { |
| | 0 | 153 | | var record = new TRecord(); |
| | | 154 | | try |
| | 0 | 155 | | { |
| | 0 | 156 | | foreach (var prop in props) |
| | 0 | 157 | | { |
| | 0 | 158 | | prop.SetValue(record, row[prop.Name].ToString().NormalizeName()); |
| | 0 | 159 | | } |
| | 0 | 160 | | importer.Validate(record); |
| | 0 | 161 | | records.Add(record); |
| | 0 | 162 | | } |
| | 0 | 163 | | catch (Exception ex) |
| | 0 | 164 | | { |
| | 0 | 165 | | invalidRecords.Add(record, ex); |
| | 0 | 166 | | } |
| | 0 | 167 | | } |
| | | 168 | | |
| | | 169 | | // событие после валидации |
| | 0 | 170 | | importer.AfterValidation(); |
| | | 171 | | |
| | | 172 | | // импортируем валидные записи |
| | 0 | 173 | | records.ForEach(x => |
| | 0 | 174 | | { |
| | 0 | 175 | | try |
| | 0 | 176 | | { |
| | 0 | 177 | | importer.Import(x); |
| | 0 | 178 | | } |
| | 0 | 179 | | catch (Exception ex) |
| | 0 | 180 | | { |
| | 0 | 181 | | invalidRecords.Add(x, ex); |
| | 0 | 182 | | } |
| | 0 | 183 | | }); |
| | 0 | 184 | | await _db.SaveChangesAsync(CurrentUserId); |
| | | 185 | | |
| | | 186 | | // событие после импорта |
| | 0 | 187 | | importer.AfterImport(); |
| | 0 | 188 | | await _db.SaveChangesAsync(CurrentUserId); |
| | | 189 | | |
| | | 190 | | // формирование объекта с результатами |
| | | 191 | | // и сохранение отчета об ошибках если были |
| | 0 | 192 | | var result = new ImportResult |
| | 0 | 193 | | { |
| | 0 | 194 | | uploadId = upload.Id, |
| | 0 | 195 | | succeed = invalidRecords.Count == 0, |
| | 0 | 196 | | errorCount = invalidRecords.Count |
| | 0 | 197 | | }; |
| | 0 | 198 | | if (!result.succeed) |
| | 0 | 199 | | { |
| | 0 | 200 | | var rows = TemplateHelper.GetTemplateWithError(invalidRecords); |
| | | 201 | | |
| | | 202 | | // сохраняем на диск эксель с отчетом |
| | 0 | 203 | | var stream = CsvUtil.ToExcelStream(rows); |
| | 0 | 204 | | _diskStorageService.SaveDownload($"upload-report{result.uploadId}.xlsx", stream, false); |
| | 0 | 205 | | result.reportUrl = $"{_commonSettings.BaseUrl.TrimEnd('/')}/api/v1/Upload/GetReport?id={result.uploadId} |
| | 0 | 206 | | } |
| | 0 | 207 | | return result; |
| | 0 | 208 | | } |
| | | 209 | | } |
| | | 210 | | } |