PartnerAppService.cs
12.1 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
using FoodLabeling.Application.Helpers;
using FoodLabeling.Application.Contracts.Dtos.Common;
using FoodLabeling.Application.Contracts.Dtos.Partner;
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>
/// 合作伙伴管理(fl_partner)
/// </summary>
public class PartnerAppService : ApplicationService, IPartnerAppService
{
private const int ExportPdfMaxRows = 5000;
private readonly ISqlSugarDbContext _dbContext;
private readonly IGuidGenerator _guidGenerator;
public PartnerAppService(ISqlSugarDbContext dbContext, IGuidGenerator guidGenerator)
{
_dbContext = dbContext;
_guidGenerator = guidGenerator;
}
/// <inheritdoc />
public async Task<PagedResultWithPageDto<PartnerGetListOutputDto>> GetListAsync(PartnerGetListInputVo input)
{
RefAsync<int> total = 0;
var query = BuildPartnerListQuery(input);
var entities = await query.ToPageListAsync(input.SkipCount, input.MaxResultCount, total);
var items = entities.Select(MapListItem).ToList();
return BuildPagedResult(input.SkipCount, input.MaxResultCount, total, items);
}
/// <inheritdoc />
public async Task<PartnerGetOutputDto> GetAsync(string id)
{
var partnerId = id?.Trim();
if (string.IsNullOrWhiteSpace(partnerId))
{
throw new UserFriendlyException("合作伙伴Id不能为空");
}
var entity = await _dbContext.SqlSugarClient.Queryable<FlPartnerDbEntity>()
.FirstAsync(x => !x.IsDeleted && x.Id == partnerId);
if (entity is null)
{
throw new UserFriendlyException("合作伙伴不存在");
}
return MapDetail(entity);
}
/// <inheritdoc />
[UnitOfWork]
public async Task<PartnerGetOutputDto> CreateAsync(PartnerCreateInputVo input)
{
var name = input.PartnerName?.Trim();
if (string.IsNullOrWhiteSpace(name))
{
throw new UserFriendlyException("合作伙伴名称不能为空");
}
var email = input.ContactEmail?.Trim();
if (!string.IsNullOrWhiteSpace(email) && !IsPlausibleEmail(email))
{
throw new UserFriendlyException("联系邮箱格式不正确");
}
var now = Clock.Now;
var entity = new FlPartnerDbEntity
{
Id = _guidGenerator.Create().ToString(),
IsDeleted = false,
PartnerName = name,
ContactEmail = string.IsNullOrWhiteSpace(email) ? null : email,
PhoneNumber = string.IsNullOrWhiteSpace(input.PhoneNumber) ? null : input.PhoneNumber.Trim(),
State = input.State,
CreationTime = now,
CreatorId = CurrentUser?.Id?.ToString(),
LastModificationTime = now,
LastModifierId = CurrentUser?.Id?.ToString()
};
await _dbContext.SqlSugarClient.Insertable(entity).ExecuteCommandAsync();
return await GetAsync(entity.Id);
}
/// <inheritdoc />
[UnitOfWork]
public async Task<PartnerGetOutputDto> UpdateAsync(string id, PartnerUpdateInputVo input)
{
var partnerId = id?.Trim();
if (string.IsNullOrWhiteSpace(partnerId))
{
throw new UserFriendlyException("合作伙伴Id不能为空");
}
var entity = await _dbContext.SqlSugarClient.Queryable<FlPartnerDbEntity>()
.FirstAsync(x => !x.IsDeleted && x.Id == partnerId);
if (entity is null)
{
throw new UserFriendlyException("合作伙伴不存在");
}
var name = input.PartnerName?.Trim();
if (string.IsNullOrWhiteSpace(name))
{
throw new UserFriendlyException("合作伙伴名称不能为空");
}
var email = input.ContactEmail?.Trim();
if (!string.IsNullOrWhiteSpace(email) && !IsPlausibleEmail(email))
{
throw new UserFriendlyException("联系邮箱格式不正确");
}
entity.PartnerName = name;
entity.ContactEmail = string.IsNullOrWhiteSpace(email) ? null : email;
entity.PhoneNumber = string.IsNullOrWhiteSpace(input.PhoneNumber) ? null : input.PhoneNumber.Trim();
entity.State = input.State;
entity.LastModificationTime = Clock.Now;
entity.LastModifierId = CurrentUser?.Id?.ToString();
await _dbContext.SqlSugarClient.Updateable(entity).ExecuteCommandAsync();
return await GetAsync(partnerId);
}
/// <inheritdoc />
[UnitOfWork]
public async Task DeleteAsync(string id)
{
var partnerId = id?.Trim();
if (string.IsNullOrWhiteSpace(partnerId))
{
throw new UserFriendlyException("合作伙伴Id不能为空");
}
var entity = await _dbContext.SqlSugarClient.Queryable<FlPartnerDbEntity>()
.FirstAsync(x => !x.IsDeleted && x.Id == partnerId);
if (entity is null)
{
throw new UserFriendlyException("合作伙伴不存在");
}
entity.IsDeleted = true;
entity.LastModificationTime = Clock.Now;
entity.LastModifierId = CurrentUser?.Id?.ToString();
await _dbContext.SqlSugarClient.Updateable(entity).ExecuteCommandAsync();
}
/// <inheritdoc />
public async Task<IActionResult> ExportPdfAsync(PartnerGetListInputVo input)
{
QuestPDF.Settings.License = LicenseType.Community;
var count = await BuildPartnerListQuery(input).CountAsync();
var query = BuildPartnerListQuery(input);
if (count > ExportPdfMaxRows)
{
throw new UserFriendlyException($"导出数据超过上限 {ExportPdfMaxRows} 条,请缩小筛选范围");
}
var rows = await query.Take(ExportPdfMaxRows).ToListAsync();
var fileName = $"companies_{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("Companies").SemiBold().FontSize(18);
page.Content().PaddingTop(12).Table(table =>
{
table.ColumnsDefinition(c =>
{
c.RelativeColumn(2.2f);
c.RelativeColumn(2.4f);
c.RelativeColumn(1.8f);
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("Company");
table.Cell().Element(CellHeader).Text("Contact");
table.Cell().Element(CellHeader).Text("Phone");
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.PartnerName ?? string.Empty);
table.Cell().BorderBottom(0.5f).BorderColor(Colors.Grey.Lighten2).Padding(5)
.Text(string.IsNullOrWhiteSpace(e.ContactEmail) ? "无" : e.ContactEmail!);
table.Cell().BorderBottom(0.5f).BorderColor(Colors.Grey.Lighten2).Padding(5)
.Text(string.IsNullOrWhiteSpace(e.PhoneNumber) ? "无" : e.PhoneNumber!);
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 ISugarQueryable<FlPartnerDbEntity> BuildPartnerListQuery(PartnerGetListInputVo input)
{
var keyword = input.Keyword?.Trim();
var query = _dbContext.SqlSugarClient.Queryable<FlPartnerDbEntity>()
.Where(x => !x.IsDeleted)
.WhereIF(input.State != null, x => x.State == input.State)
.WhereIF(!string.IsNullOrWhiteSpace(keyword),
x => x.PartnerName.Contains(keyword!) ||
(x.ContactEmail != null && x.ContactEmail.Contains(keyword!)) ||
(x.PhoneNumber != null && x.PhoneNumber.Contains(keyword!)));
if (!string.IsNullOrWhiteSpace(input.Sorting))
{
var sorting = input.Sorting.Trim();
if (sorting.Equals("PartnerName desc", StringComparison.OrdinalIgnoreCase))
{
query = query.OrderByDescending(x => x.PartnerName);
}
else if (sorting.Equals("PartnerName asc", StringComparison.OrdinalIgnoreCase))
{
query = query.OrderBy(x => x.PartnerName);
}
else if (sorting.Equals("CreationTime desc", StringComparison.OrdinalIgnoreCase))
{
query = query.OrderByDescending(x => x.CreationTime);
}
else if (sorting.Equals("CreationTime asc", StringComparison.OrdinalIgnoreCase))
{
query = query.OrderBy(x => x.CreationTime);
}
else if (sorting.Equals("State desc", StringComparison.OrdinalIgnoreCase))
{
query = query.OrderByDescending(x => x.State);
}
else if (sorting.Equals("State asc", StringComparison.OrdinalIgnoreCase))
{
query = query.OrderBy(x => x.State);
}
else
{
query = query.OrderByDescending(x => x.CreationTime);
}
}
else
{
query = query.OrderByDescending(x => x.CreationTime);
}
return query;
}
private static PartnerGetListOutputDto MapListItem(FlPartnerDbEntity x) => new()
{
Id = x.Id,
PartnerName = x.PartnerName,
ContactEmail = x.ContactEmail,
PhoneNumber = x.PhoneNumber,
State = x.State,
CreationTime = x.CreationTime
};
private static PartnerGetOutputDto MapDetail(FlPartnerDbEntity x) => new()
{
Id = x.Id,
PartnerName = x.PartnerName,
ContactEmail = x.ContactEmail,
PhoneNumber = x.PhoneNumber,
State = x.State,
CreationTime = x.CreationTime,
LastModificationTime = x.LastModificationTime
};
private static bool IsPlausibleEmail(string email)
{
if (email.Length > 256)
{
return false;
}
var at = email.IndexOf('@');
return at > 0 && at < email.Length - 1 && email.IndexOf('@', at + 1) < 0;
}
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
};
}
}