feat: 落地数据权限审计与公告一键已读
All checks were successful
Build and Deploy / deploy (push) Successful in 1m23s

补齐访问审计与订单/财务侧数据权限接入,并增加公告批量确认已读接口。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
zzh 2026-11-15 00:07:57 +08:00
parent d8f6a5c2b9
commit 79ebe77666
13 changed files with 408 additions and 38 deletions

View 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();
}

View File

@ -73,4 +73,10 @@ public static class DataPermConstants
(5, "VIP4"), (5, "VIP4"),
(6, "VIP5") (6, "VIP5")
]; ];
/// <summary>订单列表等查询访问日志采样百分比(0=关闭,100=全量)。</summary>
public const int AccessLogSamplePercentList = 10;
/// <summary>导出等敏感操作访问日志采样百分比。</summary>
public const int AccessLogSamplePercentExport = 100;
} }

View File

@ -478,9 +478,42 @@ public class DataPermStore(FakeRbacDbContext dbContext, DataPermContextCache cac
cancellationToken); 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( public async Task<DataPermPagedResult<ChangeLogItemDto>> GetChangeLogsAsync(
string? targetType, string? targetType,
string? targetId, string? targetId,
DateTime? startTime,
DateTime? endTime,
int page, int page,
int pageSize, int pageSize,
CancellationToken cancellationToken = default) CancellationToken cancellationToken = default)
@ -499,6 +532,18 @@ public class DataPermStore(FakeRbacDbContext dbContext, DataPermContextCache cac
args.Add(targetId.Trim()); 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 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 total = await dbContext.Database.SqlQueryRaw<long>(countSql, args.ToArray()).FirstAsync(cancellationToken);
var offset = Math.Max(page - 1, 0) * pageSize; 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( public async Task<DataPermPagedResult<AccessLogItemDto>> GetAccessLogsAsync(
string? userId,
string? dataResourceCode,
DateTime? startTime,
DateTime? endTime,
int page, int page,
int pageSize, int pageSize,
CancellationToken cancellationToken = default) CancellationToken cancellationToken = default)
{ {
const string countSql = "SELECT COUNT(*) AS `Value` FROM `data_perm_access_log`"; var where = "WHERE 1=1";
var total = await dbContext.Database.SqlQueryRaw<long>(countSql).FirstAsync(cancellationToken); 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 offset = Math.Max(page - 1, 0) * pageSize;
var listSql = $""" var listSql = $"""
SELECT l.`Id` AS `Id`, l.`UserId` AS `UserId`, l.`DataResourceCode` AS `DataResourceCode`, 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` l.`ApiPath` AS `ApiPath`, l.`RowCount` AS `RowCount`, l.`CreateTime` AS `CreateTime`
FROM `data_perm_access_log` l FROM `data_perm_access_log` l
{where}
ORDER BY l.`CreateTime` DESC ORDER BY l.`CreateTime` DESC
LIMIT {pageSize} OFFSET {offset} LIMIT {pageSize} OFFSET {offset}
"""; """;
var items = await dbContext.Database.SqlQueryRaw<AccessLogRow>(listSql) var items = await dbContext.Database.SqlQueryRaw<AccessLogRow>(listSql, args.ToArray())
.ToListAsync(cancellationToken); .ToListAsync(cancellationToken);
return new DataPermPagedResult<AccessLogItemDto> return new DataPermPagedResult<AccessLogItemDto>
{ {
@ -693,6 +769,7 @@ public class DataPermStore(FakeRbacDbContext dbContext, DataPermContextCache cac
public async Task<DataPermTemplateDetailDto> CreateTemplateAsync( public async Task<DataPermTemplateDetailDto> CreateTemplateAsync(
DataPermTemplateSaveInput input, DataPermTemplateSaveInput input,
Guid operatorUserId,
int operatorMapId, int operatorMapId,
CancellationToken cancellationToken = default) CancellationToken cancellationToken = default)
{ {
@ -706,12 +783,23 @@ public class DataPermStore(FakeRbacDbContext dbContext, DataPermContextCache cac
cancellationToken); cancellationToken);
await ReplaceTemplateItemsAsync(id, input.Items, 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( public async Task<DataPermTemplateDetailDto> UpdateTemplateAsync(
Guid templateId, Guid templateId,
DataPermTemplateSaveInput input, DataPermTemplateSaveInput input,
Guid operatorUserId,
int operatorMapId, int operatorMapId,
CancellationToken cancellationToken = default) CancellationToken cancellationToken = default)
{ {
@ -721,6 +809,7 @@ public class DataPermStore(FakeRbacDbContext dbContext, DataPermContextCache cac
throw new BusinessException("内置模板不可修改编码"); throw new BusinessException("内置模板不可修改编码");
} }
var beforeJson = JsonSerializer.Serialize(existing, JsonOptions);
await dbContext.Database.ExecuteSqlRawAsync(""" await dbContext.Database.ExecuteSqlRawAsync("""
UPDATE `data_perm_template` UPDATE `data_perm_template`
SET `Name` = {0}, `Description` = {1}, `RoleCode` = {2}, `UpdateUserId` = {3}, `UpdateTime` = UTC_TIMESTAMP() SET `Name` = {0}, `Description` = {1}, `RoleCode` = {2}, `UpdateUserId` = {3}, `UpdateTime` = UTC_TIMESTAMP()
@ -730,10 +819,24 @@ public class DataPermStore(FakeRbacDbContext dbContext, DataPermContextCache cac
cancellationToken); cancellationToken);
await ReplaceTemplateItemsAsync(templateId, input.Items, 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); var existing = await GetTemplateDetailAsync(templateId, cancellationToken);
if (existing.IsBuiltIn) if (existing.IsBuiltIn)
@ -741,6 +844,7 @@ public class DataPermStore(FakeRbacDbContext dbContext, DataPermContextCache cac
throw new BusinessException("内置模板不可删除"); throw new BusinessException("内置模板不可删除");
} }
var beforeJson = JsonSerializer.Serialize(existing, JsonOptions);
await dbContext.Database.ExecuteSqlRawAsync( await dbContext.Database.ExecuteSqlRawAsync(
"UPDATE `data_perm_template` SET `IsDeleted` = 1, `UpdateTime` = UTC_TIMESTAMP() WHERE `Id` = {0}", "UPDATE `data_perm_template` SET `IsDeleted` = 1, `UpdateTime` = UTC_TIMESTAMP() WHERE `Id` = {0}",
[templateId.ToString()], [templateId.ToString()],
@ -749,6 +853,15 @@ public class DataPermStore(FakeRbacDbContext dbContext, DataPermContextCache cac
"UPDATE `data_perm_template_item` SET `IsDeleted` = 1 WHERE `TemplateId` = {0}", "UPDATE `data_perm_template_item` SET `IsDeleted` = 1 WHERE `TemplateId` = {0}",
[templateId.ToString()], [templateId.ToString()],
cancellationToken); cancellationToken);
await InsertChangeLogAsync(
"template",
templateId.ToString(),
"delete",
beforeJson,
null,
operatorUserId,
operatorMapId,
cancellationToken);
} }
private async Task ReplaceTemplateItemsAsync( private async Task ReplaceTemplateItemsAsync(

View 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";
}

View File

@ -0,0 +1,12 @@
namespace Oms.Application.Dtos.System;
/// <summary>
/// 一键清扫未读结果。
/// </summary>
public class NoticeReadConfirmAllOutput
{
/// <summary>
/// 本次新标记为已读的条数。
/// </summary>
public int ClearedCount { get; set; }
}

View File

@ -43,7 +43,7 @@ public partial class DataPermService
CancellationToken cancellationToken = default) CancellationToken cancellationToken = default)
{ {
ValidateTemplateInput(input); ValidateTemplateInput(input);
return Store.CreateTemplateAsync(input, GetCurrentMapId(), cancellationToken); return Store.CreateTemplateAsync(input, GetCurrentUserGuid(), GetCurrentMapId(), cancellationToken);
} }
/// <summary> /// <summary>
@ -56,7 +56,12 @@ public partial class DataPermService
CancellationToken cancellationToken = default) CancellationToken cancellationToken = default)
{ {
ValidateTemplateInput(input); ValidateTemplateInput(input);
return Store.UpdateTemplateAsync(ParseGuid(id, "id"), input, GetCurrentMapId(), cancellationToken); return Store.UpdateTemplateAsync(
ParseGuid(id, "id"),
input,
GetCurrentUserGuid(),
GetCurrentMapId(),
cancellationToken);
} }
/// <summary> /// <summary>
@ -64,7 +69,7 @@ public partial class DataPermService
/// </summary> /// </summary>
[HttpDelete("/rbac/data-perm/template/delete")] [HttpDelete("/rbac/data-perm/template/delete")]
public Task DeleteTemplateAsync([FromQuery] string id, CancellationToken cancellationToken = default) => public Task DeleteTemplateAsync([FromQuery] string id, CancellationToken cancellationToken = default) =>
Store.DeleteTemplateAsync(ParseGuid(id, "id"), cancellationToken); Store.DeleteTemplateAsync(ParseGuid(id, "id"), GetCurrentUserGuid(), GetCurrentMapId(), cancellationToken);
/// <summary> /// <summary>
/// 应用数据权限模板 /// 应用数据权限模板
@ -74,9 +79,12 @@ public partial class DataPermService
[FromBody] TemplateApplyInput input, [FromBody] TemplateApplyInput input,
CancellationToken cancellationToken = default) 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 bundle = TemplateBundleParser.Parse(template.Items);
var result = new TemplateApplyResultDto(); var result = new TemplateApplyResultDto();
var operatorUserId = GetCurrentUserGuid();
var operatorMapId = GetCurrentMapId();
foreach (var targetIdRaw in input.TargetIds.Distinct(StringComparer.OrdinalIgnoreCase)) foreach (var targetIdRaw in input.TargetIds.Distinct(StringComparer.OrdinalIgnoreCase))
{ {
@ -87,7 +95,7 @@ public partial class DataPermService
var roleId = ParseGuid(targetIdRaw, "targetId"); var roleId = ParseGuid(targetIdRaw, "targetId");
var current = await Store.GetRoleDataPermAsync(roleId, cancellationToken); var current = await Store.GetRoleDataPermAsync(roleId, cancellationToken);
var merged = MergeRoleBundle(current, bundle, input); 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 else
{ {
@ -101,7 +109,7 @@ public partial class DataPermService
var merged = MergeUserBundle(current, bundle, input); var merged = MergeUserBundle(current, bundle, input);
DataPermSaveValidator.Validate(merged, Repository); DataPermSaveValidator.Validate(merged, Repository);
await DataPermSaveValidator.ValidateOrganizationsExistAsync(merged, Repository, cancellationToken); await DataPermSaveValidator.ValidateOrganizationsExistAsync(merged, Repository, cancellationToken);
await Store.SaveUserDataPermAsync(userId, merged, GetCurrentUserGuid(), GetCurrentMapId(), cancellationToken); await Store.SaveUserDataPermAsync(userId, merged, operatorUserId, operatorMapId, cancellationToken);
} }
result.SuccessCount++; 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; return result;
} }

View File

@ -291,12 +291,14 @@ public partial class DataPermService : ApplicationService
} }
/// <summary> /// <summary>
/// 分页查询变更日志 /// 分页查询配置变更日志(用户/角色/模板)。
/// </summary> /// </summary>
[HttpGet("/rbac/data-perm/change-log/list")] [HttpGet("/rbac/data-perm/change-log/list")]
public Task<DataPermPagedResult<ChangeLogItemDto>> GetChangeLogListAsync( public Task<DataPermPagedResult<ChangeLogItemDto>> GetChangeLogListAsync(
[FromQuery] string? targetType, [FromQuery] string? targetType,
[FromQuery] string? targetId, [FromQuery] string? targetId,
[FromQuery] DateTime? startTime = null,
[FromQuery] DateTime? endTime = null,
[FromQuery] int page = 1, [FromQuery] int page = 1,
[FromQuery] int pageSize = 30, [FromQuery] int pageSize = 30,
CancellationToken cancellationToken = default) CancellationToken cancellationToken = default)
@ -304,21 +306,31 @@ public partial class DataPermService : ApplicationService
return Store.GetChangeLogsAsync( return Store.GetChangeLogsAsync(
targetType, targetType,
targetId, targetId,
startTime,
endTime,
OmsDocHelper.NormalizePage(page), OmsDocHelper.NormalizePage(page),
OmsDocHelper.NormalizePageSize(pageSize), OmsDocHelper.NormalizePageSize(pageSize),
cancellationToken); cancellationToken);
} }
/// <summary> /// <summary>
/// 分页查询访问日志 /// 分页查询数据访问日志(订单列表等采样写入)。
/// </summary> /// </summary>
[HttpGet("/rbac/data-perm/access-log/list")] [HttpGet("/rbac/data-perm/access-log/list")]
public Task<DataPermPagedResult<AccessLogItemDto>> GetAccessLogListAsync( 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 page = 1,
[FromQuery] int pageSize = 30, [FromQuery] int pageSize = 30,
CancellationToken cancellationToken = default) CancellationToken cancellationToken = default)
{ {
return Store.GetAccessLogsAsync( return Store.GetAccessLogsAsync(
userId,
dataResourceCode,
startTime,
endTime,
OmsDocHelper.NormalizePage(page), OmsDocHelper.NormalizePage(page),
OmsDocHelper.NormalizePageSize(pageSize), OmsDocHelper.NormalizePageSize(pageSize),
cancellationToken); cancellationToken);

View File

@ -40,6 +40,9 @@ public class FinanceService : ApplicationService
private EffectiveScopeBuilder DataScopeBuilder => private EffectiveScopeBuilder DataScopeBuilder =>
LazyServiceProvider.GetRequiredService<EffectiveScopeBuilder>(); LazyServiceProvider.GetRequiredService<EffectiveScopeBuilder>();
private DataPermAccessAuditor DataPermAccessAuditor =>
LazyServiceProvider.GetRequiredService<DataPermAccessAuditor>();
/// <summary> /// <summary>
/// 分页查询应收应付(订单费用联查订单)。 /// 分页查询应收应付(订单费用联查订单)。
/// </summary> /// </summary>
@ -47,13 +50,22 @@ public class FinanceService : ApplicationService
public async Task<OmsPageResult<ReceivablePayablePaginatedOutput>> GetReceivablePayableListAsync( public async Task<OmsPageResult<ReceivablePayablePaginatedOutput>> GetReceivablePayableListAsync(
[FromQuery] ReceivablePayablePaginatedInput input) [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 pageIndex = OmsDocHelper.NormalizePage(input.Page);
var pageSize = OmsDocHelper.NormalizePageSize(input.PageSize); var pageSize = OmsDocHelper.NormalizePageSize(input.PageSize);
var (rows, total) = await OrderRepository.GetReceivablePayablePagedListAsync( var (rows, total) = await OrderRepository.GetReceivablePayablePagedListAsync(
pageIndex, pageIndex,
pageSize, pageSize,
filter); filter);
timer.Stop();
await DataPermAccessAuditor.TryWriteAsync(
scope,
"/finance/receivable-payable/list",
"GET",
rows.Count,
(int)timer.ElapsedMilliseconds,
DataPermConstants.AccessLogSamplePercentList);
var items = await MapReceivablePayableRowsAsync(rows); var items = await MapReceivablePayableRowsAsync(rows);
return new OmsPageResult<ReceivablePayablePaginatedOutput> return new OmsPageResult<ReceivablePayablePaginatedOutput>
@ -70,7 +82,7 @@ public class FinanceService : ApplicationService
public async Task<ReceivablePayableSummaryOutput> GetReceivablePayableSummaryAsync( public async Task<ReceivablePayableSummaryOutput> GetReceivablePayableSummaryAsync(
[FromQuery] ReceivablePayablePaginatedInput input) [FromQuery] ReceivablePayablePaginatedInput input)
{ {
var filter = await BuildScopedFilterAsync(input); var (filter, _) = await BuildScopedFilterAsync(input);
var rows = await OrderRepository.GetReceivablePayableSummaryAsync(filter); var rows = await OrderRepository.GetReceivablePayableSummaryAsync(filter);
var items = rows var items = rows
.Select(row => new ReceivablePayableSummaryItemOutput .Select(row => new ReceivablePayableSummaryItemOutput
@ -99,8 +111,17 @@ public class FinanceService : ApplicationService
public async Task<FileContentResult> ExportReceivablePayableAsync( public async Task<FileContentResult> ExportReceivablePayableAsync(
[FromQuery] ReceivablePayablePaginatedInput input) [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); 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 items = await MapReceivablePayableRowsAsync(rows);
var exportRows = items.Select(item => new 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) ReceivablePayablePaginatedInput input)
{ {
var customerId = await OmsSessionHelper.ResolveListCustomerIdAsync( var customerId = await OmsSessionHelper.ResolveListCustomerIdAsync(
@ -145,8 +166,8 @@ public class FinanceService : ApplicationService
CurrentUser, CurrentUser,
input.CustomerId); input.CustomerId);
var filter = BuildFilter(input, customerId); var filter = BuildFilter(input, customerId);
await ApplyInternalOrderDataScopeAsync(filter); var scope = await ApplyInternalOrderDataScopeAsync(filter);
return filter; return (filter, scope);
} }
private async Task<List<ReceivablePayablePaginatedOutput>> MapReceivablePayableRowsAsync( 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)) if (OmsSessionHelper.IsCustomerLogin(CurrentUser))
{ {
return; return null;
} }
var userGuidRaw = CurrentUser.FindClaimValueOrNull(global::System.Security.Claims.ClaimTypes.NameIdentifier); var userGuidRaw = CurrentUser.FindClaimValueOrNull(global::System.Security.Claims.ClaimTypes.NameIdentifier);
if (string.IsNullOrWhiteSpace(userGuidRaw) || !Guid.TryParse(userGuidRaw, out var userGuid)) if (string.IsNullOrWhiteSpace(userGuidRaw) || !Guid.TryParse(userGuidRaw, out var userGuid))
{ {
return; return null;
} }
var context = await DataScopeBuilder.BuildAsync(userGuid, DataScopeApplier.OrderResourceCode); var context = await DataScopeBuilder.BuildAsync(userGuid, DataScopeApplier.OrderResourceCode);
DataScopeApplier.ApplyToOrderListFilter(filter, context); DataScopeApplier.ApplyToOrderListFilter(filter, context);
return context;
} }
private static string GetFeeTypeName(string feeType) => private static string GetFeeTypeName(string feeType) =>

View File

@ -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)) if (OmsSessionHelper.IsCustomerLogin(CurrentUser))
{ {
return; return null;
} }
if (OmsSessionHelper.IsAgentLogin(CurrentUser)) if (OmsSessionHelper.IsAgentLogin(CurrentUser))
{ {
await ApplyAgentOrderScopeAsync(filter); await ApplyAgentOrderScopeAsync(filter);
return; return null;
} }
var userGuidRaw = CurrentUser.FindClaimValueOrNull(global::System.Security.Claims.ClaimTypes.NameIdentifier); var userGuidRaw = CurrentUser.FindClaimValueOrNull(global::System.Security.Claims.ClaimTypes.NameIdentifier);
if (string.IsNullOrWhiteSpace(userGuidRaw) || !Guid.TryParse(userGuidRaw, out var userGuid)) if (string.IsNullOrWhiteSpace(userGuidRaw) || !Guid.TryParse(userGuidRaw, out var userGuid))
{ {
return; return null;
} }
var context = await DataScopeBuilder.BuildAsync(userGuid, DataScopeApplier.OrderResourceCode); var context = await DataScopeBuilder.BuildAsync(userGuid, DataScopeApplier.OrderResourceCode);
DataScopeApplier.ApplyToOrderListFilter(filter, context); DataScopeApplier.ApplyToOrderListFilter(filter, context);
return context;
} }
/// <summary> /// <summary>

View File

@ -18,7 +18,7 @@ public partial class OrderService
[FromQuery] string? dimension = "day") [FromQuery] string? dimension = "day")
{ {
var dim = NormalizeMonitorDimension(dimension); var dim = NormalizeMonitorDimension(dimension);
var filter = await BuildScopedListFilterAsync(); var (filter, _) = await BuildScopedListFilterAsync();
var today = DateTime.Today; var today = DateTime.Today;
var tomorrow = today.AddDays(1); var tomorrow = today.AddDays(1);
var yesterday = today.AddDays(-1); var yesterday = today.AddDays(-1);

View File

@ -1,4 +1,5 @@
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Oms.Application.DataPerm;
using Oms.Application.Dtos.Orders; using Oms.Application.Dtos.Orders;
using Oms.Application.Shared; using Oms.Application.Shared;
using Oms.Domain.OrdersAggregate; using Oms.Domain.OrdersAggregate;
@ -22,7 +23,7 @@ public partial class OrderService
[HttpGet("/order/workplace-stats")] [HttpGet("/order/workplace-stats")]
public async Task<OrderWorkplaceStatsOutput> GetWorkplaceStatsAsync() public async Task<OrderWorkplaceStatsOutput> GetWorkplaceStatsAsync()
{ {
var filter = await BuildScopedListFilterAsync(); var (filter, _) = await BuildScopedListFilterAsync();
var rows = await OrderRepository.GetStatusCountsByFilterAsync(filter); var rows = await OrderRepository.GetStatusCountsByFilterAsync(filter);
var counts = rows var counts = rows
.Where(x => !string.Equals(x.Status, OrderStatusCodes.Deleted, StringComparison.OrdinalIgnoreCase)) .Where(x => !string.Equals(x.Status, OrderStatusCodes.Deleted, StringComparison.OrdinalIgnoreCase))
@ -136,7 +137,7 @@ public partial class OrderService
_ => Math.Clamp(count, 1, 31), _ => Math.Clamp(count, 1, 31),
}; };
var filter = await BuildScopedListFilterAsync(); var (filter, _) = await BuildScopedListFilterAsync();
var buckets = BuildTrendBuckets(dim, count); var buckets = BuildTrendBuckets(dim, count);
var points = new List<OrderWorkplaceTrendPointOutput>(buckets.Count); var points = new List<OrderWorkplaceTrendPointOutput>(buckets.Count);
@ -187,7 +188,7 @@ public partial class OrderService
_ => Math.Clamp(count, 1, 31), _ => Math.Clamp(count, 1, 31),
}; };
var filter = await BuildScopedListFilterAsync(); var (filter, _) = await BuildScopedListFilterAsync();
var buckets = BuildTrendBuckets(dim, count); var buckets = BuildTrendBuckets(dim, count);
var points = new List<OrderWorkplaceSpendTrendPointOutput>(buckets.Count); var points = new List<OrderWorkplaceSpendTrendPointOutput>(buckets.Count);
@ -252,7 +253,7 @@ public partial class OrderService
_ => Math.Clamp(count, 1, 31), _ => Math.Clamp(count, 1, 31),
}; };
var filter = await BuildScopedListFilterAsync(); var (filter, _) = await BuildScopedListFilterAsync();
var fulfillFilter = CloneScopedFilter(filter); var fulfillFilter = CloneScopedFilter(filter);
fulfillFilter.FulfillmentType = FulfillmentTypeCodes.Warehouse; fulfillFilter.FulfillmentType = FulfillmentTypeCodes.Warehouse;
@ -304,15 +305,15 @@ public partial class OrderService
ScopeCustomFilters = filter.ScopeCustomFilters, ScopeCustomFilters = filter.ScopeCustomFilters,
}; };
private async Task<OrderListFilter> BuildScopedListFilterAsync() private async Task<(OrderListFilter Filter, DataScopeContext? Scope)> BuildScopedListFilterAsync()
{ {
var customerId = await OmsSessionHelper.ResolveListCustomerIdAsync( var customerId = await OmsSessionHelper.ResolveListCustomerIdAsync(
CustomerRepository, CustomerRepository,
CurrentUser, CurrentUser,
null); null);
var filter = new OrderListFilter { CustomerId = customerId }; var filter = new OrderListFilter { CustomerId = customerId };
await ApplyInternalOrderDataScopeAsync(filter); var scope = await ApplyInternalOrderDataScopeAsync(filter);
return filter; return (filter, scope);
} }
private static List<TrendBucket> BuildTrendBuckets(string dimension, int count) private static List<TrendBucket> BuildTrendBuckets(string dimension, int count)

View File

@ -55,6 +55,9 @@ public partial class OrderService : ApplicationService
private EffectiveScopeBuilder DataScopeBuilder => private EffectiveScopeBuilder DataScopeBuilder =>
LazyServiceProvider.GetRequiredService<EffectiveScopeBuilder>(); LazyServiceProvider.GetRequiredService<EffectiveScopeBuilder>();
private DataPermAccessAuditor DataPermAccessAuditor =>
LazyServiceProvider.GetRequiredService<DataPermAccessAuditor>();
/// <summary> /// <summary>
/// 查询订单列表。 /// 查询订单列表。
/// </summary> /// </summary>
@ -63,18 +66,27 @@ public partial class OrderService : ApplicationService
[HttpPost("/order/list")] [HttpPost("/order/list")]
public async Task<OmsPageResult<OrderOutput>> GetPaginatedListAsync([FromBody] OrderPaginatedInput input) public async Task<OmsPageResult<OrderOutput>> GetPaginatedListAsync([FromBody] OrderPaginatedInput input)
{ {
var timer = DataPermAccessAuditor.StartTimer();
var customerId = await OmsSessionHelper.ResolveListCustomerIdAsync( var customerId = await OmsSessionHelper.ResolveListCustomerIdAsync(
CustomerRepository, CustomerRepository,
CurrentUser, CurrentUser,
input.CustomerId); input.CustomerId);
var filter = BuildListFilter(input, customerId); var filter = BuildListFilter(input, customerId);
await ApplyInternalOrderDataScopeAsync(filter); var scope = await ApplyInternalOrderDataScopeAsync(filter);
var pageIndex = OmsDocHelper.NormalizePage(input.Page); var pageIndex = OmsDocHelper.NormalizePage(input.Page);
var pageSize = OmsDocHelper.NormalizePageSize(input.PageSize); var pageSize = OmsDocHelper.NormalizePageSize(input.PageSize);
var (orders, total) = await OrderRepository.GetFilteredPagedListAsync( var (orders, total) = await OrderRepository.GetFilteredPagedListAsync(
pageIndex, pageIndex,
pageSize, pageSize,
filter); filter);
timer.Stop();
await DataPermAccessAuditor.TryWriteAsync(
scope,
"/order/list",
"POST",
orders.Count,
(int)timer.ElapsedMilliseconds,
DataPermConstants.AccessLogSamplePercentList);
return new OmsPageResult<OrderOutput> return new OmsPageResult<OrderOutput>
{ {
Items = await MapOrderListOutputsAsync(orders), Items = await MapOrderListOutputsAsync(orders),
@ -91,7 +103,7 @@ public partial class OrderService : ApplicationService
[FromQuery] DateTime? createTimeEnd = null, [FromQuery] DateTime? createTimeEnd = null,
[FromQuery] string? fulfillmentType = null) [FromQuery] string? fulfillmentType = null)
{ {
var filter = await BuildScopedListFilterAsync(); var (filter, _) = await BuildScopedListFilterAsync();
filter.CreateTimeStart = createTimeStart; filter.CreateTimeStart = createTimeStart;
filter.CreateTimeEnd = createTimeEnd; filter.CreateTimeEnd = createTimeEnd;
filter.FulfillmentType = NormalizeFulfillmentTypeFilter(fulfillmentType); filter.FulfillmentType = NormalizeFulfillmentTypeFilter(fulfillmentType);
@ -662,16 +674,25 @@ public partial class OrderService : ApplicationService
[HttpPost("/order/export")] [HttpPost("/order/export")]
public async Task<OrderExportOutput> ExportAsync([FromBody] OrderExportInput input) public async Task<OrderExportOutput> ExportAsync([FromBody] OrderExportInput input)
{ {
var timer = DataPermAccessAuditor.StartTimer();
await CleanupExpiredLocalExportFilesAsync(); await CleanupExpiredLocalExportFilesAsync();
var customerId = await OmsSessionHelper.ResolveListCustomerIdAsync( var customerId = await OmsSessionHelper.ResolveListCustomerIdAsync(
CustomerRepository, CustomerRepository,
CurrentUser, CurrentUser,
null); null);
var filter = BuildListFilter(input, customerId); var filter = BuildListFilter(input, customerId);
await ApplyInternalOrderDataScopeAsync(filter); var scope = await ApplyInternalOrderDataScopeAsync(filter);
const int maxExportRows = 10000; const int maxExportRows = 10000;
var (orders, total) = await OrderRepository.GetFilteredPagedListAsync(1, maxExportRows, filter); 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) if (total > maxExportRows)
{ {
throw new BusinessException($"导出结果超过 {maxExportRows} 条(当前 {total}),请缩小筛选条件后再导出"); throw new BusinessException($"导出结果超过 {maxExportRows} 条(当前 {total}),请缩小筛选条件后再导出");

View File

@ -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( private async Task<OmsPageResult<NoticeReceiverOptionOutput>> QueryUserReceiverOptionsAsync(
string? keyword, string? keyword,
int pageIndex, int pageIndex,