Blame view

美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/LocationAppService.cs 13.8 KB
a7684ddb   李曜臣   批量导入导出,批量编辑
1
  using System.IO;
143afd59   杨鑫   打印,标签
2
  using FoodLabeling.Application.Helpers;
9df65e38   李曜臣   实现美国版门店与RBAC对外接口
3
  using FoodLabeling.Application.Contracts.Dtos.Location;
a7684ddb   李曜臣   批量导入导出,批量编辑
4
  using FoodLabeling.Application.Contracts.Dtos.Common;
9df65e38   李曜臣   实现美国版门店与RBAC对外接口
5
  using FoodLabeling.Application.Contracts.IServices;
a7684ddb   李曜臣   批量导入导出,批量编辑
6
  using FoodLabeling.Application.Options;
9df65e38   李曜臣   实现美国版门店与RBAC对外接口
7
  using FoodLabeling.Domain.Entities;
9df65e38   李曜臣   实现美国版门店与RBAC对外接口
8
  using Microsoft.AspNetCore.Mvc;
a7684ddb   李曜臣   批量导入导出,批量编辑
9
  using Microsoft.Extensions.Options;
9df65e38   李曜臣   实现美国版门店与RBAC对外接口
10
11
12
13
  using SqlSugar;
  using Volo.Abp;
  using Volo.Abp.Application.Dtos;
  using Volo.Abp.Application.Services;
a7684ddb   李曜臣   批量导入导出,批量编辑
14
  using Volo.Abp.Domain.Repositories;
