GroupAppService.cs
13.2 KB
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
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
206
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
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
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;
var query = await BuildGroupJoinedQueryAsync(input);
var projected = query.Select((g, p) => new GroupGetListOutputDto
{
Id = g.Id,
GroupName = g.GroupName,
PartnerId = g.PartnerId,
PartnerName = string.IsNullOrWhiteSpace(p.PartnerName) ? "None" : p.PartnerName.Trim(),
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 />
public async Task<GroupGetOutputDto> GetAsync(Guid id)
{
if (id == Guid.Empty)
{
throw new UserFriendlyException("Group id is required.");
}
var groupId = id.ToString();
var entity = await _dbContext.SqlSugarClient.Queryable<FlGroupDbEntity>()
.FirstAsync(x => !x.IsDeleted && x.Id == groupId);
if (entity is null)
{
throw new UserFriendlyException("Group not found.");
}
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))
{
throw new UserFriendlyException("Region name is required.");
}
var partnerId = input.PartnerId?.Trim();
if (string.IsNullOrWhiteSpace(partnerId))
{
throw new UserFriendlyException("Parent company is required.");
}
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();
return await GetAsync(Guid.Parse(entity.Id));
}
/// <inheritdoc />
[UnitOfWork]
public async Task<GroupGetOutputDto> UpdateAsync(Guid id, GroupUpdateInputVo input)
{
if (id == Guid.Empty)
{
throw new UserFriendlyException("Group id is required.");
}
var groupId = id.ToString();
var entity = await _dbContext.SqlSugarClient.Queryable<FlGroupDbEntity>()
.FirstAsync(x => !x.IsDeleted && x.Id == groupId);
if (entity is null)
{
throw new UserFriendlyException("Group not found.");
}
var name = input.GroupName?.Trim();
if (string.IsNullOrWhiteSpace(name))
{
throw new UserFriendlyException("Region name is required.");
}
var partnerId = input.PartnerId?.Trim();
if (string.IsNullOrWhiteSpace(partnerId))
{
throw new UserFriendlyException("Parent company is required.");
}
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();
return await GetAsync(id);
}
/// <inheritdoc />
[UnitOfWork]
public async Task DeleteAsync(Guid id)
{
if (id == Guid.Empty)
{
throw new UserFriendlyException("Group id is required.");
}
var groupId = id.ToString();
var entity = await _dbContext.SqlSugarClient.Queryable<FlGroupDbEntity>()
.FirstAsync(x => !x.IsDeleted && x.Id == groupId);
if (entity is null)
{
throw new UserFriendlyException("Group not found.");
}
entity.IsDeleted = true;
entity.LastModificationTime = Clock.Now;
entity.LastModifierId = CurrentUser?.Id?.ToString();
await _dbContext.SqlSugarClient.Updateable(entity).ExecuteCommandAsync();
}
/// <inheritdoc />
[HttpGet]
public async Task<IActionResult> ExportPdfAsync([FromQuery] GroupGetListInputVo input)
{
QuestPDF.Settings.License = LicenseType.Community;
var exportBase = await BuildGroupJoinedQueryAsync(input);
var count = await exportBase.CountAsync();
if (count > ExportPdfMaxRows)
{
throw new UserFriendlyException(
$"Export exceeds the maximum of {ExportPdfMaxRows} rows. Narrow your filters and try again.");
}
var rows = await (await BuildGroupJoinedQueryAsync(input))
.Select((g, p) => new GroupGetListOutputDto
{
Id = g.Id,
GroupName = g.GroupName,
PartnerId = g.PartnerId,
PartnerName = string.IsNullOrWhiteSpace(p.PartnerName) ? "None" : p.PartnerName.Trim(),
State = g.State,
CreationTime = g.CreationTime
})
.Take(ExportPdfMaxRows)
.ToListAsync();
var fileName = $"regions_{Clock.Now:yyyy-MM-dd_HH-mm-ss}.pdf";
var document = Document.Create(container =>
{
container.Page(page =>
{
page.Margin(28);
page.DefaultTextStyle(x => x.FontSize(10));
page.Header().Text("Regions").SemiBold().FontSize(18);
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());
table.Cell().Element(CellHeader).Text("Region Name");
table.Cell().Element(CellHeader).Text("Parent company");
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)
.Text(string.IsNullOrWhiteSpace(e.PartnerName) ? "None" : e.PartnerName);
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 };
}
private async Task<ISugarQueryable<FlGroupDbEntity, FlPartnerDbEntity>> BuildGroupJoinedQueryAsync(
GroupGetListInputVo input)
{
var scope = await PartnerScopeHelper.ResolveGroupScopeAsync(CurrentUser, _dbContext);
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)
.Where((g, p) => !g.IsDeleted);
query = PartnerScopeHelper.ApplyGroupScope(query, scope);
query = query
.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)
{
throw new UserFriendlyException("The selected company does not exist or has been removed.");
}
}
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))
{
return "None";
}
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
};
}
}