From 79ebe77666b27722e60e7326d4ea018e6668b7ae Mon Sep 17 00:00:00 2001 From: zzh <1368735060@qq.com> Date: Sun, 15 Nov 2026 00:07:57 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E8=90=BD=E5=9C=B0=E6=95=B0=E6=8D=AE?= =?UTF-8?q?=E6=9D=83=E9=99=90=E5=AE=A1=E8=AE=A1=E4=B8=8E=E5=85=AC=E5=91=8A?= =?UTF-8?q?=E4=B8=80=E9=94=AE=E5=B7=B2=E8=AF=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 补齐访问审计与订单/财务侧数据权限接入,并增加公告批量确认已读接口。 Co-authored-by: Cursor --- .../DataPerm/DataPermAccessAuditor.cs | 93 +++++++++++++ .../DataPerm/DataPermConstants.cs | 6 + src/Oms.Application/DataPerm/DataPermStore.cs | 125 +++++++++++++++++- .../Dtos/System/NoticeReadConfirmAllInput.cs | 15 +++ .../Dtos/System/NoticeReadConfirmAllOutput.cs | 12 ++ .../DataPerm/DataPermService.Template.cs | 39 +++++- .../Services/DataPerm/DataPermService.cs | 16 ++- .../Services/Finance/FinanceService.cs | 40 ++++-- .../Services/Orders/OrderService.Helpers.cs | 9 +- .../Services/Orders/OrderService.Monitor.cs | 2 +- .../Services/Orders/OrderService.Workplace.cs | 15 ++- .../Services/Orders/OrderService.cs | 27 +++- .../Services/System/NoticeService.cs | 47 +++++++ 13 files changed, 408 insertions(+), 38 deletions(-) create mode 100644 src/Oms.Application/DataPerm/DataPermAccessAuditor.cs create mode 100644 src/Oms.Application/Dtos/System/NoticeReadConfirmAllInput.cs create mode 100644 src/Oms.Application/Dtos/System/NoticeReadConfirmAllOutput.cs diff --git a/src/Oms.Application/DataPerm/DataPermAccessAuditor.cs b/src/Oms.Application/DataPerm/DataPermAccessAuditor.cs new file mode 100644 index 0000000..d28f1a8 --- /dev/null +++ b/src/Oms.Application/DataPerm/DataPermAccessAuditor.cs @@ -0,0 +1,93 @@ +using System.Diagnostics; +using System.Text.Json; +using Fake.DependencyInjection; +using Microsoft.AspNetCore.Http; + +namespace Oms.Application.DataPerm; + +/// +/// 数据权限访问审计:按采样率写入 data_perm_access_log,失败不影响主流程。 +/// +public class DataPermAccessAuditor( + DataPermStore store, + IHttpContextAccessor httpContextAccessor) : IScopedDependency +{ + private static readonly JsonSerializerOptions JsonOptions = new() + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase + }; + + /// + /// 尝试写入访问日志;采样未命中或无用户上下文时直接跳过。 + /// + 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(); +} diff --git a/src/Oms.Application/DataPerm/DataPermConstants.cs b/src/Oms.Application/DataPerm/DataPermConstants.cs index 9c07a43..7d84733 100644 --- a/src/Oms.Application/DataPerm/DataPermConstants.cs +++ b/src/Oms.Application/DataPerm/DataPermConstants.cs @@ -73,4 +73,10 @@ public static class DataPermConstants (5, "VIP4"), (6, "VIP5") ]; + + /// 订单列表等查询访问日志采样百分比(0=关闭,100=全量)。 + public const int AccessLogSamplePercentList = 10; + + /// 导出等敏感操作访问日志采样百分比。 + public const int AccessLogSamplePercentExport = 100; } diff --git a/src/Oms.Application/DataPerm/DataPermStore.cs b/src/Oms.Application/DataPerm/DataPermStore.cs index fce007d..38ffb2d 100644 --- a/src/Oms.Application/DataPerm/DataPermStore.cs +++ b/src/Oms.Application/DataPerm/DataPermStore.cs @@ -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> 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(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> 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(countSql).FirstAsync(cancellationToken); + var where = "WHERE 1=1"; + var args = new List(); + 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(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(listSql) + var items = await dbContext.Database.SqlQueryRaw(listSql, args.ToArray()) .ToListAsync(cancellationToken); return new DataPermPagedResult { @@ -693,6 +769,7 @@ public class DataPermStore(FakeRbacDbContext dbContext, DataPermContextCache cac public async Task 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 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( diff --git a/src/Oms.Application/Dtos/System/NoticeReadConfirmAllInput.cs b/src/Oms.Application/Dtos/System/NoticeReadConfirmAllInput.cs new file mode 100644 index 0000000..c6f9df9 --- /dev/null +++ b/src/Oms.Application/Dtos/System/NoticeReadConfirmAllInput.cs @@ -0,0 +1,15 @@ +using System.ComponentModel.DataAnnotations; + +namespace Oms.Application.Dtos.System; + +/// +/// 一键清扫未读入参。 +/// +public class NoticeReadConfirmAllInput +{ + /// + /// 通知类型:notice/message;默认 message。 + /// + [StringLength(16)] + public string? NoticeType { get; set; } = "message"; +} diff --git a/src/Oms.Application/Dtos/System/NoticeReadConfirmAllOutput.cs b/src/Oms.Application/Dtos/System/NoticeReadConfirmAllOutput.cs new file mode 100644 index 0000000..49c6f17 --- /dev/null +++ b/src/Oms.Application/Dtos/System/NoticeReadConfirmAllOutput.cs @@ -0,0 +1,12 @@ +namespace Oms.Application.Dtos.System; + +/// +/// 一键清扫未读结果。 +/// +public class NoticeReadConfirmAllOutput +{ + /// + /// 本次新标记为已读的条数。 + /// + public int ClearedCount { get; set; } +} diff --git a/src/Oms.Application/Services/DataPerm/DataPermService.Template.cs b/src/Oms.Application/Services/DataPerm/DataPermService.Template.cs index 286e931..3354769 100644 --- a/src/Oms.Application/Services/DataPerm/DataPermService.Template.cs +++ b/src/Oms.Application/Services/DataPerm/DataPermService.Template.cs @@ -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); } /// @@ -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); } /// @@ -64,7 +69,7 @@ public partial class DataPermService /// [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); /// /// 应用数据权限模板 @@ -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; } diff --git a/src/Oms.Application/Services/DataPerm/DataPermService.cs b/src/Oms.Application/Services/DataPerm/DataPermService.cs index 31f0e68..18cc274 100644 --- a/src/Oms.Application/Services/DataPerm/DataPermService.cs +++ b/src/Oms.Application/Services/DataPerm/DataPermService.cs @@ -291,12 +291,14 @@ public partial class DataPermService : ApplicationService } /// - /// 分页查询变更日志 + /// 分页查询配置变更日志(用户/角色/模板)。 /// [HttpGet("/rbac/data-perm/change-log/list")] public Task> 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); } /// - /// 分页查询访问日志 + /// 分页查询数据访问日志(订单列表等采样写入)。 /// [HttpGet("/rbac/data-perm/access-log/list")] public Task> 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); diff --git a/src/Oms.Application/Services/Finance/FinanceService.cs b/src/Oms.Application/Services/Finance/FinanceService.cs index 04142c2..5bec82d 100644 --- a/src/Oms.Application/Services/Finance/FinanceService.cs +++ b/src/Oms.Application/Services/Finance/FinanceService.cs @@ -40,6 +40,9 @@ public class FinanceService : ApplicationService private EffectiveScopeBuilder DataScopeBuilder => LazyServiceProvider.GetRequiredService(); + private DataPermAccessAuditor DataPermAccessAuditor => + LazyServiceProvider.GetRequiredService(); + /// /// 分页查询应收应付(订单费用联查订单)。 /// @@ -47,13 +50,22 @@ public class FinanceService : ApplicationService public async Task> 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 @@ -70,7 +82,7 @@ public class FinanceService : ApplicationService public async Task 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 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 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> MapReceivablePayableRowsAsync( @@ -284,21 +305,22 @@ public class FinanceService : ApplicationService }; } - private async Task ApplyInternalOrderDataScopeAsync(OrderReceivablePayableFilter filter) + private async Task 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) => diff --git a/src/Oms.Application/Services/Orders/OrderService.Helpers.cs b/src/Oms.Application/Services/Orders/OrderService.Helpers.cs index a3d5ca0..26ba52f 100644 --- a/src/Oms.Application/Services/Orders/OrderService.Helpers.cs +++ b/src/Oms.Application/Services/Orders/OrderService.Helpers.cs @@ -1201,27 +1201,28 @@ public partial class OrderService }; } - private async Task ApplyInternalOrderDataScopeAsync(OrderListFilter filter) + private async Task 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; } /// diff --git a/src/Oms.Application/Services/Orders/OrderService.Monitor.cs b/src/Oms.Application/Services/Orders/OrderService.Monitor.cs index f5a04fc..9bf97e5 100644 --- a/src/Oms.Application/Services/Orders/OrderService.Monitor.cs +++ b/src/Oms.Application/Services/Orders/OrderService.Monitor.cs @@ -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); diff --git a/src/Oms.Application/Services/Orders/OrderService.Workplace.cs b/src/Oms.Application/Services/Orders/OrderService.Workplace.cs index 2bc46b5..3c3ee54 100644 --- a/src/Oms.Application/Services/Orders/OrderService.Workplace.cs +++ b/src/Oms.Application/Services/Orders/OrderService.Workplace.cs @@ -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 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(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(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 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 BuildTrendBuckets(string dimension, int count) diff --git a/src/Oms.Application/Services/Orders/OrderService.cs b/src/Oms.Application/Services/Orders/OrderService.cs index a57fe50..edb4ef4 100644 --- a/src/Oms.Application/Services/Orders/OrderService.cs +++ b/src/Oms.Application/Services/Orders/OrderService.cs @@ -55,6 +55,9 @@ public partial class OrderService : ApplicationService private EffectiveScopeBuilder DataScopeBuilder => LazyServiceProvider.GetRequiredService(); + private DataPermAccessAuditor DataPermAccessAuditor => + LazyServiceProvider.GetRequiredService(); + /// /// 查询订单列表。 /// @@ -63,18 +66,27 @@ public partial class OrderService : ApplicationService [HttpPost("/order/list")] public async Task> 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 { 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 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}),请缩小筛选条件后再导出"); diff --git a/src/Oms.Application/Services/System/NoticeService.cs b/src/Oms.Application/Services/System/NoticeService.cs index e3238b6..246f7b5 100644 --- a/src/Oms.Application/Services/System/NoticeService.cs +++ b/src/Oms.Application/Services/System/NoticeService.cs @@ -228,6 +228,53 @@ public class NoticeService : ApplicationService }); } + /// + /// 一键清扫当前主体可见的未读通知(默认站内信)。 + /// + [HttpPost("/system/notice/read-confirm-all")] + public async Task 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> QueryUserReceiverOptionsAsync( string? keyword, int pageIndex,