20261116 #24
93
src/Oms.Application/DataPerm/DataPermAccessAuditor.cs
Normal file
93
src/Oms.Application/DataPerm/DataPermAccessAuditor.cs
Normal file
@ -0,0 +1,93 @@
|
||||
using System.Diagnostics;
|
||||
using System.Text.Json;
|
||||
using Fake.DependencyInjection;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
|
||||
namespace Oms.Application.DataPerm;
|
||||
|
||||
/// <summary>
|
||||
/// 数据权限访问审计:按采样率写入 data_perm_access_log,失败不影响主流程。
|
||||
/// </summary>
|
||||
public class DataPermAccessAuditor(
|
||||
DataPermStore store,
|
||||
IHttpContextAccessor httpContextAccessor) : IScopedDependency
|
||||
{
|
||||
private static readonly JsonSerializerOptions JsonOptions = new()
|
||||
{
|
||||
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// 尝试写入访问日志;采样未命中或无用户上下文时直接跳过。
|
||||
/// </summary>
|
||||
public async Task TryWriteAsync(
|
||||
DataScopeContext? context,
|
||||
string apiPath,
|
||||
string httpMethod,
|
||||
int? rowCount,
|
||||
int? elapsedMs,
|
||||
int samplePercent,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (context == null || samplePercent <= 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (samplePercent < 100 && Random.Shared.Next(100) >= samplePercent)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var appliedScopeJson = JsonSerializer.Serialize(
|
||||
new
|
||||
{
|
||||
context.IsAdmin,
|
||||
context.DataResourceCode,
|
||||
context.DataScope,
|
||||
OrganizationIds = context.OrganizationIds.Select(x => x.ToString()).ToList(),
|
||||
SecretLevels = context.SecretLevels.OrderBy(x => x).ToList(),
|
||||
BizFilters = context.BizFilters,
|
||||
OwnerMapIds = context.ResolvedOwnerIds
|
||||
},
|
||||
JsonOptions);
|
||||
|
||||
await store.InsertAccessLogAsync(
|
||||
context.UserId,
|
||||
context.MapId,
|
||||
context.DataResourceCode,
|
||||
apiPath,
|
||||
httpMethod,
|
||||
appliedScopeJson,
|
||||
rowCount,
|
||||
elapsedMs,
|
||||
ResolveClientIp(),
|
||||
cancellationToken);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 审计失败不阻断业务
|
||||
}
|
||||
}
|
||||
|
||||
private string? ResolveClientIp()
|
||||
{
|
||||
var http = httpContextAccessor.HttpContext;
|
||||
if (http == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var forwarded = http.Request.Headers["X-Forwarded-For"].FirstOrDefault();
|
||||
if (!string.IsNullOrWhiteSpace(forwarded))
|
||||
{
|
||||
return forwarded.Split(',')[0].Trim();
|
||||
}
|
||||
|
||||
return http.Connection.RemoteIpAddress?.ToString();
|
||||
}
|
||||
|
||||
public static Stopwatch StartTimer() => Stopwatch.StartNew();
|
||||
}
|
||||
@ -73,4 +73,10 @@ public static class DataPermConstants
|
||||
(5, "VIP4"),
|
||||
(6, "VIP5")
|
||||
];
|
||||
|
||||
/// <summary>订单列表等查询访问日志采样百分比(0=关闭,100=全量)。</summary>
|
||||
public const int AccessLogSamplePercentList = 10;
|
||||
|
||||
/// <summary>导出等敏感操作访问日志采样百分比。</summary>
|
||||
public const int AccessLogSamplePercentExport = 100;
|
||||
}
|
||||
|
||||
@ -478,9 +478,42 @@ public class DataPermStore(FakeRbacDbContext dbContext, DataPermContextCache cac
|
||||
cancellationToken);
|
||||
}
|
||||
|
||||
public async Task InsertAccessLogAsync(
|
||||
Guid userId,
|
||||
int mapId,
|
||||
string dataResourceCode,
|
||||
string apiPath,
|
||||
string httpMethod,
|
||||
string? appliedScopeJson,
|
||||
int? rowCount,
|
||||
int? elapsedMs,
|
||||
string? clientIp,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
await dbContext.Database.ExecuteSqlRawAsync("""
|
||||
INSERT INTO `data_perm_access_log`
|
||||
(`UserId`,`MapId`,`DataResourceCode`,`ApiPath`,`HttpMethod`,`AppliedScopeJson`,`RowCount`,`ElapsedMs`,`ClientIp`,`CreateTime`)
|
||||
VALUES ({0},{1},{2},{3},{4},{5},{6},{7},{8},UTC_TIMESTAMP())
|
||||
""",
|
||||
[
|
||||
userId.ToString(),
|
||||
mapId,
|
||||
dataResourceCode.Trim(),
|
||||
apiPath.Trim(),
|
||||
string.IsNullOrWhiteSpace(httpMethod) ? "GET" : httpMethod.Trim().ToUpperInvariant(),
|
||||
SqlParam(appliedScopeJson),
|
||||
SqlParam(rowCount),
|
||||
SqlParam(elapsedMs),
|
||||
SqlParam(clientIp)
|
||||
],
|
||||
cancellationToken);
|
||||
}
|
||||
|
||||
public async Task<DataPermPagedResult<ChangeLogItemDto>> GetChangeLogsAsync(
|
||||
string? targetType,
|
||||
string? targetId,
|
||||
DateTime? startTime,
|
||||
DateTime? endTime,
|
||||
int page,
|
||||
int pageSize,
|
||||
CancellationToken cancellationToken = default)
|
||||
@ -499,6 +532,18 @@ public class DataPermStore(FakeRbacDbContext dbContext, DataPermContextCache cac
|
||||
args.Add(targetId.Trim());
|
||||
}
|
||||
|
||||
if (startTime.HasValue)
|
||||
{
|
||||
where += " AND l.`CreateTime` >= {" + args.Count + "}";
|
||||
args.Add(startTime.Value);
|
||||
}
|
||||
|
||||
if (endTime.HasValue)
|
||||
{
|
||||
where += " AND l.`CreateTime` <= {" + args.Count + "}";
|
||||
args.Add(endTime.Value);
|
||||
}
|
||||
|
||||
var countSql = $"SELECT COUNT(*) AS `Value` FROM `data_perm_change_log` l {where}";
|
||||
var total = await dbContext.Database.SqlQueryRaw<long>(countSql, args.ToArray()).FirstAsync(cancellationToken);
|
||||
var offset = Math.Max(page - 1, 0) * pageSize;
|
||||
@ -567,22 +612,53 @@ public class DataPermStore(FakeRbacDbContext dbContext, DataPermContextCache cac
|
||||
}
|
||||
|
||||
public async Task<DataPermPagedResult<AccessLogItemDto>> GetAccessLogsAsync(
|
||||
string? userId,
|
||||
string? dataResourceCode,
|
||||
DateTime? startTime,
|
||||
DateTime? endTime,
|
||||
int page,
|
||||
int pageSize,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
const string countSql = "SELECT COUNT(*) AS `Value` FROM `data_perm_access_log`";
|
||||
var total = await dbContext.Database.SqlQueryRaw<long>(countSql).FirstAsync(cancellationToken);
|
||||
var where = "WHERE 1=1";
|
||||
var args = new List<object>();
|
||||
if (!string.IsNullOrWhiteSpace(userId))
|
||||
{
|
||||
where += " AND l.`UserId` = {" + args.Count + "}";
|
||||
args.Add(userId.Trim());
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(dataResourceCode))
|
||||
{
|
||||
where += " AND l.`DataResourceCode` = {" + args.Count + "}";
|
||||
args.Add(dataResourceCode.Trim());
|
||||
}
|
||||
|
||||
if (startTime.HasValue)
|
||||
{
|
||||
where += " AND l.`CreateTime` >= {" + args.Count + "}";
|
||||
args.Add(startTime.Value);
|
||||
}
|
||||
|
||||
if (endTime.HasValue)
|
||||
{
|
||||
where += " AND l.`CreateTime` <= {" + args.Count + "}";
|
||||
args.Add(endTime.Value);
|
||||
}
|
||||
|
||||
var countSql = $"SELECT COUNT(*) AS `Value` FROM `data_perm_access_log` l {where}";
|
||||
var total = await dbContext.Database.SqlQueryRaw<long>(countSql, args.ToArray()).FirstAsync(cancellationToken);
|
||||
var offset = Math.Max(page - 1, 0) * pageSize;
|
||||
var listSql = $"""
|
||||
SELECT l.`Id` AS `Id`, l.`UserId` AS `UserId`, l.`DataResourceCode` AS `DataResourceCode`,
|
||||
l.`ApiPath` AS `ApiPath`, l.`RowCount` AS `RowCount`, l.`CreateTime` AS `CreateTime`
|
||||
FROM `data_perm_access_log` l
|
||||
{where}
|
||||
ORDER BY l.`CreateTime` DESC
|
||||
LIMIT {pageSize} OFFSET {offset}
|
||||
""";
|
||||
|
||||
var items = await dbContext.Database.SqlQueryRaw<AccessLogRow>(listSql)
|
||||
var items = await dbContext.Database.SqlQueryRaw<AccessLogRow>(listSql, args.ToArray())
|
||||
.ToListAsync(cancellationToken);
|
||||
return new DataPermPagedResult<AccessLogItemDto>
|
||||
{
|
||||
@ -693,6 +769,7 @@ public class DataPermStore(FakeRbacDbContext dbContext, DataPermContextCache cac
|
||||
|
||||
public async Task<DataPermTemplateDetailDto> CreateTemplateAsync(
|
||||
DataPermTemplateSaveInput input,
|
||||
Guid operatorUserId,
|
||||
int operatorMapId,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
@ -706,12 +783,23 @@ public class DataPermStore(FakeRbacDbContext dbContext, DataPermContextCache cac
|
||||
cancellationToken);
|
||||
|
||||
await ReplaceTemplateItemsAsync(id, input.Items, cancellationToken);
|
||||
return await GetTemplateDetailAsync(id, cancellationToken);
|
||||
var created = await GetTemplateDetailAsync(id, cancellationToken);
|
||||
await InsertChangeLogAsync(
|
||||
"template",
|
||||
id.ToString(),
|
||||
"create",
|
||||
null,
|
||||
JsonSerializer.Serialize(created, JsonOptions),
|
||||
operatorUserId,
|
||||
operatorMapId,
|
||||
cancellationToken);
|
||||
return created;
|
||||
}
|
||||
|
||||
public async Task<DataPermTemplateDetailDto> UpdateTemplateAsync(
|
||||
Guid templateId,
|
||||
DataPermTemplateSaveInput input,
|
||||
Guid operatorUserId,
|
||||
int operatorMapId,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
@ -721,6 +809,7 @@ public class DataPermStore(FakeRbacDbContext dbContext, DataPermContextCache cac
|
||||
throw new BusinessException("内置模板不可修改编码");
|
||||
}
|
||||
|
||||
var beforeJson = JsonSerializer.Serialize(existing, JsonOptions);
|
||||
await dbContext.Database.ExecuteSqlRawAsync("""
|
||||
UPDATE `data_perm_template`
|
||||
SET `Name` = {0}, `Description` = {1}, `RoleCode` = {2}, `UpdateUserId` = {3}, `UpdateTime` = UTC_TIMESTAMP()
|
||||
@ -730,10 +819,24 @@ public class DataPermStore(FakeRbacDbContext dbContext, DataPermContextCache cac
|
||||
cancellationToken);
|
||||
|
||||
await ReplaceTemplateItemsAsync(templateId, input.Items, cancellationToken);
|
||||
return await GetTemplateDetailAsync(templateId, cancellationToken);
|
||||
var updated = await GetTemplateDetailAsync(templateId, cancellationToken);
|
||||
await InsertChangeLogAsync(
|
||||
"template",
|
||||
templateId.ToString(),
|
||||
"update",
|
||||
beforeJson,
|
||||
JsonSerializer.Serialize(updated, JsonOptions),
|
||||
operatorUserId,
|
||||
operatorMapId,
|
||||
cancellationToken);
|
||||
return updated;
|
||||
}
|
||||
|
||||
public async Task DeleteTemplateAsync(Guid templateId, CancellationToken cancellationToken = default)
|
||||
public async Task DeleteTemplateAsync(
|
||||
Guid templateId,
|
||||
Guid operatorUserId,
|
||||
int operatorMapId,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var existing = await GetTemplateDetailAsync(templateId, cancellationToken);
|
||||
if (existing.IsBuiltIn)
|
||||
@ -741,6 +844,7 @@ public class DataPermStore(FakeRbacDbContext dbContext, DataPermContextCache cac
|
||||
throw new BusinessException("内置模板不可删除");
|
||||
}
|
||||
|
||||
var beforeJson = JsonSerializer.Serialize(existing, JsonOptions);
|
||||
await dbContext.Database.ExecuteSqlRawAsync(
|
||||
"UPDATE `data_perm_template` SET `IsDeleted` = 1, `UpdateTime` = UTC_TIMESTAMP() WHERE `Id` = {0}",
|
||||
[templateId.ToString()],
|
||||
@ -749,6 +853,15 @@ public class DataPermStore(FakeRbacDbContext dbContext, DataPermContextCache cac
|
||||
"UPDATE `data_perm_template_item` SET `IsDeleted` = 1 WHERE `TemplateId` = {0}",
|
||||
[templateId.ToString()],
|
||||
cancellationToken);
|
||||
await InsertChangeLogAsync(
|
||||
"template",
|
||||
templateId.ToString(),
|
||||
"delete",
|
||||
beforeJson,
|
||||
null,
|
||||
operatorUserId,
|
||||
operatorMapId,
|
||||
cancellationToken);
|
||||
}
|
||||
|
||||
private async Task ReplaceTemplateItemsAsync(
|
||||
|
||||
15
src/Oms.Application/Dtos/System/NoticeReadConfirmAllInput.cs
Normal file
15
src/Oms.Application/Dtos/System/NoticeReadConfirmAllInput.cs
Normal file
@ -0,0 +1,15 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace Oms.Application.Dtos.System;
|
||||
|
||||
/// <summary>
|
||||
/// 一键清扫未读入参。
|
||||
/// </summary>
|
||||
public class NoticeReadConfirmAllInput
|
||||
{
|
||||
/// <summary>
|
||||
/// 通知类型:notice/message;默认 message。
|
||||
/// </summary>
|
||||
[StringLength(16)]
|
||||
public string? NoticeType { get; set; } = "message";
|
||||
}
|
||||
@ -0,0 +1,12 @@
|
||||
namespace Oms.Application.Dtos.System;
|
||||
|
||||
/// <summary>
|
||||
/// 一键清扫未读结果。
|
||||
/// </summary>
|
||||
public class NoticeReadConfirmAllOutput
|
||||
{
|
||||
/// <summary>
|
||||
/// 本次新标记为已读的条数。
|
||||
/// </summary>
|
||||
public int ClearedCount { get; set; }
|
||||
}
|
||||
@ -43,7 +43,7 @@ public partial class DataPermService
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ValidateTemplateInput(input);
|
||||
return Store.CreateTemplateAsync(input, GetCurrentMapId(), cancellationToken);
|
||||
return Store.CreateTemplateAsync(input, GetCurrentUserGuid(), GetCurrentMapId(), cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -56,7 +56,12 @@ public partial class DataPermService
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ValidateTemplateInput(input);
|
||||
return Store.UpdateTemplateAsync(ParseGuid(id, "id"), input, GetCurrentMapId(), cancellationToken);
|
||||
return Store.UpdateTemplateAsync(
|
||||
ParseGuid(id, "id"),
|
||||
input,
|
||||
GetCurrentUserGuid(),
|
||||
GetCurrentMapId(),
|
||||
cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -64,7 +69,7 @@ public partial class DataPermService
|
||||
/// </summary>
|
||||
[HttpDelete("/rbac/data-perm/template/delete")]
|
||||
public Task DeleteTemplateAsync([FromQuery] string id, CancellationToken cancellationToken = default) =>
|
||||
Store.DeleteTemplateAsync(ParseGuid(id, "id"), cancellationToken);
|
||||
Store.DeleteTemplateAsync(ParseGuid(id, "id"), GetCurrentUserGuid(), GetCurrentMapId(), cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// 应用数据权限模板
|
||||
@ -74,9 +79,12 @@ public partial class DataPermService
|
||||
[FromBody] TemplateApplyInput input,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var template = await Store.GetTemplateDetailAsync(ParseGuid(input.TemplateId, "templateId"), cancellationToken);
|
||||
var templateId = ParseGuid(input.TemplateId, "templateId");
|
||||
var template = await Store.GetTemplateDetailAsync(templateId, cancellationToken);
|
||||
var bundle = TemplateBundleParser.Parse(template.Items);
|
||||
var result = new TemplateApplyResultDto();
|
||||
var operatorUserId = GetCurrentUserGuid();
|
||||
var operatorMapId = GetCurrentMapId();
|
||||
|
||||
foreach (var targetIdRaw in input.TargetIds.Distinct(StringComparer.OrdinalIgnoreCase))
|
||||
{
|
||||
@ -87,7 +95,7 @@ public partial class DataPermService
|
||||
var roleId = ParseGuid(targetIdRaw, "targetId");
|
||||
var current = await Store.GetRoleDataPermAsync(roleId, cancellationToken);
|
||||
var merged = MergeRoleBundle(current, bundle, input);
|
||||
await Store.SaveRoleDataPermAsync(roleId, merged, GetCurrentUserGuid(), GetCurrentMapId(), Repository, cancellationToken);
|
||||
await Store.SaveRoleDataPermAsync(roleId, merged, operatorUserId, operatorMapId, Repository, cancellationToken);
|
||||
}
|
||||
else
|
||||
{
|
||||
@ -101,7 +109,7 @@ public partial class DataPermService
|
||||
var merged = MergeUserBundle(current, bundle, input);
|
||||
DataPermSaveValidator.Validate(merged, Repository);
|
||||
await DataPermSaveValidator.ValidateOrganizationsExistAsync(merged, Repository, cancellationToken);
|
||||
await Store.SaveUserDataPermAsync(userId, merged, GetCurrentUserGuid(), GetCurrentMapId(), cancellationToken);
|
||||
await Store.SaveUserDataPermAsync(userId, merged, operatorUserId, operatorMapId, cancellationToken);
|
||||
}
|
||||
|
||||
result.SuccessCount++;
|
||||
@ -116,6 +124,25 @@ public partial class DataPermService
|
||||
}
|
||||
}
|
||||
|
||||
await Store.InsertChangeLogAsync(
|
||||
"template",
|
||||
templateId.ToString(),
|
||||
"apply_template",
|
||||
null,
|
||||
JsonSerializer.Serialize(new
|
||||
{
|
||||
templateId = templateId.ToString(),
|
||||
templateCode = template.Code,
|
||||
targetType = input.TargetType,
|
||||
targetIds = input.TargetIds,
|
||||
mode = input.Mode,
|
||||
successCount = result.SuccessCount,
|
||||
failures = result.Failures
|
||||
}),
|
||||
operatorUserId,
|
||||
operatorMapId,
|
||||
cancellationToken);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
@ -291,12 +291,14 @@ public partial class DataPermService : ApplicationService
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 分页查询变更日志
|
||||
/// 分页查询配置变更日志(用户/角色/模板)。
|
||||
/// </summary>
|
||||
[HttpGet("/rbac/data-perm/change-log/list")]
|
||||
public Task<DataPermPagedResult<ChangeLogItemDto>> GetChangeLogListAsync(
|
||||
[FromQuery] string? targetType,
|
||||
[FromQuery] string? targetId,
|
||||
[FromQuery] DateTime? startTime = null,
|
||||
[FromQuery] DateTime? endTime = null,
|
||||
[FromQuery] int page = 1,
|
||||
[FromQuery] int pageSize = 30,
|
||||
CancellationToken cancellationToken = default)
|
||||
@ -304,21 +306,31 @@ public partial class DataPermService : ApplicationService
|
||||
return Store.GetChangeLogsAsync(
|
||||
targetType,
|
||||
targetId,
|
||||
startTime,
|
||||
endTime,
|
||||
OmsDocHelper.NormalizePage(page),
|
||||
OmsDocHelper.NormalizePageSize(pageSize),
|
||||
cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 分页查询访问日志
|
||||
/// 分页查询数据访问日志(订单列表等采样写入)。
|
||||
/// </summary>
|
||||
[HttpGet("/rbac/data-perm/access-log/list")]
|
||||
public Task<DataPermPagedResult<AccessLogItemDto>> GetAccessLogListAsync(
|
||||
[FromQuery] string? userId = null,
|
||||
[FromQuery] string? dataResourceCode = null,
|
||||
[FromQuery] DateTime? startTime = null,
|
||||
[FromQuery] DateTime? endTime = null,
|
||||
[FromQuery] int page = 1,
|
||||
[FromQuery] int pageSize = 30,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
return Store.GetAccessLogsAsync(
|
||||
userId,
|
||||
dataResourceCode,
|
||||
startTime,
|
||||
endTime,
|
||||
OmsDocHelper.NormalizePage(page),
|
||||
OmsDocHelper.NormalizePageSize(pageSize),
|
||||
cancellationToken);
|
||||
|
||||
@ -40,6 +40,9 @@ public class FinanceService : ApplicationService
|
||||
private EffectiveScopeBuilder DataScopeBuilder =>
|
||||
LazyServiceProvider.GetRequiredService<EffectiveScopeBuilder>();
|
||||
|
||||
private DataPermAccessAuditor DataPermAccessAuditor =>
|
||||
LazyServiceProvider.GetRequiredService<DataPermAccessAuditor>();
|
||||
|
||||
/// <summary>
|
||||
/// 分页查询应收应付(订单费用联查订单)。
|
||||
/// </summary>
|
||||
@ -47,13 +50,22 @@ public class FinanceService : ApplicationService
|
||||
public async Task<OmsPageResult<ReceivablePayablePaginatedOutput>> GetReceivablePayableListAsync(
|
||||
[FromQuery] ReceivablePayablePaginatedInput input)
|
||||
{
|
||||
var filter = await BuildScopedFilterAsync(input);
|
||||
var timer = DataPermAccessAuditor.StartTimer();
|
||||
var (filter, scope) = await BuildScopedFilterAsync(input);
|
||||
var pageIndex = OmsDocHelper.NormalizePage(input.Page);
|
||||
var pageSize = OmsDocHelper.NormalizePageSize(input.PageSize);
|
||||
var (rows, total) = await OrderRepository.GetReceivablePayablePagedListAsync(
|
||||
pageIndex,
|
||||
pageSize,
|
||||
filter);
|
||||
timer.Stop();
|
||||
await DataPermAccessAuditor.TryWriteAsync(
|
||||
scope,
|
||||
"/finance/receivable-payable/list",
|
||||
"GET",
|
||||
rows.Count,
|
||||
(int)timer.ElapsedMilliseconds,
|
||||
DataPermConstants.AccessLogSamplePercentList);
|
||||
|
||||
var items = await MapReceivablePayableRowsAsync(rows);
|
||||
return new OmsPageResult<ReceivablePayablePaginatedOutput>
|
||||
@ -70,7 +82,7 @@ public class FinanceService : ApplicationService
|
||||
public async Task<ReceivablePayableSummaryOutput> GetReceivablePayableSummaryAsync(
|
||||
[FromQuery] ReceivablePayablePaginatedInput input)
|
||||
{
|
||||
var filter = await BuildScopedFilterAsync(input);
|
||||
var (filter, _) = await BuildScopedFilterAsync(input);
|
||||
var rows = await OrderRepository.GetReceivablePayableSummaryAsync(filter);
|
||||
var items = rows
|
||||
.Select(row => new ReceivablePayableSummaryItemOutput
|
||||
@ -99,8 +111,17 @@ public class FinanceService : ApplicationService
|
||||
public async Task<FileContentResult> ExportReceivablePayableAsync(
|
||||
[FromQuery] ReceivablePayablePaginatedInput input)
|
||||
{
|
||||
var filter = await BuildScopedFilterAsync(input);
|
||||
var timer = DataPermAccessAuditor.StartTimer();
|
||||
var (filter, scope) = await BuildScopedFilterAsync(input);
|
||||
var rows = await OrderRepository.GetReceivablePayableExportListAsync(filter, ExportMaxRows);
|
||||
timer.Stop();
|
||||
await DataPermAccessAuditor.TryWriteAsync(
|
||||
scope,
|
||||
"/finance/receivable-payable/export",
|
||||
"GET",
|
||||
rows.Count,
|
||||
(int)timer.ElapsedMilliseconds,
|
||||
DataPermConstants.AccessLogSamplePercentExport);
|
||||
var items = await MapReceivablePayableRowsAsync(rows);
|
||||
var exportRows = items.Select(item => new
|
||||
{
|
||||
@ -137,7 +158,7 @@ public class FinanceService : ApplicationService
|
||||
};
|
||||
}
|
||||
|
||||
private async Task<OrderReceivablePayableFilter> BuildScopedFilterAsync(
|
||||
private async Task<(OrderReceivablePayableFilter Filter, DataScopeContext? Scope)> BuildScopedFilterAsync(
|
||||
ReceivablePayablePaginatedInput input)
|
||||
{
|
||||
var customerId = await OmsSessionHelper.ResolveListCustomerIdAsync(
|
||||
@ -145,8 +166,8 @@ public class FinanceService : ApplicationService
|
||||
CurrentUser,
|
||||
input.CustomerId);
|
||||
var filter = BuildFilter(input, customerId);
|
||||
await ApplyInternalOrderDataScopeAsync(filter);
|
||||
return filter;
|
||||
var scope = await ApplyInternalOrderDataScopeAsync(filter);
|
||||
return (filter, scope);
|
||||
}
|
||||
|
||||
private async Task<List<ReceivablePayablePaginatedOutput>> MapReceivablePayableRowsAsync(
|
||||
@ -284,21 +305,22 @@ public class FinanceService : ApplicationService
|
||||
};
|
||||
}
|
||||
|
||||
private async Task ApplyInternalOrderDataScopeAsync(OrderReceivablePayableFilter filter)
|
||||
private async Task<DataScopeContext?> ApplyInternalOrderDataScopeAsync(OrderReceivablePayableFilter filter)
|
||||
{
|
||||
if (OmsSessionHelper.IsCustomerLogin(CurrentUser))
|
||||
{
|
||||
return;
|
||||
return null;
|
||||
}
|
||||
|
||||
var userGuidRaw = CurrentUser.FindClaimValueOrNull(global::System.Security.Claims.ClaimTypes.NameIdentifier);
|
||||
if (string.IsNullOrWhiteSpace(userGuidRaw) || !Guid.TryParse(userGuidRaw, out var userGuid))
|
||||
{
|
||||
return;
|
||||
return null;
|
||||
}
|
||||
|
||||
var context = await DataScopeBuilder.BuildAsync(userGuid, DataScopeApplier.OrderResourceCode);
|
||||
DataScopeApplier.ApplyToOrderListFilter(filter, context);
|
||||
return context;
|
||||
}
|
||||
|
||||
private static string GetFeeTypeName(string feeType) =>
|
||||
|
||||
@ -1201,27 +1201,28 @@ public partial class OrderService
|
||||
};
|
||||
}
|
||||
|
||||
private async Task ApplyInternalOrderDataScopeAsync(OrderListFilter filter)
|
||||
private async Task<DataScopeContext?> ApplyInternalOrderDataScopeAsync(OrderListFilter filter)
|
||||
{
|
||||
if (OmsSessionHelper.IsCustomerLogin(CurrentUser))
|
||||
{
|
||||
return;
|
||||
return null;
|
||||
}
|
||||
|
||||
if (OmsSessionHelper.IsAgentLogin(CurrentUser))
|
||||
{
|
||||
await ApplyAgentOrderScopeAsync(filter);
|
||||
return;
|
||||
return null;
|
||||
}
|
||||
|
||||
var userGuidRaw = CurrentUser.FindClaimValueOrNull(global::System.Security.Claims.ClaimTypes.NameIdentifier);
|
||||
if (string.IsNullOrWhiteSpace(userGuidRaw) || !Guid.TryParse(userGuidRaw, out var userGuid))
|
||||
{
|
||||
return;
|
||||
return null;
|
||||
}
|
||||
|
||||
var context = await DataScopeBuilder.BuildAsync(userGuid, DataScopeApplier.OrderResourceCode);
|
||||
DataScopeApplier.ApplyToOrderListFilter(filter, context);
|
||||
return context;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@ -18,7 +18,7 @@ public partial class OrderService
|
||||
[FromQuery] string? dimension = "day")
|
||||
{
|
||||
var dim = NormalizeMonitorDimension(dimension);
|
||||
var filter = await BuildScopedListFilterAsync();
|
||||
var (filter, _) = await BuildScopedListFilterAsync();
|
||||
var today = DateTime.Today;
|
||||
var tomorrow = today.AddDays(1);
|
||||
var yesterday = today.AddDays(-1);
|
||||
|
||||
@ -1,4 +1,5 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Oms.Application.DataPerm;
|
||||
using Oms.Application.Dtos.Orders;
|
||||
using Oms.Application.Shared;
|
||||
using Oms.Domain.OrdersAggregate;
|
||||
@ -22,7 +23,7 @@ public partial class OrderService
|
||||
[HttpGet("/order/workplace-stats")]
|
||||
public async Task<OrderWorkplaceStatsOutput> GetWorkplaceStatsAsync()
|
||||
{
|
||||
var filter = await BuildScopedListFilterAsync();
|
||||
var (filter, _) = await BuildScopedListFilterAsync();
|
||||
var rows = await OrderRepository.GetStatusCountsByFilterAsync(filter);
|
||||
var counts = rows
|
||||
.Where(x => !string.Equals(x.Status, OrderStatusCodes.Deleted, StringComparison.OrdinalIgnoreCase))
|
||||
@ -136,7 +137,7 @@ public partial class OrderService
|
||||
_ => Math.Clamp(count, 1, 31),
|
||||
};
|
||||
|
||||
var filter = await BuildScopedListFilterAsync();
|
||||
var (filter, _) = await BuildScopedListFilterAsync();
|
||||
var buckets = BuildTrendBuckets(dim, count);
|
||||
var points = new List<OrderWorkplaceTrendPointOutput>(buckets.Count);
|
||||
|
||||
@ -187,7 +188,7 @@ public partial class OrderService
|
||||
_ => Math.Clamp(count, 1, 31),
|
||||
};
|
||||
|
||||
var filter = await BuildScopedListFilterAsync();
|
||||
var (filter, _) = await BuildScopedListFilterAsync();
|
||||
var buckets = BuildTrendBuckets(dim, count);
|
||||
var points = new List<OrderWorkplaceSpendTrendPointOutput>(buckets.Count);
|
||||
|
||||
@ -252,7 +253,7 @@ public partial class OrderService
|
||||
_ => Math.Clamp(count, 1, 31),
|
||||
};
|
||||
|
||||
var filter = await BuildScopedListFilterAsync();
|
||||
var (filter, _) = await BuildScopedListFilterAsync();
|
||||
var fulfillFilter = CloneScopedFilter(filter);
|
||||
fulfillFilter.FulfillmentType = FulfillmentTypeCodes.Warehouse;
|
||||
|
||||
@ -304,15 +305,15 @@ public partial class OrderService
|
||||
ScopeCustomFilters = filter.ScopeCustomFilters,
|
||||
};
|
||||
|
||||
private async Task<OrderListFilter> BuildScopedListFilterAsync()
|
||||
private async Task<(OrderListFilter Filter, DataScopeContext? Scope)> BuildScopedListFilterAsync()
|
||||
{
|
||||
var customerId = await OmsSessionHelper.ResolveListCustomerIdAsync(
|
||||
CustomerRepository,
|
||||
CurrentUser,
|
||||
null);
|
||||
var filter = new OrderListFilter { CustomerId = customerId };
|
||||
await ApplyInternalOrderDataScopeAsync(filter);
|
||||
return filter;
|
||||
var scope = await ApplyInternalOrderDataScopeAsync(filter);
|
||||
return (filter, scope);
|
||||
}
|
||||
|
||||
private static List<TrendBucket> BuildTrendBuckets(string dimension, int count)
|
||||
|
||||
@ -55,6 +55,9 @@ public partial class OrderService : ApplicationService
|
||||
private EffectiveScopeBuilder DataScopeBuilder =>
|
||||
LazyServiceProvider.GetRequiredService<EffectiveScopeBuilder>();
|
||||
|
||||
private DataPermAccessAuditor DataPermAccessAuditor =>
|
||||
LazyServiceProvider.GetRequiredService<DataPermAccessAuditor>();
|
||||
|
||||
/// <summary>
|
||||
/// 查询订单列表。
|
||||
/// </summary>
|
||||
@ -63,18 +66,27 @@ public partial class OrderService : ApplicationService
|
||||
[HttpPost("/order/list")]
|
||||
public async Task<OmsPageResult<OrderOutput>> GetPaginatedListAsync([FromBody] OrderPaginatedInput input)
|
||||
{
|
||||
var timer = DataPermAccessAuditor.StartTimer();
|
||||
var customerId = await OmsSessionHelper.ResolveListCustomerIdAsync(
|
||||
CustomerRepository,
|
||||
CurrentUser,
|
||||
input.CustomerId);
|
||||
var filter = BuildListFilter(input, customerId);
|
||||
await ApplyInternalOrderDataScopeAsync(filter);
|
||||
var scope = await ApplyInternalOrderDataScopeAsync(filter);
|
||||
var pageIndex = OmsDocHelper.NormalizePage(input.Page);
|
||||
var pageSize = OmsDocHelper.NormalizePageSize(input.PageSize);
|
||||
var (orders, total) = await OrderRepository.GetFilteredPagedListAsync(
|
||||
pageIndex,
|
||||
pageSize,
|
||||
filter);
|
||||
timer.Stop();
|
||||
await DataPermAccessAuditor.TryWriteAsync(
|
||||
scope,
|
||||
"/order/list",
|
||||
"POST",
|
||||
orders.Count,
|
||||
(int)timer.ElapsedMilliseconds,
|
||||
DataPermConstants.AccessLogSamplePercentList);
|
||||
return new OmsPageResult<OrderOutput>
|
||||
{
|
||||
Items = await MapOrderListOutputsAsync(orders),
|
||||
@ -91,7 +103,7 @@ public partial class OrderService : ApplicationService
|
||||
[FromQuery] DateTime? createTimeEnd = null,
|
||||
[FromQuery] string? fulfillmentType = null)
|
||||
{
|
||||
var filter = await BuildScopedListFilterAsync();
|
||||
var (filter, _) = await BuildScopedListFilterAsync();
|
||||
filter.CreateTimeStart = createTimeStart;
|
||||
filter.CreateTimeEnd = createTimeEnd;
|
||||
filter.FulfillmentType = NormalizeFulfillmentTypeFilter(fulfillmentType);
|
||||
@ -662,16 +674,25 @@ public partial class OrderService : ApplicationService
|
||||
[HttpPost("/order/export")]
|
||||
public async Task<OrderExportOutput> ExportAsync([FromBody] OrderExportInput input)
|
||||
{
|
||||
var timer = DataPermAccessAuditor.StartTimer();
|
||||
await CleanupExpiredLocalExportFilesAsync();
|
||||
var customerId = await OmsSessionHelper.ResolveListCustomerIdAsync(
|
||||
CustomerRepository,
|
||||
CurrentUser,
|
||||
null);
|
||||
var filter = BuildListFilter(input, customerId);
|
||||
await ApplyInternalOrderDataScopeAsync(filter);
|
||||
var scope = await ApplyInternalOrderDataScopeAsync(filter);
|
||||
|
||||
const int maxExportRows = 10000;
|
||||
var (orders, total) = await OrderRepository.GetFilteredPagedListAsync(1, maxExportRows, filter);
|
||||
timer.Stop();
|
||||
await DataPermAccessAuditor.TryWriteAsync(
|
||||
scope,
|
||||
"/order/export",
|
||||
"POST",
|
||||
orders.Count,
|
||||
(int)timer.ElapsedMilliseconds,
|
||||
DataPermConstants.AccessLogSamplePercentExport);
|
||||
if (total > maxExportRows)
|
||||
{
|
||||
throw new BusinessException($"导出结果超过 {maxExportRows} 条(当前 {total}),请缩小筛选条件后再导出");
|
||||
|
||||
@ -228,6 +228,53 @@ public class NoticeService : ApplicationService
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 一键清扫当前主体可见的未读通知(默认站内信)。
|
||||
/// </summary>
|
||||
[HttpPost("/system/notice/read-confirm-all")]
|
||||
public async Task<NoticeReadConfirmAllOutput> ReadConfirmAllAsync(
|
||||
[FromBody] NoticeReadConfirmAllInput? input = null)
|
||||
{
|
||||
var currentReceiverType = OmsSessionHelper.IsCustomerLogin(CurrentUser)
|
||||
? ReceiverTypeCustomer
|
||||
: ReceiverTypeUser;
|
||||
var currentReceiverId = OmsSessionHelper.ResolveMapUserId(CurrentUser);
|
||||
if (currentReceiverId <= 0)
|
||||
{
|
||||
throw new BusinessException("当前登录主体无效");
|
||||
}
|
||||
|
||||
var noticeType = string.IsNullOrWhiteSpace(input?.NoticeType)
|
||||
? NoticeTypeMessage
|
||||
: NormalizeNoticeType(input.NoticeType);
|
||||
|
||||
var myReadNoticeIds = (await NoticeReadRepository.GetListAsync(x =>
|
||||
x.ReceiverType == currentReceiverType && x.ReceiverId == currentReceiverId))
|
||||
.Select(x => x.NoticeId)
|
||||
.Distinct()
|
||||
.ToHashSet();
|
||||
|
||||
var candidates = await NoticeRepository.GetListAsync(x => x.NoticeType == noticeType);
|
||||
var unreadVisible = candidates
|
||||
.Where(x => IsVisibleToReceiver(x, currentReceiverId, currentReceiverType))
|
||||
.Where(x => !myReadNoticeIds.Contains(x.Id))
|
||||
.ToList();
|
||||
|
||||
var now = DateTime.Now;
|
||||
foreach (var notice in unreadVisible)
|
||||
{
|
||||
await NoticeReadRepository.InsertAsync(new NoticeRead
|
||||
{
|
||||
NoticeId = notice.Id,
|
||||
ReceiverType = currentReceiverType,
|
||||
ReceiverId = currentReceiverId,
|
||||
ReadTime = now
|
||||
});
|
||||
}
|
||||
|
||||
return new NoticeReadConfirmAllOutput { ClearedCount = unreadVisible.Count };
|
||||
}
|
||||
|
||||
private async Task<OmsPageResult<NoticeReceiverOptionOutput>> QueryUserReceiverOptionsAsync(
|
||||
string? keyword,
|
||||
int pageIndex,
|
||||
|
||||
Loading…
Reference in New Issue
Block a user