BaseAmountHistoryService.cs
20.5 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
using NCC.Common.Core.Manager;
using NCC.Common.Enum;
using NCC.Common.Extension;
using NCC.Common.Filter;
using NCC.Dependency;
using NCC.DynamicApiController;
using NCC.FriendlyException;
using NCC.Order.Interfaces.BaseAmountHistory;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using NCC.Order.Entitys;
using NCC.Order.Entitys.Dto.BaseAmountHistory;
using Yitter.IdGenerator;
using NCC.Common.Helper;
using NCC.JsonSerialization;
using NCC.System.Interfaces.System;
using NCC.Food.Entitys.Enum;
using NCC.Order.Interfaces.MarketingRules;
using NCC.Order.Interfaces.BaseOrder;
using Serilog;
using Antis.Pay.Core.Interface;
using NCC.System.Entitys.Permission;
using NCC.Core.Pay.WeChatPay.V2.Request;
using NCC.Core.Pay.WeChatPay.V2;
using NCC.Core.Pay.WeChatPay;
using Microsoft.Extensions.Options;
using NPOI.POIFS.Properties;
namespace NCC.Order.BaseAmountHistory
{
/// <summary>
/// 金额流水记录服务
/// </summary>
[ApiDescriptionSettings(Tag = "订单流水", Name = "BaseAmountHistory", Order = 200)]
[Route("api/Order/[controller]")]
public class BaseAmountHistoryService : IBaseAmountHistoryService, IDynamicApiController, ITransient
{
private readonly ISqlSugarRepository<BaseAmountHistoryEntity> _baseAmountHistoryRepository;
private readonly IDbLinkService _dbLinkService;
private readonly IDataBaseService _dataBaseService;
private readonly SqlSugarScope _db;
private readonly IUserManager _userManager;
private readonly IWePay _wepay;
private readonly IWeChatPayClient _client;
private readonly IOptions<WeChatPayOptions> _optionsAccessor;
/// <summary>
/// 初始化一个<see cref="BaseAmountHistoryService"/>类型的新实例
/// </summary>
public BaseAmountHistoryService(
ISqlSugarRepository<BaseAmountHistoryEntity> baseAmountHistoryRepository,
IDbLinkService dbLinkService,
IDataBaseService dataBaseService,
IUserManager userManager,
IWePay wepay,
IWeChatPayClient client,
IOptions<WeChatPayOptions> optionsAccessor)
{
_baseAmountHistoryRepository = baseAmountHistoryRepository;
_db = _baseAmountHistoryRepository.Context;
_dbLinkService = dbLinkService;
_dataBaseService = dataBaseService;
_userManager = userManager;
_wepay = wepay;
_client = client;
_optionsAccessor = optionsAccessor;
}
/// <summary>
/// 获取金额流水记录
/// </summary>
/// <param name="id">参数</param>
/// <returns></returns>
[HttpGet("{id}")]
public async Task<dynamic> GetInfo(string id)
{
var dbLink = await _dbLinkService.GetInfo("218239598550058245");
_db.AddConnection(new ConnectionConfig()
{
ConfigId = dbLink.Id,
DbType = _dataBaseService.ToDbType(dbLink.DbType),
ConnectionString = _dataBaseService.ToConnectionString(dbLink),
InitKeyType = InitKeyType.Attribute,
IsAutoCloseConnection = true
});
_db.ChangeDatabase(dbLink.Id);
var entity = await _db.Queryable<BaseAmountHistoryEntity>().FirstAsync(p => p.Id == id);
var output = entity.Adapt<BaseAmountHistoryInfoOutput>();
return output;
}
/// <summary>
/// 获取金额流水记录列表
/// </summary>
/// <param name="input">请求参数</param>
/// <returns></returns>
[HttpGet("")]
public async Task<dynamic> GetList([FromQuery] BaseAmountHistoryListQueryInput input)
{
var dbLink = await _dbLinkService.GetInfo("218239598550058245");
_db.AddConnection(new ConnectionConfig()
{
ConfigId = dbLink.Id,
DbType = _dataBaseService.ToDbType(dbLink.DbType),
ConnectionString = _dataBaseService.ToConnectionString(dbLink),
InitKeyType = InitKeyType.Attribute,
IsAutoCloseConnection = true
});
_db.ChangeDatabase(dbLink.Id);
var sidx = input.sidx == null ? "id" : input.sidx;
List<string> queryCreatorTime = input.creatorTime != null ? input.creatorTime.Split(',').ToObeject<List<string>>() : null;
DateTime? startCreatorTime = queryCreatorTime != null ? Ext.GetDateTime(queryCreatorTime.First()) : null;
DateTime? endCreatorTime = queryCreatorTime != null ? Ext.GetDateTime(queryCreatorTime.Last()) : null;
var data = await _db.Queryable<BaseAmountHistoryEntity>()
.WhereIF(!string.IsNullOrEmpty(input.money), p => p.Money.Equals(input.money))
.WhereIF(!string.IsNullOrEmpty(input.productId), p => p.ProductId.Contains(input.productId))
.WhereIF(!string.IsNullOrEmpty(input.userId), p => p.UserId.Contains(input.userId))
.WhereIF(!string.IsNullOrEmpty(input.source), p => p.Source.Contains(input.source))
.WhereIF(!string.IsNullOrEmpty(input.status), p => p.Status.Equals(input.status))
.WhereIF(queryCreatorTime != null, p => p.CreatorTime >= new DateTime(startCreatorTime.ToDate().Year, startCreatorTime.ToDate().Month, startCreatorTime.ToDate().Day, 0, 0, 0))
.WhereIF(queryCreatorTime != null, p => p.CreatorTime <= new DateTime(endCreatorTime.ToDate().Year, endCreatorTime.ToDate().Month, endCreatorTime.ToDate().Day, 23, 59, 59))
//.WhereIF(input.myChildren != null && input.myChildren.Value, p =>
//p.Source == SqlFunc.ToString(MoneyHistoryType.分销提成.ToString())
//&& SqlFunc.Subqueryable<UserEntity>().Where(o => o.ParentId == _userManager.UserId && o.Id == p.PayUserId).Any())
.Select(p => new BaseAmountHistoryListOutput
{
id = p.Id,
money = p.Money,
productId = p.ProductId,
userId = p.UserId,
source = p.Source,
status = p.Status,
creatorTime = p.CreatorTime,
payUserId = p.PayUserId,
orderId = p.OrderId,
orderMoney = SqlFunc.Subqueryable<BaseOrderEntity>().Where(od => od.Id == p.OrderId).Select(o => o.Money),
payUserName = SqlFunc.Subqueryable<UserEntity>().Where(o => o.Id == p.PayUserId).Select(o => o.RealName),
userName = SqlFunc.Subqueryable<UserEntity>().Where(o => o.Id == p.UserId).Select(o => o.RealName)
}).MergeTable().OrderBy(sidx + " " + input.sort).ToPagedListAsync(input.currentPage, input.pageSize);
return PageResult<BaseAmountHistoryListOutput>.SqlSugarPageResult(data);
}
/// <summary>
/// 新建金额流水记录
/// </summary>
/// <param name="input">参数</param>
/// <returns></returns>
[HttpPost("")]
public async Task Create([FromBody] BaseAmountHistoryCrInput input)
{
var dbLink = await _dbLinkService.GetInfo("218239598550058245");
_db.AddConnection(new ConnectionConfig()
{
ConfigId = dbLink.Id,
DbType = _dataBaseService.ToDbType(dbLink.DbType),
ConnectionString = _dataBaseService.ToConnectionString(dbLink),
InitKeyType = InitKeyType.Attribute,
IsAutoCloseConnection = true
});
_db.ChangeDatabase(dbLink.Id);
var userInfo = await _userManager.GetUserInfo();
var entity = input.Adapt<BaseAmountHistoryEntity>();
entity.Id = YitIdHelper.NextId().ToString();
entity.CreatorTime = DateTime.Now;
var isOk = await _db.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
if (!(isOk > 0)) throw NCCException.Oh(ErrorCode.COM1000);
}
/// <summary>
/// 更新金额流水记录
/// </summary>
/// <param name="id">主键</param>
/// <param name="input">参数</param>
/// <returns></returns>
[HttpPut("{id}")]
[NonAction]
public async Task Update(string id, [FromBody] BaseAmountHistoryUpInput input)
{
var dbLink = await _dbLinkService.GetInfo("218239598550058245");
_db.AddConnection(new ConnectionConfig()
{
ConfigId = dbLink.Id,
DbType = _dataBaseService.ToDbType(dbLink.DbType),
ConnectionString = _dataBaseService.ToConnectionString(dbLink),
InitKeyType = InitKeyType.Attribute,
IsAutoCloseConnection = true
});
_db.ChangeDatabase(dbLink.Id);
var entity = input.Adapt<BaseAmountHistoryEntity>();
var isOk = await _db.Updateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
if (!(isOk > 0)) throw NCCException.Oh(ErrorCode.COM1001);
}
/// <summary>
/// 删除金额流水记录
/// </summary>
/// <returns></returns>
[HttpDelete("{id}")]
[NonAction]
public async Task Delete(string id)
{
var dbLink = await _dbLinkService.GetInfo("218239598550058245");
_db.AddConnection(new ConnectionConfig()
{
ConfigId = dbLink.Id,
DbType = _dataBaseService.ToDbType(dbLink.DbType),
ConnectionString = _dataBaseService.ToConnectionString(dbLink),
InitKeyType = InitKeyType.Attribute,
IsAutoCloseConnection = true
});
_db.ChangeDatabase(dbLink.Id);
var entity = await _db.Queryable<BaseAmountHistoryEntity>().FirstAsync(p => p.Id == id);
_ = entity ?? throw NCCException.Oh(ErrorCode.COM1005);
var isOk = await _db.Deleteable<BaseAmountHistoryEntity>().Where(d => d.Id == id).ExecuteCommandAsync();
if (!(isOk > 0)) throw NCCException.Oh(ErrorCode.COM1002);
}
/// <summary>
/// 获取当前用户所有余额
/// </summary>
/// <returns></returns>
[HttpGet("userAmount")]
public decimal GetUserAmount()
{
string UserId = _userManager.UserId;
return _db.Queryable<BaseAmountHistoryEntity>()
.Where(u =>
u.UserId == UserId
&& u.Status == PriceStatus.可用.GetHashCode()
&& u.Source != MoneyHistoryType.消费.ToString()
&& u.Source != MoneyHistoryType.退款.ToString()
).Sum(u => u.Money);
}
/// <summary>
/// 获取当前用户所有剩余匹配次数
/// </summary>
/// <returns></returns>
[HttpGet("GetMatchOverCount")]
public int GetMatchOverCount()
{
try
{
string UserId = _userManager.UserId;
return decimal.ToInt32(_db.Queryable<BaseAmountHistoryEntity>()
.Where(u =>
u.UserId == UserId
&& u.Status == PriceStatus.可用.GetHashCode()
&& u.Source == MoneyHistoryType.匹配次数.ToString()
).Sum(u => u.Money));
}
catch (Exception)
{
return 0;
}
}
[HttpPost("transtest")]
public async Task<object> transtest(int money = 1)
{
var user = _db.Queryable<UserEntity>().First(o => o.Id == _userManager.UserId);
string orderid = YitIdHelper.NextId().ToString();
var request = new WeChatPayPromotionTransfersRequest
{
PartnerTradeNo = orderid,
OpenId = user.OpenId,
CheckName = "NO_CHECK",
ReUserName = user.OpenId,
Amount = money,
Desc = "测试提现",
SpBillCreateIp = ""
};
return await _client.ExecuteAsync(request, _optionsAccessor.Value);
}
/// <summary>
/// 提现
/// </summary>
/// <param name="money">提现金额</param>
/// <returns></returns>
[HttpGet("Withdrawal")]
public async Task Withdrawal(decimal money)
{
var user = _db.Queryable<UserEntity>().First(o => o.Id == _userManager.UserId);
if (user == null) throw NCCException.Oh("用户信息拉取失败!");
var cmoney = GetUserAmount();
if (cmoney < money) throw NCCException.Oh("提现金额超过余额!");
_db.BeginTran();
try
{
string wid = YitIdHelper.NextId().ToString();
string orderid = YitIdHelper.NextId().ToString();
string? transfer = null;
//.......
//增加余额提现
await _db.Insertable(new BaseAmountHistoryEntity()
{
CreatorTime = DateTime.Now,
Id = wid,
Money = -money,
OrderId = orderid,
ProductId = "",
Source = MoneyHistoryType.提现.ToString(),
Status = PriceStatus.可用.GetHashCode(),
UserId = _userManager.UserId,
}).ExecuteCommandAsync();
//后面测试在做验证
if (transfer == null)
{
_db.RollbackTran();
throw NCCException.Oh("发起提现失败!");
}
_db.CommitTran();
}
catch (Exception)
{
_db.RollbackTran();
}
}
/// <summary>
/// 代理星球首页信息
/// </summary>
/// <returns>percentageScale 提成比例 myFans 我的粉丝 balance 余额 </returns>
[HttpGet("homeStatistics")]
public async Task<dynamic> HomeStatistics()
{
var rule = await App.GetService<IMarketingRulesService>().GetUserRule();
decimal percentageScale = 0;
decimal myFans = 0;
decimal balance = GetUserAmount();
if (rule != null)
{
myFans = rule.fansCount;
percentageScale = rule.proportion;
}
return new
{
percentageScale,
myFans,
balance
};
}
/// <summary>
/// 订单 匹配次数增加
/// </summary>
/// <param name="orderId"></param>
/// <returns></returns>
[HttpPost("UserMatchCountAccount")]
public async Task UserMatchCountAccount(string orderId)
{
try
{
var order = _db.Queryable<BaseOrderEntity>().Where(o => o.Id == orderId).First();// await App.GetService<IBaseOrderService>().GetInfo(orderId);
if (order == null)
{
Log.Information($"订单 {orderId} 不存在!");
return;
}
if (_db.Queryable<BaseAmountHistoryEntity>()
.Where(u =>
u.OrderId == orderId
&& u.Status == PriceStatus.可用.GetHashCode()
&& u.Source == MoneyHistoryType.匹配次数.ToString()).Any())
{
Log.Information($"订单 {orderId} 已处理过!");
return;
}
var product = _db.Queryable<BaseProductEntity>().Where(o => o.Id == order.ProductId).First();
if (product != null && product.Discount > 0)
{
List<BaseAmountHistoryEntity> list = new List<BaseAmountHistoryEntity>();
for (int i = 0; i < product.Discount; i++)
{
//增加次数
list.Add(new BaseAmountHistoryEntity()
{
CreatorTime = DateTime.Now,
Id = YitIdHelper.NextId().ToString(),
Money = 1,
OrderId = order.Id,
ProductId = order.ProductId,
Source = MoneyHistoryType.匹配次数.ToString(),
Status = PriceStatus.可用.GetHashCode(),
UserId = order.CreatorUserId,
PayUserId = order.CreatorUserId,
ValidStart = product.ValidStart,
ValidEnd = product.ValidEnd,
});//.ExecuteCommandAsync();
}
await _db.Insertable(list).ExecuteCommandAsync();
}
else
{
Log.Information($" 匹配次数计算未进行");
}
}
catch (Exception ex)
{
Log.Information($"匹配次数计算异常 原因 :{ex.Message}");
}
}
/// <summary>
/// 订单分销金额计算 还需要完善 分销的条件 不应该是所有人都能
/// </summary>
/// <param name="orderId"></param>
/// <returns></returns>
public async Task DistributionAccount(string orderId)
{
return;
//try
//{
// var order = _db.Queryable<BaseOrderEntity>().Where(o => o.Id == orderId).First();// await App.GetService<IBaseOrderService>().GetInfo(orderId);
// if (order == null)
// {
// Log.Information($"订单 {orderId} 不存在!");
// return;
// }
// var parentId = _db.Queryable<UserEntity>().Where(o => o.Id == order.CreatorUserId).Select(o => o.ParentId).First();
// if (parentId.IsNullOrEmpty())
// {
// Log.Information($"订单 {orderId}下单用户不是分销成员不进行分销!");
// return;
// }
// Log.Information($"订单 {orderId} 开始计算分销提成!");
// var rule = await App.GetService<IMarketingRulesService>().GetUserRule(parentId);
// if (order != null && rule != null && rule.proportion > 0)
// {
// decimal money = order.Money;
// money = (rule.proportion / 100) * money; //得到百分比的分销提成
// if (_db.Queryable<BaseAmountHistoryEntity>().Where(o => o.OrderId == order.Id && o.Source == MoneyHistoryType.分销提成.ToString()).Any())
// {
// Log.Information($"订单 {order.Id} 已进行过分销不在进行处理!");
// }
// else if (money <= 0)
// {
// Log.Information($"订单 {order.Id} 分销得到的金额小于等于0 不进行分销 金额= {money} ");
// }
// else
// {
// //增加余额
// await _db.Insertable(new BaseAmountHistoryEntity()
// {
// CreatorTime = DateTime.Now,
// Id = YitIdHelper.NextId().ToString(),
// Money = money,
// OrderId = order.Id,
// ProductId = order.ProductId,
// Source = MoneyHistoryType.分销提成.ToString(),
// Status = PriceStatus.可用.GetHashCode(),
// UserId = parentId,
// PayUserId = order.CreatorUserId
// }).ExecuteCommandAsync();
// }
// }
// else
// {
// Log.Information($"分销未进行");
// }
//}
//catch (Exception ex)
//{
// Log.Information($"分销异常 原因 :{ex.Message}");
//}
}
}
}