9df65e38   李曜臣   实现美国版门店与RBAC对外接口
15
16
17
18
19
20
21
22
23
24
  using Yi.Framework.SqlSugarCore.Abstractions;
  
  namespace FoodLabeling.Application.Services;
  
  /// <summary>
  /// 门店管理服务(美国版)
  /// </summary>
  public class LocationAppService : ApplicationService, ILocationAppService
  {
      private readonly ISqlSugarRepository<LocationAggregateRoot, Guid> _locationRepository;
07d5dea2   李曜臣   5-18代码优化
25
      private readonly ISqlSugarDbContext _dbContext;
a7684ddb   李曜臣   批量导入导出,批量编辑
26
      private readonly IOptionsSnapshot<FoodLabelingBatchImportOptions> _batchImportOptions;
9df65e38   李曜臣   实现美国版门店与RBAC对外接口
27
  
a7684ddb   李曜臣   批量导入导出,批量编辑
28
29
      public LocationAppService(
          ISqlSugarRepository<LocationAggregateRoot, Guid> locationRepository,
07d5dea2   李曜臣   5-18代码优化
30
          ISqlSugarDbContext dbContext,
a7684ddb   李曜臣   批量导入导出,批量编辑
31
          IOptionsSnapshot<FoodLabelingBatchImportOptions> batchImportOptions)
9df65e38   李曜臣   实现美国版门店与RBAC对外接口
32
33
      {
          _locationRepository = locationRepository;
07d5dea2   李曜臣   5-18代码优化
34
          _dbContext = dbContext;
a7684ddb   李曜臣   批量导入导出,批量编辑
35
          _batchImportOptions = batchImportOptions;
9df65e38   李曜臣   实现美国版门店与RBAC对外接口
36
37
38
39
40
41
42
      }
  
      /// <inheritdoc />
      public async Task<PagedResultWithPageDto<LocationGetListOutputDto>> GetListAsync([FromQuery] LocationGetListInputVo input)
      {
          RefAsync<int> total = 0;
  
07d5dea2   李曜臣   5-18代码优化
43
          var query = await BuildFilteredQueryAsync(input);
9df65e38   李曜臣   实现美国版门店与RBAC对外接口
44
45
46
47
48
49
50
51
52
53
54
          if (!string.IsNullOrWhiteSpace(input.Sorting))
          {
              query = query.OrderBy(input.Sorting);
          }
          else
          {
              query = query.OrderBy(x => x.CreationTime, OrderByType.Desc);
          }
  
          var entities = await query.ToPageListAsync(input.SkipCount, input.MaxResultCount, total);
  
a7684ddb   李曜臣   批量导入导出,批量编辑
55
          var items = entities.Select(ToListDto).ToList();
9df65e38   李曜臣   实现美国版门店与RBAC对外接口
56
57
  
          var pageSize = input.MaxResultCount <= 0 ? items.Count : input.MaxResultCount;
143afd59   杨鑫   打印,标签
58
          var pageIndex = pageSize <= 0 ? 1 : PagedQueryConvention.PageIndexFromSkipCount(input.SkipCount);
a7684ddb   李曜臣   批量导入导出,批量编辑
59
          var totalPages = pageSize <= 0 ? 0 : (int)Math.Ceiling(total.Value / (double)pageSize);
9df65e38   李曜臣   实现美国版门店与RBAC对外接口
60
61
62
63
64
  
          return new PagedResultWithPageDto<LocationGetListOutputDto>
          {
              PageIndex = pageIndex,
              PageSize = pageSize,
a7684ddb   李曜臣   批量导入导出,批量编辑
65
              TotalCount = total.Value,
9df65e38   李曜臣   实现美国版门店与RBAC对外接口
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
              TotalPages = totalPages,
              Items = items
          };
      }
  
      /// <inheritdoc />
      public async Task<LocationGetListOutputDto> CreateAsync([FromBody] LocationCreateInputVo input)
      {
          var locationCode = input.LocationCode?.Trim();
          if (string.IsNullOrWhiteSpace(locationCode))
          {
              throw new UserFriendlyException("Location ID不能为空");
          }
  
          var locationName = input.LocationName?.Trim();
          if (string.IsNullOrWhiteSpace(locationName))
          {
              throw new UserFriendlyException("Location Name不能为空");
          }
  
          var isExist = await _locationRepository.IsAnyAsync(x => x.LocationCode == locationCode);
          if (isExist)
          {
              throw new UserFriendlyException("Location ID已存在");
          }
  
          var entity = new LocationAggregateRoot(GuidGenerator.Create())
          {
              Partner = input.Partner?.Trim(),
              GroupName = input.GroupName?.Trim(),
              LocationCode = locationCode,
              LocationName = locationName,
              Street = input.Street?.Trim(),
              City = input.City?.Trim(),
              StateCode = input.StateCode?.Trim(),
              Country = input.Country?.Trim(),
              ZipCode = input.ZipCode?.Trim(),
              Phone = input.Phone?.Trim(),
              Email = input.Email?.Trim(),
              Latitude = input.Latitude,
              Longitude = input.Longitude,
10fd1324   李曜臣   5-17接口优化
107
              OperatingHours = input.OperatingHours?.Trim(),
9df65e38   李曜臣   实现美国版门店与RBAC对外接口
108
109
110
111
112
              State = input.State
          };
  
          await _locationRepository.InsertAsync(entity);
  
a7684ddb   李曜臣   批量导入导出,批量编辑
113
          return ToListDto(entity);
9df65e38   李曜臣   实现美国版门店与RBAC对外接口
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
      }
  
      /// <inheritdoc />
      public async Task<LocationGetListOutputDto> UpdateAsync(Guid id, [FromBody] LocationUpdateInputVo input)
      {
          var entity = await _locationRepository.GetSingleAsync(x => x.Id == id && x.IsDeleted == false);
          if (entity is null)
          {
              throw new UserFriendlyException("门店不存在");
          }
  
          var locationName = input.LocationName?.Trim();
          if (string.IsNullOrWhiteSpace(locationName))
          {
              throw new UserFriendlyException("Location Name不能为空");
          }
  
9df65e38   李曜臣   实现美国版门店与RBAC对外接口
131
132
133
134
135
136
137
138
139
140
141
142
          entity.Partner = input.Partner?.Trim();
          entity.GroupName = input.GroupName?.Trim();
          entity.LocationName = locationName;
          entity.Street = input.Street?.Trim();
          entity.City = input.City?.Trim();
          entity.StateCode = input.StateCode?.Trim();
          entity.Country = input.Country?.Trim();
          entity.ZipCode = input.ZipCode?.Trim();
          entity.Phone = input.Phone?.Trim();
          entity.Email = input.Email?.Trim();
          entity.Latitude = input.Latitude;
          entity.Longitude = input.Longitude;
10fd1324   李曜臣   5-17接口优化
143
          entity.OperatingHours = input.OperatingHours?.Trim();
9df65e38   李曜臣   实现美国版门店与RBAC对外接口
144
145
146
147
          entity.State = input.State;
  
          await _locationRepository.UpdateAsync(entity);
  
a7684ddb   李曜臣   批量导入导出,批量编辑
148
          return ToListDto(entity);
9df65e38   李曜臣   实现美国版门店与RBAC对外接口
149
150
151
152
153
154
155
156
157
158
159
160
161
162
      }
  
      /// <inheritdoc />
      public async Task DeleteAsync(Guid id)
      {
          var entity = await _locationRepository.GetSingleAsync(x => x.Id == id && x.IsDeleted == false);
          if (entity is null)
          {
              throw new UserFriendlyException("门店不存在");
          }
  
          entity.IsDeleted = true;
          await _locationRepository.UpdateAsync(entity);
      }
9df65e38   李曜臣   实现美国版门店与RBAC对外接口
163
  
a7684ddb   李曜臣   批量导入导出,批量编辑
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
      /// <inheritdoc />
      public Task<IActionResult> DownloadLocationImportTemplateAsync()
      {
          var opt = _batchImportOptions.Value;
          var dir = opt.TemplateDirectory?.Trim();
          if (string.IsNullOrWhiteSpace(dir))
          {
              throw new UserFriendlyException("未配置批量导入模板目录 FoodLabeling:BatchImport:TemplateDirectory");
          }
  
          var fileName = opt.LocationTemplateFileName?.Trim();
          if (string.IsNullOrWhiteSpace(fileName))
          {
              throw new UserFriendlyException("未配置模板文件名 FoodLabeling:BatchImport:LocationTemplateFileName");
          }
  
          var fullPath = Path.Combine(dir, fileName);
          if (!File.Exists(fullPath))
          {
              throw new UserFriendlyException($"模板文件不存在:{fullPath}");
          }
  
          var stream = new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.Read);
          const string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
          return Task.FromResult<IActionResult>(new FileStreamResult(stream, contentType)
          {
              FileDownloadName = fileName
          });
      }
  
      /// <inheritdoc />
      public async Task<IActionResult> ExportLocationsExcelAsync([FromQuery] LocationGetListInputVo input)
      {
          var exportFilter = new LocationGetListInputVo
          {
              Sorting = input.Sorting,
              Keyword = input.Keyword,
              Partner = input.Partner,
              GroupName = input.GroupName,
              State = input.State
          };
  
07d5dea2   李曜臣   5-18代码优化
206
          var query = await BuildFilteredQueryAsync(exportFilter);
a7684ddb   李曜臣   批量导入导出,批量编辑
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
          if (!string.IsNullOrWhiteSpace(exportFilter.Sorting))
          {
              query = query.OrderBy(exportFilter.Sorting);
          }
          else
          {
              query = query.OrderBy(x => x.CreationTime, OrderByType.Desc);
          }
  
          var entities = await query.ToListAsync();
          var rows = entities.Select(ToListDto).ToList();
  
          var ms = LocationBatchExcelHelper.BuildExportWorkbook(rows);
          const string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
          var downloadName = $"locations-export-{Clock.Now:yyyyMMdd-HHmmss}.xlsx";
          return new FileStreamResult(ms, contentType) { FileDownloadName = downloadName };
      }
  
      /// <inheritdoc />
      public async Task<LocationBatchImportResultDto> ImportLocationsBatchAsync([FromForm] LocationBatchImportInputVo input)
      {
          if (input?.File is null || input.File.Length == 0)
          {
              throw new UserFriendlyException("请上传 Excel 文件(form 字段名:file)");
          }
  
          var opt = _batchImportOptions.Value;
          if (input.File.Length > opt.MaxUploadBytes)
          {
              throw new UserFriendlyException($"文件过大,最大允许 {opt.MaxUploadBytes / 1024 / 1024} MB");
          }
  
          var ext = Path.GetExtension(input.File.FileName)?.ToLowerInvariant();
          if (ext != ".xlsx")
          {
              throw new UserFriendlyException("仅支持 .xlsx 格式的 Excel 文件");
          }
  
          await using var uploadStream = input.File.OpenReadStream();
          var parseErrors = new List<LocationBatchImportErrorDto>();
          var rows = LocationBatchExcelHelper.ParseImportWorkbook(
              uploadStream,
              opt.MaxImportRows <= 0 ? 5000 : opt.MaxImportRows,
              out var headerErrors);
          parseErrors.AddRange(headerErrors);
  
          var result = new LocationBatchImportResultDto();
          if (rows.Count == 0 && parseErrors.Count > 0)
          {
              result.Errors = parseErrors;
              result.FailCount = parseErrors.Count;
              return result;
          }
  
          foreach (var (rowNum, vo) in rows)
          {
              try
              {
                  await CreateAsync(vo);
                  result.SuccessCount++;
              }
              catch (UserFriendlyException ex)
              {
                  result.FailCount++;
                  result.Errors.Add(new LocationBatchImportErrorDto
                  {
                      RowNumber = rowNum,
                      LocationCode = vo.LocationCode,
                      Message = ex.Message
                  });
              }
          }
  
          result.Errors.InsertRange(0, parseErrors);
          return result;
      }
  
      /// <inheritdoc />
      public async Task<LocationBulkUpdateResultDto> UpdateLocationsBulkAsync([FromBody] LocationBulkUpdateInputVo input)
      {
          if (input?.Items is null || input.Items.Count == 0)
          {
              throw new UserFriendlyException("请至少提交一条编辑数据(items 不能为空)");
          }
  
          var opt = _batchImportOptions.Value;
          var maxItems = opt.MaxBulkUpdateItems <= 0 ? 500 : opt.MaxBulkUpdateItems;
          if (input.Items.Count > maxItems)
          {
              throw new UserFriendlyException($"单次批量编辑最多允许 {maxItems} 条,请分批提交");
          }
  
          var effectiveCount = input.Items.Count(static x => x is not null && x.Id != Guid.Empty);
          if (effectiveCount == 0)
          {
              throw new UserFriendlyException("没有有效的门店 Id(请为待保存行填写 id,空行请使用 id 为空 GUID 或从列表中移除)");
          }
  
          var result = new LocationBulkUpdateResultDto();
          for (var i = 0; i < input.Items.Count; i++)
          {
              var item = input.Items[i];
              if (item is null || item.Id == Guid.Empty)
              {
                  continue;
              }
  
              try
              {
                  await UpdateAsync(item.Id, item);
                  result.SuccessCount++;
              }
              catch (UserFriendlyException ex)
              {
                  result.FailCount++;
                  result.Errors.Add(new LocationBulkUpdateErrorDto
                  {
                      RowNumber = i + 1,
                      Id = item.Id,
                      Message = ex.Message
                  });
              }
          }
  
          return result;
      }
  
