Blame view

美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/GroupAppService.cs 13.2 KB
4d328ec2   李曜臣   平台端报表reports,仪表盘D...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
  using FoodLabeling.Application.Helpers;
  using FoodLabeling.Application.Contracts.Dtos.Common;
  using FoodLabeling.Application.Contracts.Dtos.Group;
  using FoodLabeling.Application.Contracts.IServices;
  using FoodLabeling.Application.Services.DbModels;
  using Microsoft.AspNetCore.Mvc;
  using QuestPDF.Fluent;
  using QuestPDF.Helpers;
  using QuestPDF.Infrastructure;
  using SqlSugar;
  using Volo.Abp;
  using Volo.Abp.Application.Services;
  using Volo.Abp.Guids;
  using Volo.Abp.Uow;
  using Yi.Framework.SqlSugarCore.Abstractions;
  
  namespace FoodLabeling.Application.Services;
  
  /// <summary>
  /// 组织(Group)管理(fl_group
  /// </summary>
  public class GroupAppService : ApplicationService, IGroupAppService
  {
      private const int ExportPdfMaxRows = 5000;
  
      private readonly ISqlSugarDbContext _dbContext;
      private readonly IGuidGenerator _guidGenerator;
  
      public GroupAppService(ISqlSugarDbContext dbContext, IGuidGenerator guidGenerator)
      {
          _dbContext = dbContext;
          _guidGenerator = guidGenerator;
      }
  
      /// <inheritdoc />
      public async Task<PagedResultWithPageDto<GroupGetListOutputDto>> GetListAsync(GroupGetListInputVo input)
      {
          RefAsync<int> total = 0;
10fd1324   李曜臣   5-17接口优化
39
          var query = await BuildGroupJoinedQueryAsync(input);
4d328ec2   李曜臣   平台端报表reports,仪表盘D...
40
41
42
43
44
          var projected = query.Select((g, p) => new GroupGetListOutputDto
          {
              Id = g.Id,
              GroupName = g.GroupName,
              PartnerId = g.PartnerId,
10fd1324   李曜臣   5-17接口优化
45
              PartnerName = string.IsNullOrWhiteSpace(p.PartnerName) ? "None" : p.PartnerName.Trim(),
4d328ec2   李曜臣   平台端报表reports,仪表盘D...
46
47
48
49
50
51
52
53
54
              State = g.State,
              CreationTime = g.CreationTime
          });
  
          var items = await projected.ToPageListAsync(input.SkipCount, input.MaxResultCount, total);
          return BuildPagedResult(input.SkipCount, input.MaxResultCount, total, items);
      }
  
      /// <inheritdoc />
10fd1324   李曜臣   5-17接口优化
55
      public async Task<GroupGetOutputDto> GetAsync(Guid id)
4d328ec2   李曜臣   平台端报表reports,仪表盘D...
56
      {
10fd1324   李曜臣   5-17接口优化
57
          if (id == Guid.Empty)
4d328ec2   李曜臣   平台端报表reports,仪表盘D...
58
          {
10fd1324   李曜臣   5-17接口优化
59
              throw new UserFriendlyException("Group id is required.");
4d328ec2   李曜臣   平台端报表reports,仪表盘D...
60
61
          }
  
10fd1324   李曜臣   5-17接口优化
62
          var groupId = id.ToString();
4d328ec2   李曜臣   平台端报表reports,仪表盘D...
63
64
65
66
          var entity = await _dbContext.SqlSugarClient.Queryable<FlGroupDbEntity>()
              .FirstAsync(x => !x.IsDeleted && x.Id == groupId);
          if (entity is null)
          {
10fd1324   李曜臣   5-17接口优化
67
              throw new UserFriendlyException("Group not found.");
4d328ec2   李曜臣   平台端报表reports,仪表盘D...
68
69
70
71
72
73
74
75
76
77
78
79
80
          }
  
          var partnerName = await ResolvePartnerNameAsync(entity.PartnerId);
          return MapDetail(entity, partnerName);
      }
  
      /// <inheritdoc />
      [UnitOfWork]
      public async Task<GroupGetOutputDto> CreateAsync(GroupCreateInputVo input)
      {
          var name = input.GroupName?.Trim();
          if (string.IsNullOrWhiteSpace(name))
          {
10fd1324   李曜臣   5-17接口优化
81
              throw new UserFriendlyException("Region name is required.");
4d328ec2   李曜臣   平台端报表reports,仪表盘D...
82
83
84
85
86
          }
  
          var partnerId = input.PartnerId?.Trim();
          if (string.IsNullOrWhiteSpace(partnerId))
          {
10fd1324   李曜臣   5-17接口优化
87
              throw new UserFriendlyException("Parent company is required.");
4d328ec2   李曜臣   平台端报表reports,仪表盘D...
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
          }
  
          await EnsurePartnerExistsAsync(partnerId);
  
          var now = Clock.Now;
          var entity = new FlGroupDbEntity
          {
              Id = _guidGenerator.Create().ToString(),
              IsDeleted = false,
              GroupName = name,
              PartnerId = partnerId,
              State = input.State,
              CreationTime = now,
              CreatorId = CurrentUser?.Id?.ToString(),
              LastModificationTime = now,
              LastModifierId = CurrentUser?.Id?.ToString()
          };
  
          await _dbContext.SqlSugarClient.Insertable(entity).ExecuteCommandAsync();
10fd1324   李曜臣   5-17接口优化
107
          return await GetAsync(Guid.Parse(entity.Id));
4d328ec2   李曜臣   平台端报表reports,仪表盘D...
108
109
110
111
      }
  
      /// <inheritdoc />
      [UnitOfWork]
10fd1324   李曜臣   5-17接口优化
112
      public async Task<GroupGetOutputDto> UpdateAsync(Guid id, GroupUpdateInputVo input)
4d328ec2   李曜臣   平台端报表reports,仪表盘D...
113
      {
10fd1324   李曜臣   5-17接口优化
114
          if (id == Guid.Empty)
4d328ec2   李曜臣   平台端报表reports,仪表盘D...
115
          {
10fd1324   李曜臣   5-17接口优化
116
              throw new UserFriendlyException("Group id is required.");
4d328ec2   李曜臣   平台端报表reports,仪表盘D...
117
118
          }
  
10fd1324   李曜臣   5-17接口优化
119
          var groupId = id.ToString();
4d328ec2   李曜臣   平台端报表reports,仪表盘D...
120
121
122
123
          var entity = await _dbContext.SqlSugarClient.Queryable<FlGroupDbEntity>()
              .FirstAsync(x => !x.IsDeleted && x.Id == groupId);
          if (entity is null)
          {
10fd1324   李曜臣   5-17接口优化
124
              throw new UserFriendlyException("Group not found.");
4d328ec2   李曜臣   平台端报表reports,仪表盘D...
125
126
127
128
129
          }
  
          var name = input.GroupName?.Trim();
          if (string.IsNullOrWhiteSpace(name))
          {
10fd1324   李曜臣   5-17接口优化
130
              throw new UserFriendlyException("Region name is required.");
4d328ec2   李曜臣   平台端报表reports,仪表盘D...
131
132
133
134
135
          }
  
          var partnerId = input.PartnerId?.Trim();
          if (string.IsNullOrWhiteSpace(partnerId))
          {
10fd1324   李曜臣   5-17接口优化
136
              throw new UserFriendlyException("Parent company is required.");
4d328ec2   李曜臣   平台端报表reports,仪表盘D...
137
138
139
140
141
142
143
144
145
146
147
          }
  
          await EnsurePartnerExistsAsync(partnerId);
  
          entity.GroupName = name;
          entity.PartnerId = partnerId;
          entity.State = input.State;
          entity.LastModificationTime = Clock.Now;
          entity.LastModifierId = CurrentUser?.Id?.ToString();
  
          await _dbContext.SqlSugarClient.Updateable(entity).ExecuteCommandAsync();
10fd1324   李曜臣   5-17接口优化
148
          return await GetAsync(id);
4d328ec2   李曜臣   平台端报表reports,仪表盘D...
149
150
151
152
      }
  
      /// <inheritdoc />
      [UnitOfWork]
10fd1324   李曜臣   5-17接口优化
153
      public async Task DeleteAsync(Guid id)
4d328ec2   李曜臣   平台端报表reports,仪表盘D...
154
      {
10fd1324   李曜臣   5-17接口优化
155
          if (id == Guid.Empty)
4d328ec2   李曜臣   平台端报表reports,仪表盘D...
156
          {
10fd1324   李曜臣   5-17接口优化
157
              throw new UserFriendlyException("Group id is required.");
4d328ec2   李曜臣   平台端报表reports,仪表盘D...
158
159
          }
  
10fd1324   李曜臣   5-17接口优化
160
          var groupId = id.ToString();
4d328ec2   李曜臣   平台端报表reports,仪表盘D...
161
162
163
164
          var entity = await _dbContext.SqlSugarClient.Queryable<FlGroupDbEntity>()
              .FirstAsync(x => !x.IsDeleted && x.Id == groupId);
          if (entity is null)
          {
10fd1324   李曜臣   5-17接口优化
165
              throw new UserFriendlyException("Group not found.");
4d328ec2   李曜臣   平台端报表reports,仪表盘D...
166
167
168
169
170
171
172
173
174
          }
  
          entity.IsDeleted = true;
          entity.LastModificationTime = Clock.Now;
          entity.LastModifierId = CurrentUser?.Id?.ToString();
          await _dbContext.SqlSugarClient.Updateable(entity).ExecuteCommandAsync();
      }
  
      /// <inheritdoc />
10fd1324   李曜臣   5-17接口优化
175
176
      [HttpGet]
      public async Task<IActionResult> ExportPdfAsync([FromQuery] GroupGetListInputVo input)
4d328ec2   李曜臣   平台端报表reports,仪表盘D...
177
178
179
      {
          QuestPDF.Settings.License = LicenseType.Community;
  
10fd1324   李曜臣   5-17接口优化
180
          var exportBase = await BuildGroupJoinedQueryAsync(input);
4d328ec2   李曜臣   平台端报表reports,仪表盘D...
181
182
183
          var count = await exportBase.CountAsync();
          if (count > ExportPdfMaxRows)
          {
10fd1324   李曜臣   5-17接口优化
184
185
              throw new UserFriendlyException(
                  $"Export exceeds the maximum of {ExportPdfMaxRows} rows. Narrow your filters and try again.");
4d328ec2   李曜臣   平台端报表reports,仪表盘D...
186
187
          }
  
10fd1324   李曜臣   5-17接口优化
188
          var rows = await (await BuildGroupJoinedQueryAsync(input))
4d328ec2   李曜臣   平台端报表reports,仪表盘D...
189
190
191
192
193
              .Select((g, p) => new GroupGetListOutputDto
              {
                  Id = g.Id,
                  GroupName = g.GroupName,
                  PartnerId = g.PartnerId,
10fd1324   李曜臣   5-17接口优化
194
                  PartnerName = string.IsNullOrWhiteSpace(p.PartnerName) ? "None" : p.PartnerName.Trim(),
4d328ec2   李曜臣   平台端报表reports,仪表盘D...
195
196
197
198
199
200
                  State = g.State,
                  CreationTime = g.CreationTime
              })
              .Take(ExportPdfMaxRows)
              .ToListAsync();
  
a7684ddb   李曜臣   批量导入导出,批量编辑
201
          var fileName = $"regions_{Clock.Now:yyyy-MM-dd_HH-mm-ss}.pdf";
4d328ec2   李曜臣   平台端报表reports,仪表盘D...
202
203
204
205
206
207
          var document = Document.Create(container =>
          {
              container.Page(page =>
              {
                  page.Margin(28);
                  page.DefaultTextStyle(x => x.FontSize(10));
a7684ddb   李曜臣   批量导入导出,批量编辑
208
                  page.Header().Text("Regions").SemiBold().FontSize(18);
4d328ec2   李曜臣   平台端报表reports,仪表盘D...
209
210
211
212
213
214
215
216
217
218
219
220
221
                  page.Content().PaddingTop(12).Table(table =>
                  {
                      table.ColumnsDefinition(c =>
                      {
                          c.RelativeColumn(2.2f);
                          c.RelativeColumn(2.4f);
                          c.RelativeColumn(1f);
                          c.RelativeColumn(1.6f);
                      });
  
                      static IContainer CellHeader(IContainer c) =>
                          c.Background(Colors.Grey.Lighten3).Padding(6).DefaultTextStyle(x => x.SemiBold());
  
a7684ddb   李曜臣   批量导入导出,批量编辑
222
223
                      table.Cell().Element(CellHeader).Text("Region Name");
                      table.Cell().Element(CellHeader).Text("Parent company");
4d328ec2   李曜臣   平台端报表reports,仪表盘D...
224
225
226
227
228
229
230
231
232
                      table.Cell().Element(CellHeader).Text("Status");
                      table.Cell().Element(CellHeader).Text("Created");
  
                      foreach (var e in rows)
                      {
                          var status = e.State ? "active" : "inactive";
                          table.Cell().BorderBottom(0.5f).BorderColor(Colors.Grey.Lighten2).Padding(5)
                              .Text(e.GroupName ?? string.Empty);
                          table.Cell().BorderBottom(0.5f).BorderColor(Colors.Grey.Lighten2).Padding(5)
10fd1324   李曜臣   5-17接口优化
233
                              .Text(string.IsNullOrWhiteSpace(e.PartnerName) ? "None" : e.PartnerName);
4d328ec2   李曜臣   平台端报表reports,仪表盘D...
234
235
236
237
238
239
240
241
242
243
244
245
246
247
                          table.Cell().BorderBottom(0.5f).BorderColor(Colors.Grey.Lighten2).Padding(5).Text(status);
                          table.Cell().BorderBottom(0.5f).BorderColor(Colors.Grey.Lighten2).Padding(5)
                              .Text(e.CreationTime.ToString("yyyy-MM-dd HH:mm"));
                      }
                  });
              });
          });
  
          var stream = new MemoryStream();
          document.GeneratePdf(stream);
          stream.Position = 0;
          return new FileStreamResult(stream, "application/pdf") { FileDownloadName = fileName };
      }
  
10fd1324   李曜臣   5-17接口优化
248
249
      private async Task<ISugarQueryable<FlGroupDbEntity, FlPartnerDbEntity>> BuildGroupJoinedQueryAsync(
          GroupGetListInputVo input)
4d328ec2   李曜臣   平台端报表reports,仪表盘D...
250
      {
10fd1324   李曜臣   5-17接口优化
251
252
          var scope = await PartnerScopeHelper.ResolveGroupScopeAsync(CurrentUser, _dbContext);
  
4d328ec2   李曜臣   平台端报表reports,仪表盘D...
253
254
255
256
257
          var keyword = input.Keyword?.Trim();
          var partnerId = input.PartnerId?.Trim();
  
          var query = _dbContext.SqlSugarClient.Queryable<FlGroupDbEntity>()
              .LeftJoin<FlPartnerDbEntity>((g, p) => g.PartnerId == p.Id && !p.IsDeleted)
10fd1324   李曜臣   5-17接口优化
258
259
260
261
262
              .Where((g, p) => !g.IsDeleted);
  
          query = PartnerScopeHelper.ApplyGroupScope(query, scope);
  
          query = query
4d328ec2   李曜臣   平台端报表reports,仪表盘D...
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
              .WhereIF(input.State != null, (g, p) => g.State == input.State)
              .WhereIF(!string.IsNullOrWhiteSpace(partnerId), (g, p) => g.PartnerId == partnerId)
              .WhereIF(!string.IsNullOrWhiteSpace(keyword),
                  (g, p) => g.GroupName.Contains(keyword!) ||
                            (p.PartnerName != null && p.PartnerName.Contains(keyword!)));
  
          if (!string.IsNullOrWhiteSpace(input.Sorting))
          {
              var sorting = input.Sorting.Trim();
              if (sorting.Equals("GroupName desc", StringComparison.OrdinalIgnoreCase))
              {
                  query = query.OrderByDescending((g, p) => g.GroupName);
              }
              else if (sorting.Equals("GroupName asc", StringComparison.OrdinalIgnoreCase))
              {
                  query = query.OrderBy((g, p) => g.GroupName);
              }
              else if (sorting.Equals("CreationTime desc", StringComparison.OrdinalIgnoreCase))
              {
                  query = query.OrderByDescending((g, p) => g.CreationTime);
              }
              else if (sorting.Equals("CreationTime asc", StringComparison.OrdinalIgnoreCase))
              {
                  query = query.OrderBy((g, p) => g.CreationTime);
              }
              else if (sorting.Equals("State desc", StringComparison.OrdinalIgnoreCase))
              {
                  query = query.OrderByDescending((g, p) => g.State);
              }
              else if (sorting.Equals("State asc", StringComparison.OrdinalIgnoreCase))
              {
                  query = query.OrderBy((g, p) => g.State);
              }
              else if (sorting.Equals("PartnerName desc", StringComparison.OrdinalIgnoreCase))
              {
                  query = query.OrderByDescending((g, p) => p.PartnerName);
              }
              else if (sorting.Equals("PartnerName asc", StringComparison.OrdinalIgnoreCase))
              {
                  query = query.OrderBy((g, p) => p.PartnerName);
              }
              else
              {
                  query = query.OrderByDescending((g, p) => g.CreationTime);
              }
          }
          else
          {
              query = query.OrderByDescending((g, p) => g.CreationTime);
          }
  
          return query;
      }
  
      private async Task EnsurePartnerExistsAsync(string partnerId)
      {
          var ok = await _dbContext.SqlSugarClient.Queryable<FlPartnerDbEntity>()
              .AnyAsync(x => !x.IsDeleted && x.Id == partnerId);
          if (!ok)
          {
10fd1324   李曜臣   5-17接口优化
323
              throw new UserFriendlyException("The selected company does not exist or has been removed.");
4d328ec2   李曜臣   平台端报表reports,仪表盘D...
324
325
326
327
328
329
330
331
332
          }
      }
  
      private async Task<string> ResolvePartnerNameAsync(string partnerId)
      {
          var p = await _dbContext.SqlSugarClient.Queryable<FlPartnerDbEntity>()
              .FirstAsync(x => !x.IsDeleted && x.Id == partnerId);
          if (p is null || string.IsNullOrWhiteSpace(p.PartnerName))
          {
10fd1324   李曜臣   5-17接口优化
333
              return "None";
4d328ec2   李曜臣   平台端报表reports,仪表盘D...
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
          }
  
          return p.PartnerName.Trim();
      }
  
      private static GroupGetOutputDto MapDetail(FlGroupDbEntity x, string partnerName) => new()
      {
          Id = x.Id,
          GroupName = x.GroupName,
          PartnerId = x.PartnerId,
          PartnerName = partnerName,
          State = x.State,
          CreationTime = x.CreationTime,
          LastModificationTime = x.LastModificationTime
      };
  
      private static PagedResultWithPageDto<T> BuildPagedResult<T>(int skipCount, int maxResultCount, int total,
          List<T> items)
      {
          var pageSize = maxResultCount <= 0 ? items.Count : maxResultCount;
          var pageIndex = pageSize <= 0 ? 1 : PagedQueryConvention.PageIndexFromSkipCount(skipCount);
          var totalPages = pageSize <= 0 ? 0 : (int)Math.Ceiling(total / (double)pageSize);
          return new PagedResultWithPageDto<T>
          {
              PageIndex = pageIndex,
              PageSize = pageSize,
              TotalCount = total,
              TotalPages = totalPages,
              Items = items
          };
      }
  }