DemoService.cs
23.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
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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
using NCC.Common.Core.Manager;
using NCC.Common.Extension;
using NCC.Common.FileManage;
using NCC.Common.Filter;
using NCC.Common.Helper;
using NCC.Dependency;
using NCC.DynamicApiController;
using NCC.Extend.Entitys.common_extend;
using NCC.Extend.Entitys.Dto.Order;
using NCC.Extend.Entitys.Model;
using NCC.LinqBuilder;
using NCC.System.Entitys.Permission;
using NCC.System.Interfaces.Permission;
using NCC.System.Interfaces.System;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using SqlSugar.IOC;
using System;
using System.Collections.Generic;
using System.Data;
using System.Threading.Tasks;
using Yitter.IdGenerator;
using NCC.Code;
using NCC.FriendlyException;
using NCC.Common.Enum;
using NCC.Extend.Entitys.Dto;
using NCC.Common.Extensions;
using NCC.Common;
using System.Linq.Expressions;
using NCC.System.Interfaces.Common;
using NCC.Extend.Entitys.Dto.Document;
using NCC.Common.Model.NPOI;
using NCC.Common.Configuration;
using NCC.DataEncryption;
using Microsoft.Extensions.Logging;
using Serilog;
using NCC.Logging;
namespace NCC.Extend
{
/// <summary>
/// 订单管理
/// 版 本:V1.20.15
/// 版 权:Wesley(https://www.NCCsoft.com)
/// 作 者:NCC开发平台组
/// 日 期:2022-03-16
/// </summary>
[ApiDescriptionSettings(Tag = "演示", Name = "Demo", Order = 200)]
[Route("api/extend/[controller]")]
public class DemoService : IDynamicApiController, ITransient
{
private readonly IFileService _fileService;
private readonly ISqlSugarRepository<DemoEntity> _demoRepository;
private readonly ISqlSugarRepository<OrderEntity> _orderRepository;
private readonly IUserManager _userManager; // 用户管理
private readonly IUsersService _usersService; //用户服务
private readonly IAuthorizeService _authorizeService;
private readonly ILogger<DemoService> _logger;
private readonly SqlSugarScope db;// 核心对象:拥有完整的SqlSugar全部功能
/// <summary>
/// 初始化一个<see cref="DemoService"/>类型的演示实例
/// </summary>
public DemoService(ISqlSugarRepository<DemoEntity> demoRepository,
ISqlSugarRepository<OrderEntity> orderRepository,
IFileService fileService,
IUserManager userManager, IUsersService usersService, IAuthorizeService authorizeService, ILogger<DemoService> logger)
{
_orderRepository = orderRepository;
_demoRepository = demoRepository;
db = demoRepository.Context;
_userManager = userManager;
_usersService = usersService;
_authorizeService = authorizeService;
_fileService = fileService;
_logger = logger;
}
//数据库初始化 创建表 实体类实现 DTO 映射
//依赖注入 & 直接调用 (基于接口)
//模块化 和定义标准 (暂不集成网关)
//接口 注释 swagger
//匿名接口 AllowAnonymous 私有不暴露的方法 [NonAction]
//实体转换 Mapster Adapt用法
public void Test()
{
Log.Debug("wesley Debugger;");
//Log.Information("hellow!");
//_logger.LogDebug("_wesley LogDebug");
//_logger.LogInformation("_wesley LogInformation");
//_logger.LogWarning("_wesley LogWarning");
//_logger.LogError("_wesley LogError");
}
/// <summary>
/// 一些 比较好 的溧子
/// </summary>
/// <returns></returns>
public async Task DemoYYDS()
{
//自定义配置节点信息
//var setting = App.GetConfig<AntisSoftSettingsOptions>("AntisSoftSettings", true);
#region 登录用户获取
////当前用户ID(登录信息中取)
//string cuserid = _userManager.UserId;
////获取当前用户 优先从缓存中取 泛型对象《UserInfo》
//var cuser = _userManager.GetUserInfo();
////从数据库取(无缓存)
//var cuser1 = _userManager.User;
#endregion
//基础新增 删除 修改 查询
//YitIdHelper.NextId().ToString()
#region 新增
#region 插入单个
////插入单条
//db.Insertable(new DemoEntity()
//{
// Id = "antis",
// CustomerName = "110",
// Age = 100,
// Sex = "男",
// CreatorTime = DateTime.Now,
// CreatorUserId = "1111",
// DeleteMark = 0,
// OrderDate = DateTime.Now
//}).ExecuteCommand();
//db.Insertable(new
//{
// Id = "222",
// CustomerName = "222",
// Age = 200,
// Sex = "男",
// CreatorTime = DateTime.Now,
// CreatorUserId = "1111",
// DeleteMark = 0,
// OrderDate = DateTime.Now
//}).ExecuteCommand();
#endregion
#region 批量Insert
//List<DemoEntity> demolist = new List<DemoEntity>() {
// new DemoEntity() {
// Id = "333",
// CustomerName = "333",
// Age = 200,
// Sex = "男",
// CreatorTime = DateTime.Now,
// CreatorUserId = "333",
// DeleteMark = 0,
// OrderDate = DateTime.Now
// },
// new DemoEntity() {
// Id = "4444",
// CustomerName = "444",
// Age = 200,
// Sex = "男",
// CreatorTime = DateTime.Now,
// CreatorUserId = "4444",
// DeleteMark = 0,
// OrderDate = DateTime.Now
// }};
//await db.Insertable(demolist.ToArray()).ExecuteCommandAsync();
#endregion
#endregion
#region 删除
////实体删除 需要设置主键
//db.Deleteable<DemoEntity>().Where(new DemoEntity() { Id = "666" }).ExecuteCommand();
////主键包含删除
//db.Deleteable<DemoEntity>().In(new string[] { "777", "888" }).ExecuteCommand();
////指定条件删除
//db.Deleteable<DemoEntity>().Where(it => it.Id == "333").ExecuteCommand();
//// 子查询删除
//db.Deleteable<DemoEntity>().Where(p => p.Id == SqlFunc.Subqueryable<DemoEntity>().Where(s => s.Id == p.ReId).Select(s => s.Id)).ExecuteCommand()
#endregion
#region 修改
////拿到一个信息
//var entity = await _demoRepository.FirstOrDefaultAsync(o => o.Id == "111");
////1.单个修改
//entity.CustomerName += "_new";
////直接修改(不等待)
//_demoRepository.Context.Updateable(entity).ExecuteCommand();
////指定需要修改的字段
//var isOk = await _demoRepository.Context
//.Updateable(entity)
//.IgnoreColumns(ignoreAllNullColumns: true) //按需加载 排除 null值的字段
//.CallEntityMethod(m => m.LastModify())
//.UpdateColumns(o => new { o.CustomerName, o.LastModifyTime, o.LastModifyUserId })
//.ExecuteCommandAsync();
//if (isOk < 1)
// throw NCCException.Oh(ErrorCode.COM1001);
////2.批量修改 按条件
//List<string> ids = new List<string> { "111", "222" };
//var isOk1 = await db.Updateable<DemoEntity>()
// .SetColumns(x => new DemoEntity() //指定要修改的信息
// {
// DeleteMark = 1,//删除
// DeleteTime = null,
// DeleteUserId = null
// })
// .Where(o => ids.Contains(o.Id))
// .ExecuteCommandAsync();
//if (isOk1 < 1)
// throw NCCException.Oh(ErrorCode.COM1001);
#endregion
#region 查询
//查询表的所有
//var list = db.Queryable<DemoEntity>().ToList();
//string keyword = "antis";
////条件查询 和 条件判断
//var qlist = db.Queryable<DemoEntity>()
// .Where(o => o.Id != "111")
// //动态 条件筛选
// .WhereIF(!keyword.IsNullOrEmpty(), o => o.CustomerName.Contains(keyword))
// .WhereIF(keyword.IsNullOrEmpty(), o => o.CustomerName == null || o.CustomerName != "")
// .ToList();
//分组取第一条,部分数据库支持
//var list3 = db.Queryable<DemoEntity>()
//.PartitionBy(it => new { it.Age, it.CustomerName }).Take(1).ToList();
////快速多表查询
//var list = db.Queryable<OrderEntity, UserEntity, DemoEntity>((o, u, d) => o.CreatorUserId == u.Id && u.Id == d.ReId)
// .Select((o, u, d) => new OrderInfoOutput
// {
// customerId = SqlFunc.GetSelfAndAutoFill(o.Id),
// customerName = d.CustomerName //[d].[Name] AS [CustomName]
// })
// .ToList();
////sql 语句 直接查询
//int total = 0;
//db.SqlQueryable<OrderEntity>("select * from OrderEntity").OrderBy("id asc").ToPageList(1, 2, ref total);
//简介联表查询
//var queryorder = db.Queryable<OrderEntity>()
//.LeftJoin<DemoEntity>((o, d) => o.Id == d.ReId)//多个条件用&&
//.LeftJoin<UserEntity>((o, d, u) => o.CreatorUserId == u.CreatorUserId)
//.Where((o,d1,u) => o.Id == "112233" )
//.Select(o => o)
//.ToList();
//复杂组合查询
//Case when
// SqlFunc.IF(st.Id > 1)
//.Return(st.Id)
//.ElseIF(st.Id == 1)
//.Return(st.SchoolId).End(st.Id) //等于
////Left Join 连表查询
//var oneClass = db.Queryable<OrderEntity, UserEntity, DemoEntity>((o, i, c) => new JoinQueryInfos(
//JoinType.Left, o.CreatorUserId == i.Id,
//JoinType.Left, o.Id == c.ReId
//))
//.Select((o, i, c) => new
//{
// Id = SqlFunc.GetSelfAndAutoFill(o.Id),// o.*
// CustomName = c.CustomerName //[c].[Name] AS [CustomName]
//}).ToList();
////多表联合查询 Join中Where用法
//var SearchList = db.Queryable<OrderEntity, UserEntity, DemoEntity>((o, i, c) => new JoinQueryInfos(
//JoinType.Left, o.CreatorUserId == i.Id,
//JoinType.Left, o.Id == c.ReId
//))
//.Where(o => o.CustomerName.Contains("Antis")) //只用到o这样写就行
//.Where((o, i) => i.Account.Contains("Antis")) //如果用到i需要这么写
//.Select((o, i, c) => new
//{
// Id = SqlFunc.GetSelfAndAutoFill(o.Id),// o.*
// CustomName = c.CustomerName //[c].[Name] AS [CustomName]
//}).ToList()
//两个queryable查询 把一个单 表查询和一个多表查询在进行了一次Join操作
//var query1 = db.Queryable<DemoEntity, UserEntity>((d, user) => new JoinQueryInfos(
//JoinType.Left, d.CreatorUserId == user.Id
//))
//.Where(st => st.CustomerName.Contains("antis"));
//var query2 = db.Queryable<DemoEntity>().Where(o => o.DeleteMark == 0);
//db.Queryable(query1, query2, (p1, p2) => p1.CreatorUserId == p2.CreatorUserId).Select<DemoEntity>((d1, d2) => new DemoEntity
//{
// //....赋值
//})
//.ToPagedList<DemoEntity>(1, 10); //也可分页
////1.判断是否存在
//bool exists1 = db.Queryable<DemoEntity>().Any(q => q.CustomerName == "YYDS");
//Console.WriteLine(exists1);
////2.模糊查询,含有
//List<DemoEntity> contains1 = db.Queryable<DemoEntity>()
// .Where(q => q.CustomerName.Contains("antis"))
// .ToList();
//Console.WriteLine(contains1.ToJson());
////以End王结尾
//List<DemoEntity> end1 = db.Queryable<DemoEntity>()
// .Where(q => q.CustomerName.EndsWith("End王"))
// .ToList();
//Console.WriteLine(end1.ToJson());
////3. in关键词查询
//string[] idList = new string[] { "111", "222" };
//List<DemoEntity> in1 = db.Queryable<DemoEntity>()
// .In(q => q.Id, idList)
// .ToList();
//Console.WriteLine(in1.ToJson());
//List<DemoEntity> in2 = db.Queryable<DemoEntity>()
// .Where(q => idList.Equals(q.Id))
// .ToList();
//Console.WriteLine(in2.ToJson());
////1.获取总数
//int count = db.Queryable<DemoEntity>()
// .Where(q => q.Sex == "男")
// .Count();
//Console.WriteLine("count=" + count);
////2.获取最大值
//decimal maxDegree = db.Queryable<DemoEntity>()
// .Where(q => q.Sex == "男")
// .Max(q => q.Age)
// .ObjToInt();
//Console.WriteLine("maxAge:" + maxDegree);
////3.获取最小值
//decimal minDegree = db.Queryable<DemoEntity>()
// .Where(q => q.Sex == "男")
// .Min(q => q.Age)
// .ObjToInt();
//Console.WriteLine("minAge:" + minDegree);
//var top10 = db.Queryable<DemoEntity>().Take(10).ToList();//查询前10
//获取第一个
//var getFirst = db.Queryable<DemoEntity>().First(it => it.Id == "111");//查询单条
//NoLock查询
//var getAllNoLock = db.Queryable<DemoEntity>().With(SqlWith.NoLock).ToList();//SqlServer 有效
#endregion
#region 事务的实现
try
{
db.BeginTran();
for (int i = 0; i < 10; i++)
{
var isOk = await db.Insertable(new DemoEntity
{
Age = 10 + i,
CustomerName = $"antis_{i}"
})
.CallEntityMethod(m => m.Creator())
.CallEntityMethod(m => m.LastModify())
.ExecuteCommandAsync();
if (isOk < 1)
{
db.RollbackTran();
throw NCCException.Bah($"操作失败!");
}
db.CommitTran();
}
}
catch (Exception ee)
{
db.RollbackTran();
throw NCCException.Bah($"操作失败!");
}
#endregion
#region 文件操作 上传 下载
//Uploader
//Export
#endregion
#region excel导出
//Export
#endregion
}
/// <summary>
/// 复杂逻辑 SQL结果查询分页
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public async Task<dynamic> GetTrashList([FromQuery] PageInputBase input)
{
var sidx = input.sidx.IsNullOrWhiteSpace() ? "Id" : input.sidx;
string userid = _userManager.UserId;
string strSql = $@"
select * from ( select F_Id as Id,Name,F_LastModifyTime,Size,Extension,'folder' type,F_LastModifyTime LastModifyTime from disk_document_folder where F_DeleteMark = 1 and F_CREATORUSERID = '{userid}'
union all
select F_Id as Id, Name,F_LastModifyTime,Size,Extension,'file' type,F_LastModifyTime LastModifyTime from disk_document where F_DeleteMark = 1 and F_CREATORUSERID = '{userid}'
) T ";
int total = 0; //table对象返回时得到总条数
var dt = await db.SqlQueryable<object>(strSql)
//.WhereIF(!input.keyword.IsNullOrEmpty(), m => m.Name.Contains(input.keyword))
.OrderBy(sidx + " " + input.sort)
.ToPagedListAsync<object>(input.currentPage, input.pageSize);
//如果直接使用table对象 可用下列方法实现
//.ToDataTablePageAsync(input.currentPage, input.pageSize, total);
//dt.DataTableToDicList();
var pageList = new SqlSugarPagedList<object>()
{
list = dt.list,
pagination = dt.pagination,
//获取table对象后 需要主动构建 分页信息
//pagination = new PagedModel {
// list = dt.list,
// PageIndex = input.currentPage,
// PageSize = input.pageSize,
// Total = total
//}
};
return PageResult<object>.SqlSugarPageResult(pageList);
}
/// <summary>
/// 导出合作方信息
/// </summary>
/// <param name="input">请求参数</param>
/// <returns></returns>
[HttpGet("Actions/Export")]
public async Task<dynamic> Export([FromQuery] DemoQuery input)
{
var userInfo = await _userManager.GetUserInfo();
var exportData = db.Queryable<DemoEntity>().Where(o => o.CreatorUserId == "antis").ToList();
List<ParamsModel> paramList = new List<ParamsModel>();
ExcelConfig excelconfig = new ExcelConfig();
excelconfig.FileName = "AntisSoftExport.xls";
excelconfig.HeadFont = "微软雅黑";
excelconfig.HeadPoint = 10;
excelconfig.IsAllSizeColumn = true;
excelconfig.ColumnModel = new List<ExcelColumnModel>();
excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = "CustomerName", ExcelColumn = "我的名字" });
//...列配置
var addPath = FileVariable.TemporaryFilePath + excelconfig.FileName;
ExcelExportHelper<DemoEntity>.Export(exportData, excelconfig, addPath);
var fileName = _userManager.UserId + "|" + addPath + "|xls";
var output = new
{
name = excelconfig.FileName,
url = "/api/File/Download?encryption=" + DESCEncryption.Encrypt(fileName, "NCC")
};
return output;
}
/// <summary>
/// 上传文件
/// </summary>
/// <returns></returns>
[HttpPost("Uploader")]
public async Task Uploader([FromForm] DocumentUploaderInput input)
{
long Size = input.file.Length;
var currentUser = _userManager.User;
_fileService.UploadFile("document", input.file);
//文件名(存文件名即可)
string FileName = input.file.FileName;
//获取路径 出去文件名的完整路径
string PrevPath = _fileService.GetPathByType("document");
//完整路径
string path = PrevPath + FileName;
//缩略图生成
//FileHelper.MakeThumbnail(path, "新的路径", 100, 100, "W", "jpg", 0, 0);
bool IsOk = false;
//。。。。业务逻辑
if (!IsOk)
throw NCCException.Oh(ErrorCode.D8001);
}
#region GET
/// <summary>
/// 列表 (带分页)
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
[HttpGet("")]
public async Task<dynamic> GetList([FromQuery] DemoQuery input)
{
var sidx = input.sidx.IsNullOrWhiteSpace() ? "F_CREATORTIME" : input.sidx;
var list = await _demoRepository.Entities
.Where(x => x.CreatorUserId == _userManager.UserId && (x.DeleteMark == null || x.DeleteMark == 0))
.WhereIF(!input.keyword.IsNullOrEmpty(), m => m.CustomerName.Contains(input.keyword) || m.Description.Contains(input.keyword))
.WhereIF(!input.CustomeName.IsNullOrEmpty(), m => m.CustomerName == input.CustomeName)
.OrderBy(sidx + " " + input.sort).ToPagedListAsync(input.currentPage, input.pageSize);
var pageList = new SqlSugarPagedList<DemoListOutput>()
{
list = list.list.Adapt<List<DemoListOutput>>(),
pagination = list.pagination
};
return PageResult<DemoListOutput>.SqlSugarPageResult(pageList);
}
/// <summary>
/// 信息
/// </summary>
/// <param name="id">主键值</param>
/// <returns></returns>
[HttpGet("{id}")]
public async Task<dynamic> GetInfo(string id)
{
return (await _demoRepository.FirstOrDefaultAsync(x => x.Id == id && x.DeleteMark == null)).Adapt<DemoEntity>();
}
#endregion
#region POST
/// <summary>
/// 新建
/// </summary>
/// <param name="input">请求参数</param>
/// <returns></returns>
[HttpPost("")]
public async Task Create([FromBody] DemoEntity input)
{
App.GetService<IBillRullService>().UseBillNumber("OrderNumber");
var orderEntity = input.Adapt<DemoEntity>();
orderEntity.Id = YitIdHelper.NextId().ToString();
if (await _demoRepository.AnyAsync(x => x.CustomerName == input.CustomerName && x.DeleteMark != 1))
throw NCCException.Oh(ErrorCode.COM1004);
var entity = input.Adapt<DocumentEntity>();
entity.DeleteMark = 0;
var isOk = await _demoRepository.Context.Insertable(entity).CallEntityMethod(m => m.Creator()).ExecuteCommandAsync();
if (isOk < 1)
throw NCCException.Oh(ErrorCode.COM1000);
}
/// <summary>
/// 更新
/// </summary>
/// <param name="input">请求参数</param>
/// <returns></returns>
[HttpPut("{id}")]
public async Task Update([FromBody] DemoEntity input)
{
var Entity = input.Adapt<DemoEntity>();
_demoRepository.Update(Entity);
}
/// <summary>
/// 删除
/// </summary>
/// <param name="id">主键值</param>
/// <returns></returns>
[HttpDelete("{id}")]
public async Task Delete(string id)
{
var entity = await _demoRepository.FirstOrDefaultAsync(x => x.Id == id && x.DeleteMark == null);
if (entity != null)
{
await _demoRepository.DeleteAsync(x => x.Id == id);
}
else
throw NCCException.Oh(ErrorCode.COM1002);
}
#endregion
}
}