07d5dea2   李曜臣   5-18代码优化
334
      private async Task<ISugarQueryable<LocationAggregateRoot>> BuildFilteredQueryAsync(LocationGetListInputVo input)
a7684ddb   李曜臣   批量导入导出,批量编辑
335
      {
07d5dea2   李曜臣   5-18代码优化
336
337
          var scope = await LocationRegionScopeHelper.ResolveLocationListScopeAsync(CurrentUser, _dbContext);
  
a7684ddb   李曜臣   批量导入导出,批量编辑
338
339
340
341
          var keyword = input.Keyword?.Trim();
          var partner = input.Partner?.Trim();
          var groupName = input.GroupName?.Trim();
  
07d5dea2   李曜臣   5-18代码优化
342
343
344
345
346
347
          var query = _locationRepository._DbQueryable
              .Where(x => x.IsDeleted == false);
  
          query = LocationRegionScopeHelper.ApplyLocationListScope(query, scope);
  
          return query
a7684ddb   李曜臣   批量导入导出,批量编辑
348
349
350
351
352
353
354
355
356
357
358
359
360
              .WhereIF(!string.IsNullOrEmpty(partner), x => x.Partner == partner)
              .WhereIF(!string.IsNullOrEmpty(groupName), x => x.GroupName == groupName)
              .WhereIF(input.State is not null, x => x.State == input.State)
              .WhereIF(!string.IsNullOrEmpty(keyword),
                  x =>
                      x.LocationCode.Contains(keyword!) ||
                      x.LocationName.Contains(keyword!) ||
                      (x.Street != null && x.Street.Contains(keyword!)) ||
                      (x.City != null && x.City.Contains(keyword!)) ||
                      (x.StateCode != null && x.StateCode.Contains(keyword!)) ||
                      (x.Country != null && x.Country.Contains(keyword!)) ||
                      (x.ZipCode != null && x.ZipCode.Contains(keyword!)) ||
                      (x.Phone != null && x.Phone.Contains(keyword!)) ||
10fd1324   李曜臣   5-17接口优化
361
                      (x.Email != null && x.Email.Contains(keyword!)) ||
07d5dea2   李曜臣   5-18代码优化
362
                      (x.OperatingHours != null && x.OperatingHours.Contains(keyword!)));
a7684ddb   李曜臣   批量导入导出,批量编辑
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
      }
  
      private static LocationGetListOutputDto ToListDto(LocationAggregateRoot x) =>
          new()
          {
              Id = x.Id,
              Partner = x.Partner,
              GroupName = x.GroupName,
              LocationCode = x.LocationCode,
              LocationName = x.LocationName,
              Street = x.Street,
              City = x.City,
              StateCode = x.StateCode,
              Country = x.Country,
              ZipCode = x.ZipCode,
              Phone = x.Phone,
              Email = x.Email,
              Latitude = x.Latitude,
              Longitude = x.Longitude,
10fd1324   李曜臣   5-17接口优化
382
              OperatingHours = x.OperatingHours,
a7684ddb   李曜臣   批量导入导出,批量编辑
383
384
385
              State = x.State
          };
  }