shop/CoreCms.Net.Task/RefreshUserBalanceJob.cs
2025-10-25 02:09:56 +08:00

97 lines
3.4 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using CoreCms.Net.Caching.AutoMate.RedisCache;
using CoreCms.Net.Configuration;
using CoreCms.Net.IServices;
using CoreCms.Net.Model.Entities;
using CoreCms.Net.WeChat.Service.HttpClients;
using CoreCms.Net.WeChat.Service.Options;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using SKIT.FlurlHttpClient.Wechat.Api.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CoreCms.Net.Task
{
/// <summary>
/// 定时重置用户余额当用户刷新余额大于0的时候每天会将用户余额数量设置为刷新余额数量。
/// </summary>
public class RefreshUserBalanceJob
{
private readonly ISysTaskLogServices _taskLogServices;
private readonly ICoreCmsUserServices _userServices;
public RefreshUserBalanceJob(IRedisOperationRepository redisOperationRepository, ISysTaskLogServices taskLogServices, IOptions<WeChatOptions> weChatOptions, IWeChatApiHttpClientFactory weChatApiHttpClientFactory, IWeChatAccessTokenServices weChatAccessTokenServices, ICoreCmsUserServices userServices)
{
_taskLogServices = taskLogServices;
_userServices = userServices;
}
public async System.Threading.Tasks.Task Execute()
{
try
{
// 查询所有需要刷新余额的用户reBalance > 0
var users = await _userServices.QueryListByClauseAsync(p => p.reBalance > 0);
if (users == null || users.Count == 0)
{
var emptyLog = new SysTaskLog
{
createTime = DateTime.Now,
isSuccess = true,
name = "刷新用户余额",
parameters = JsonConvert.SerializeObject(new { total = 0, updated = 0, skipped = 0 })
};
await _taskLogServices.InsertAsync(emptyLog);
return;
}
int total = users.Count;
int updated = 0;
int skipped = 0;
foreach (var u in users)
{
var delta = u.reBalance - u.balance;
if (delta == 0)
{
skipped++;
continue;
}
var res = await _userServices.UpdateBalance(u.id, delta);
if (res != null && res.code == 0)
{
updated++;
}
}
var log = new SysTaskLog
{
createTime = DateTime.Now,
isSuccess = true,
name = "刷新用户余额",
parameters = JsonConvert.SerializeObject(new { total, updated, skipped })
};
await _taskLogServices.InsertAsync(log);
}
catch (Exception ex)
{
//插入日志
var model = new SysTaskLog
{
createTime = DateTime.Now,
isSuccess = false,
name = "刷新用户余额",
parameters = JsonConvert.SerializeObject(ex)
};
await _taskLogServices.InsertAsync(model);
}
}
}
}