diff --git a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/Dtos/UsAppLabeling/UsAppLabelPreviewDto.cs b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/Dtos/UsAppLabeling/UsAppLabelPreviewDto.cs index 4e2e0c3..ce77dba 100644 --- a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/Dtos/UsAppLabeling/UsAppLabelPreviewDto.cs +++ b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/Dtos/UsAppLabeling/UsAppLabelPreviewDto.cs @@ -49,8 +49,16 @@ public class UsAppLabelPreviewDto /// /// 当前预览上下文(模板+产品+标签类型)命中的默认值配置。 - /// 数据来源:fl_label_template_product_default.DefaultValuesJson + /// 数据来源:fl_label_template_product_default.DefaultValuesJson,并与标签 + /// LabelInfoJson.templateInputValues 合并(标签级优先)。 + /// Nutrition Facts 元素的值为营养成分 JSON 字符串。 /// public Dictionary? TemplateProductDefaultValues { get; set; } + + /// + /// Nutrition Facts 元素已保存的营养成分表(elementId → 字段字典)。 + /// 来源:标签 templateInputValues / 产品模板默认值中该元素对应的 JSON。 + /// + public Dictionary> NutritionByElementId { get; set; } = new(); } diff --git a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/IServices/IDashboardAppService.cs b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/IServices/IDashboardAppService.cs index c944d38..5604368 100644 --- a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/IServices/IDashboardAppService.cs +++ b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/IServices/IDashboardAppService.cs @@ -15,6 +15,7 @@ public interface IDashboardAppService : IApplicationService /// 按 Token 数据范围统计:系统管理员为全平台;其它账号仅统计其 userlocation 绑定门店所属公司范围内数据。 /// companies 统计可见 fl_partner 数;regions 统计可见 fl_group 数(与 Region 列表同一套 scope)。 /// labels 统计可见 fl_label 总数(与 Label 列表无额外筛选时同一套 scope)。 + /// activeTemplates 统计可见且启用的 fl_label_template 数(与 Label Templates 列表无额外筛选时同一套 scope)。 /// people 为注册用户数(与 Team Member 列表 TotalCount 一致);activeUsers 为其中 State=true 的用户数。 /// 系统 Admin 统计全部未删 User;非 Admin 仅统计在可见门店有 userlocation 绑定的用户。 /// recentLabels[].labelCode 为门店当日打印序号 yyyyMMdd-n,规则与 POST /api/app/us-app-labeling/preview、print-log 一致。 diff --git a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/IServices/IGroupAppService.cs b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/IServices/IGroupAppService.cs index 8224567..3a24e3f 100644 --- a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/IServices/IGroupAppService.cs +++ b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/IServices/IGroupAppService.cs @@ -44,6 +44,10 @@ public interface IGroupAppService : IApplicationService /// 若 groupName 相对原值发生变化(忽略大小写与首尾空格),会同步更新未删除门店 /// location.GroupName(精确匹配旧 Region 名称,且 location.Partner 与当前 Region 所属公司名称一致), /// 避免跨公司同名 Region 误更新。 + /// 若 State 从 true 变为 false,级联停用其下全部 Location, + /// 软删这些门店的 userlocation 绑定(不停用成员、不解绑其它门店); + /// 若存在 fl_team_member_region 则删除该 Region 的成员关联; + /// inactive→active 不自动恢复下级或绑定;已 inactive 再次保存不重复级联。 /// Task UpdateAsync(Guid id, GroupUpdateInputVo input); diff --git a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/IServices/ILocationAppService.cs b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/IServices/ILocationAppService.cs index 29a5ff0..8175da7 100644 --- a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/IServices/ILocationAppService.cs +++ b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/IServices/ILocationAppService.cs @@ -28,6 +28,10 @@ public interface ILocationAppService : IApplicationService /// /// 门店Id /// 门店信息 + /// + /// 若 State 从 true 变为 false,软删该门店的 userlocation 绑定(不停用成员); + /// inactive→active 不自动恢复绑定;已 inactive 再次保存不重复级联。批量编辑经本方法逐条处理,同样生效。 + /// Task UpdateAsync(Guid id, LocationUpdateInputVo input); /// diff --git a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/IServices/IPartnerAppService.cs b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/IServices/IPartnerAppService.cs index 77f42e4..4c7ab35 100644 --- a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/IServices/IPartnerAppService.cs +++ b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/IServices/IPartnerAppService.cs @@ -74,6 +74,9 @@ public interface IPartnerAppService : IApplicationService /// /// 若 partnerName 相对原值发生变化(忽略大小写与首尾空格),会同步更新未删除门店 /// location.Partner(精确匹配旧公司名称),以保持门店/产品/标签按名称解析的绑定关系。 + /// 若 State 从 true 变为 false,级联停用其下全部 Region、Location, + /// 并将经该公司门店 userlocation 绑定的 Team Member 设为 State=false; + /// inactive→active 不自动恢复下级或绑定;已 inactive 再次保存不重复级联。 /// /// 成功 /// 校验失败或记录不存在 diff --git a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/IServices/IUsAppLabelingAppService.cs b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/IServices/IUsAppLabelingAppService.cs index 50a50e0..a5a50f2 100644 --- a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/IServices/IUsAppLabelingAppService.cs +++ b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/IServices/IUsAppLabelingAppService.cs @@ -18,6 +18,7 @@ public interface IUsAppLabelingAppService : IApplicationService /// /// App 打印预览:按标签编码解析模板并返回顶部展示字段 + 预览模板结构。 /// 出参 labelId 为门店当日**下一个**打印序号(yyyyMMdd-n),非 fl_label.Id。 + /// 出参 nutritionByElementId / templateProductDefaultValues 含 Nutrition Facts 已保存 JSON。 /// Task PreviewAsync(UsAppLabelPreviewInputVo input); diff --git a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/AccountStructureCascadeDeleteHelper.cs b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/AccountStructureCascadeDeleteHelper.cs index 0aaafed..28ae1e0 100644 --- a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/AccountStructureCascadeDeleteHelper.cs +++ b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/AccountStructureCascadeDeleteHelper.cs @@ -204,6 +204,16 @@ public static class AccountStructureCascadeDeleteHelper } /// + /// 清理指定门店 Id 列表对应的 userlocation 绑定(逻辑删除)。 + /// + public static Task SoftDeleteUserLocationBindingsAsync( + ISqlSugarClient db, + IReadOnlyList locationIds, + DateTime now, + string? modifierId) => + SoftDeleteUserLocationBindingsCoreAsync(db, locationIds, now, modifierId); + + /// /// Region 存在下级门店且未确认级联删除时的提示文案。 /// public static string BuildGroupCascadeRequiredMessage(int locationCount) => @@ -240,7 +250,7 @@ public static class AccountStructureCascadeDeleteHelper .ExecuteCommandAsync(); } - private static async Task SoftDeleteUserLocationBindingsAsync( + private static async Task SoftDeleteUserLocationBindingsCoreAsync( ISqlSugarClient db, IReadOnlyList locationIds, DateTime now, @@ -251,11 +261,15 @@ public static class AccountStructureCascadeDeleteHelper return; } - var normalizedKeys = locationIds - .Select(g => TeamMemberListScopeHelper.NormalizeScopeKey(g.ToString("D"))) - .Where(x => !string.IsNullOrEmpty(x)) - .Distinct(StringComparer.OrdinalIgnoreCase) - .ToList(); + var normalizedKeys = new HashSet( + locationIds + .SelectMany(g => new[] + { + TeamMemberListScopeHelper.NormalizeScopeKey(g.ToString("D")), + TeamMemberListScopeHelper.NormalizeScopeKey(g.ToString("N")) + }) + .Where(x => !string.IsNullOrEmpty(x)), + StringComparer.OrdinalIgnoreCase); if (normalizedKeys.Count == 0) { @@ -268,8 +282,13 @@ public static class AccountStructureCascadeDeleteHelper .ToListAsync(); var bindingIds = bindings - .Where(x => normalizedKeys.Contains(TeamMemberListScopeHelper.NormalizeScopeKey(x.LocationId))) + .Where(x => + { + var key = TeamMemberListScopeHelper.NormalizeScopeKey(x.LocationId); + return !string.IsNullOrEmpty(key) && normalizedKeys.Contains(key); + }) .Select(x => x.Id) + .Distinct(StringComparer.OrdinalIgnoreCase) .ToList(); if (bindingIds.Count == 0) diff --git a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/AccountStructureCascadeInactiveHelper.cs b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/AccountStructureCascadeInactiveHelper.cs new file mode 100644 index 0000000..88b6d1d --- /dev/null +++ b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/AccountStructureCascadeInactiveHelper.cs @@ -0,0 +1,211 @@ +using FoodLabeling.Application.Services.DbModels; +using FoodLabeling.Domain.Entities; +using SqlSugar; +using Yi.Framework.Rbac.Domain.Entities; + +namespace FoodLabeling.Application.Helpers; + +/// +/// Account Management 结构(Company / Region / Location)停用(State=false)时的级联处理。 +/// 仅在 旧 State==true 且 新 State==false 时触发;inactive→active 不自动恢复下级或绑定。 +/// +public static class AccountStructureCascadeInactiveHelper +{ + /// + /// 判断是否从启用变为停用。 + /// + public static bool IsBecomingInactive(bool wasActive, bool newState) => wasActive && !newState; + + /// + /// Company 停用时:其下全部 Region、Location 设为 State=false; + /// 经该公司门店 userlocation 绑定的 Team Member 设为 State=false(不解绑 userlocation)。 + /// + public static async Task CascadePartnerInactiveAsync( + ISqlSugarClient db, + string partnerId, + DateTime now, + Guid? modifierId) + { + var modifierIdString = modifierId?.ToString(); + + await db.Updateable() + .SetColumns(x => new FlGroupDbEntity + { + State = false, + LastModificationTime = now, + LastModifierId = modifierIdString + }) + .Where(x => !x.IsDeleted && x.PartnerId == partnerId && x.State) + .ExecuteCommandAsync(); + + var locationIdStrings = await LocationScopeBindingHelper.ResolveLocationIdsFromPartnerIdsAsync( + db, + new[] { partnerId }); + + await DeactivateLocationsByIdsAsync(db, locationIdStrings, now, modifierId); + await DeactivateUsersBoundToLocationsAsync(db, locationIdStrings, now, modifierId); + } + + /// + /// Region 停用时:其下全部 Location 设为 State=false; + /// 软删这些门店的 userlocation 绑定(不解绑其它门店、不停用成员); + /// 若存在 fl_team_member_region 表则删除该 Region 的成员关联。 + /// + public static async Task CascadeGroupInactiveAsync( + ISqlSugarClient db, + string groupId, + DateTime now, + Guid? modifierId, + string? userLocationModifierId) + { + var locationIdStrings = await LocationScopeBindingHelper.ResolveLocationIdsFromGroupIdsAsync( + db, + new[] { groupId }); + + await DeactivateLocationsByIdsAsync(db, locationIdStrings, now, modifierId); + + var locationGuids = ParseLocationGuids(locationIdStrings); + if (locationGuids.Count > 0) + { + await AccountStructureCascadeDeleteHelper.SoftDeleteUserLocationBindingsAsync( + db, + locationGuids, + now, + userLocationModifierId); + } + + await TryDeleteTeamMemberRegionByGroupIdAsync(db, groupId); + } + + /// + /// Location 停用时:软删该门店的 userlocation 绑定(不停用成员)。 + /// + public static Task CascadeLocationInactiveAsync( + ISqlSugarClient db, + Guid locationId, + DateTime now, + string? userLocationModifierId) => + AccountStructureCascadeDeleteHelper.SoftDeleteUserLocationBindingsForLocationAsync( + db, + locationId, + now, + userLocationModifierId); + + private static async Task DeactivateLocationsByIdsAsync( + ISqlSugarClient db, + IReadOnlyList locationIdStrings, + DateTime now, + Guid? modifierId) + { + var locationGuids = ParseLocationGuids(locationIdStrings); + if (locationGuids.Count == 0) + { + return; + } + + await db.Updateable() + .SetColumns(x => new LocationAggregateRoot + { + State = false, + LastModificationTime = now, + LastModifierId = modifierId + }) + .Where(x => !x.IsDeleted && locationGuids.Contains(x.Id) && x.State) + .ExecuteCommandAsync(); + } + + private static async Task DeactivateUsersBoundToLocationsAsync( + ISqlSugarClient db, + IReadOnlyList locationIdStrings, + DateTime now, + Guid? modifierId) + { + var userIds = await ResolveUserIdsBoundToLocationIdsAsync(db, locationIdStrings); + if (userIds.Count == 0) + { + return; + } + + await db.Updateable() + .SetColumns(x => new UserAggregateRoot + { + State = false, + LastModificationTime = now, + LastModifierId = modifierId + }) + .Where(x => !x.IsDeleted && x.State && userIds.Contains(x.Id)) + .ExecuteCommandAsync(); + } + + private static async Task> ResolveUserIdsBoundToLocationIdsAsync( + ISqlSugarClient db, + IReadOnlyList locationIdStrings) + { + var normalizedKeys = new HashSet( + locationIdStrings + .Select(id => TeamMemberListScopeHelper.NormalizeScopeKey(id)) + .Where(x => !string.IsNullOrEmpty(x)), + StringComparer.OrdinalIgnoreCase); + + if (normalizedKeys.Count == 0) + { + return new List(); + } + + var bindings = await db.Queryable() + .Where(x => !x.IsDeleted) + .Select(x => new { x.UserId, x.LocationId }) + .ToListAsync(); + + var userIdStrings = bindings + .Where(x => normalizedKeys.Contains(TeamMemberListScopeHelper.NormalizeScopeKey(x.LocationId))) + .Select(x => x.UserId) + .Where(x => !string.IsNullOrWhiteSpace(x)) + .Distinct(StringComparer.OrdinalIgnoreCase) + .ToList(); + + var result = new List(); + foreach (var uid in userIdStrings) + { + if (Guid.TryParse(uid.Trim(), out var guid)) + { + result.Add(guid); + } + } + + return result; + } + + private static List ParseLocationGuids(IReadOnlyList locationIdStrings) + { + var result = new List(); + foreach (var id in locationIdStrings) + { + if (Guid.TryParse(id?.Trim(), out var guid)) + { + result.Add(guid); + } + } + + return result; + } + + private static async Task TryDeleteTeamMemberRegionByGroupIdAsync(ISqlSugarClient db, string groupId) + { + if (!await TeamMemberRegionScopeHelper.HasTableAsync(db)) + { + return; + } + + try + { + await db.Deleteable() + .Where(x => x.GroupId == groupId) + .ExecuteCommandAsync(); + } + catch + { + // 表探测通过但删除失败时静默跳过,与 TeamMemberRegionScopeHelper 一致 + } + } +} diff --git a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/AllScopeBindingHelper.cs b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/AllScopeBindingHelper.cs index aa8bd00..22d0c42 100644 --- a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/AllScopeBindingHelper.cs +++ b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/AllScopeBindingHelper.cs @@ -428,9 +428,7 @@ public static class AllScopeBindingHelper return (partnerIds, regionIds, locs); } - /// - /// 标签/产品分类等:解析 Region + Location 落库(对齐 Label:Region=ALL 时可保留具体门店快照)。 - /// + /// 标签/产品分类等 Region + Location 落库结果。 public sealed class LabelEntityRegionLocationSaveResult { public string AvailabilityType { get; init; } = ScopeSpecified; @@ -440,6 +438,10 @@ public static class AllScopeBindingHelper public List LocationIds { get; init; } = new(); } + /// + /// 标签/产品分类等:解析 Region + Location 落库(对齐 Label:Region=ALL 时可保留具体门店快照)。 + /// 含 ALL 且已传具体 Region 时,为范围内 ALL(Scoped ALL),禁止升公司级 ALL。 + /// public static async Task ResolveLabelEntityRegionLocationForSaveAsync( ISqlSugarClient db, string? declaredAvailabilityType, @@ -459,9 +461,14 @@ public static class AllScopeBindingHelper // 仅显式 ALL 哨兵视为 Region=ALL。 // 禁止「公司下仅 1 个 Region + 勾选该 Region」自动升 ALL(否则编辑回显/再提交会丢 SPECIFIED)。 - // 无具体门店且未声明 SPECIFIED 时,才把「勾选当前全部 Region」归档为 ALL。 + // locationIds=["ALL"] + 具体 RegionIds 为 Scoped ALL:禁止「勾选当前全部 Region」启发式升 Region=ALL。 var regionHasAll = regionHasAllSentinel; - if (!regionHasAll && regionIds.Count > 0 && explicitLocationIds.Count == 0 && !declaredSpecified) + var isScopedAllWithConcreteRegions = locationHasAll && regionIds.Count > 0 && !regionHasAllSentinel; + if (!regionHasAll + && regionIds.Count > 0 + && explicitLocationIds.Count == 0 + && !declaredSpecified + && !isScopedAllWithConcreteRegions) { var allRegions = await ResolveAllRegionIdsAsync( db, @@ -469,9 +476,14 @@ public static class AllScopeBindingHelper regionHasAll = allRegions.Count > 0 && IsFullIdSelection(regionIds, allRegions); } - // 仅 locationIds 含 ALL 哨兵才按「全部门店」展开;有具体 Guid 时一律按 SPECIFIED 快照落库 + // locationIds=["ALL"]:相对已传 RegionIds 为范围内 ALL;有具体 Region 时禁止升公司级 ALL if (locationHasAll) { + if (isScopedAllWithConcreteRegions) + { + regionHasAll = false; + } + if (regionHasAll) { var partnerScoped = await TryResolvePartnerScopedAllRegionAllLocationAsync( diff --git a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/DashboardScopeHelper.cs b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/DashboardScopeHelper.cs index 4a5a280..24a1699 100644 --- a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/DashboardScopeHelper.cs +++ b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/DashboardScopeHelper.cs @@ -267,6 +267,30 @@ public static class DashboardScopeHelper } /// + /// 统计范围内启用标签模板数(fl_label_template,未删除且 State=true), + /// 范围与 Label Templates 列表无额外 partnerId/groupId/locationId 筛选时一致。 + /// + public static async Task CountScopedActiveTemplatesAsync( + ISqlSugarClient db, + List? scopedLocationIds, + DateTime? createdBefore) + { + var query = db.Queryable() + .Where(x => !x.IsDeleted && x.State); + + query = await LabelTemplateScopeHelper.ApplyTemplateScopeFilterAsync( + db, query, scopedLocationIds, null, null, null); + + if (createdBefore.HasValue) + { + query = query.Where(x => x.CreationTime < createdBefore.Value); + } + + query = LabelTemplateQueryHelper.ProjectListColumns(query); + return await query.CountAsync(); + } + + /// /// 为打印任务查询附加门店范围(scopeLocationIds == null 不限制)。 /// public static ISugarQueryable ApplyPrintTaskLocationScope( diff --git a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/LabelRegionScopeHelper.cs b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/LabelRegionScopeHelper.cs index 3f79226..60cf025 100644 --- a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/LabelRegionScopeHelper.cs +++ b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/LabelRegionScopeHelper.cs @@ -51,6 +51,8 @@ public static class LabelRegionScopeHelper /// /// 解析新增/编辑入参中的 Region / Location 范围。 /// 前端 Select All 常传 SPECIFIED + 当前全量 Id:覆盖全集时归档为 ALL(或不写门店快照),后续新增 Region/Location 动态适用。 + /// 含 ALL 且已传具体 时,表示范围内 ALL(Scoped ALL): + /// 落 AppliedRegionType=SPECIFIED + fl_label_region,不写 fl_label_location,禁止升公司级 ALL。 /// public static async Task ResolveScopeForSaveAsync( ISqlSugarClient db, @@ -71,7 +73,19 @@ public static class LabelRegionScopeHelper var hasScopeArrays = regionIds is not null || groupIds is not null || locationIds is not null; var partnerContext = LocationScopeBindingHelper.NormalizeIds(partnerIdsForContext); - // locationIds / regionIds 含 ALL 哨兵:不归档为 Guid 校验,按全选处理(Company 由 fl_label.PartnerId 落库) + // locationIds=["ALL"] + 具体 RegionIds → Scoped ALL(SPECIFIED + Region 快照,无门店快照) + if (locationHasAll && mergedRegionIds.Count > 0 && !regionHasAll) + { + await ValidateRegionIdsExistAsync(db, mergedRegionIds); + return new LabelRegionScopeSaveResult + { + AppliedRegionType = AppliedRegionSpecified, + RegionIds = mergedRegionIds, + LocationIds = new List() + }; + } + + // Region=ALL + Location=ALL(或无具体 Region)→ 公司级/全局 ALL(Partner 由 fl_label.PartnerId 落库) if (locationHasAll || (regionHasAll && explicitLocationIds.Count == 0)) { return new LabelRegionScopeSaveResult @@ -487,7 +501,7 @@ public static class LabelRegionScopeHelper null, regionIds, locationIds, - ScopeAllEchoHelper.ForLabelRegionScope(appliedRegionType, locationIds)); + ScopeAllEchoHelper.ForLabelRegionScope(appliedRegionType, locationIds, regionIds)); return new LabelRegionScopeDisplay { @@ -500,10 +514,14 @@ public static class LabelRegionScopeHelper public static async Task BuildLocationDisplayAsync( ISqlSugarClient db, string? appliedRegionType, - IReadOnlyList locationIds) + IReadOnlyList locationIds, + string? labelId = null, + IReadOnlyList? regionIds = null) { + var persistedLocations = LocationScopeBindingHelper.NormalizeIds(locationIds); + if (string.Equals(appliedRegionType, AppliedRegionAll, StringComparison.OrdinalIgnoreCase) - && locationIds.Count == 0) + && persistedLocations.Count == 0) { return new LabelLocationScopeDisplay { @@ -512,7 +530,25 @@ public static class LabelRegionScopeHelper }; } - if (locationIds.Count == 0) + var concreteRegions = LocationScopeBindingHelper.FilterConcreteScopeIds(regionIds); + if (concreteRegions.Count == 0 && !string.IsNullOrWhiteSpace(labelId)) + { + concreteRegions = await GetRegionIdsForLabelAsync(db, labelId); + } + + // Scoped ALL:SPECIFIED + 有 Region 快照 + 无门店快照 → 范围内 Location 回显 ALL + if (AllScopeBindingHelper.IsDeclaredSpecified(appliedRegionType) + && concreteRegions.Count > 0 + && persistedLocations.Count == 0) + { + return new LabelLocationScopeDisplay + { + Location = AllLocationsDisplay, + LocationIds = new List { AllScopeBindingHelper.ScopeAll } + }; + } + + if (persistedLocations.Count == 0) { return new LabelLocationScopeDisplay { @@ -521,7 +557,7 @@ public static class LabelRegionScopeHelper }; } - var guidList = locationIds.Where(x => Guid.TryParse(x, out _)).Select(Guid.Parse).ToList(); + var guidList = persistedLocations.Where(x => Guid.TryParse(x, out _)).Select(Guid.Parse).ToList(); var names = new List(); if (guidList.Count > 0) { @@ -539,9 +575,9 @@ public static class LabelRegionScopeHelper var collapsed = await ScopeAllEchoHelper.CollapseScopeIdsToAllSentinelAsync( db, null, - null, - locationIds, - ScopeAllEchoHelper.ForLabelRegionScope(appliedRegionType, locationIds)); + concreteRegions, + persistedLocations, + ScopeAllEchoHelper.ForLabelRegionScope(appliedRegionType, persistedLocations, concreteRegions)); return new LabelLocationScopeDisplay { diff --git a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/ScopeAllEchoHelper.cs b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/ScopeAllEchoHelper.cs index 750dec8..67d9136 100644 --- a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/ScopeAllEchoHelper.cs +++ b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/ScopeAllEchoHelper.cs @@ -88,6 +88,10 @@ public static class ScopeAllEchoHelper && LocationScopeBindingHelper.FilterConcreteScopeIds(regionIds).Count == 0 && LocationScopeBindingHelper.FilterConcreteScopeIds(locationIds).Count == 0, IsLocationAll = AllScopeBindingHelper.IsDeclaredAll(availabilityType) + || (AllScopeBindingHelper.IsDeclaredSpecified(appliedRegionType) + && LocationScopeBindingHelper.FilterConcreteScopeIds(regionIds).Count > 0 + && LocationScopeBindingHelper.FilterConcreteScopeIds(locationIds).Count == 0 + && !AllScopeBindingHelper.IsDeclaredAll(appliedRegionType)) }; /// 兼容旧调用:无 Region 类型时用 AvailabilityType 同时驱动 Region/Location。 @@ -96,16 +100,25 @@ public static class ScopeAllEchoHelper string? availabilityType) => ForLabelEntityScope(appliedPartnerType, availabilityType, availabilityType); - /// Label:AppliedRegionType=ALL 且未落门店快照时 Region/Location 均为 ALL。 + /// + /// Label:AppliedRegionType=ALL 且未落门店快照时 Region/Location 均为 ALL; + /// Scoped ALL(SPECIFIED + 有 Region 快照 + 无门店快照)时 Location 回显 ["ALL"](范围内 ALL)。 + /// public static ScopeAllEchoOptions ForLabelRegionScope( string? appliedRegionType, - IReadOnlyList locationIds) + IReadOnlyList locationIds, + IReadOnlyList? regionIds = null) { + var persistedLocations = LocationScopeBindingHelper.NormalizeIds(locationIds); + var concreteRegions = LocationScopeBindingHelper.FilterConcreteScopeIds(regionIds); var isRegionAll = AllScopeBindingHelper.IsDeclaredAll(appliedRegionType); + var isScopedLocationAll = AllScopeBindingHelper.IsDeclaredSpecified(appliedRegionType) + && concreteRegions.Count > 0 + && persistedLocations.Count == 0; return new ScopeAllEchoOptions { IsRegionAll = isRegionAll, - IsLocationAll = isRegionAll && LocationScopeBindingHelper.NormalizeIds(locationIds).Count == 0 + IsLocationAll = (isRegionAll && persistedLocations.Count == 0) || isScopedLocationAll }; } diff --git a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/DashboardAppService.cs b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/DashboardAppService.cs index 11f02a8..db931d8 100644 --- a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/DashboardAppService.cs +++ b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/DashboardAppService.cs @@ -54,12 +54,10 @@ public class DashboardAppService : ApplicationService, IDashboardAppService db.Queryable(), scopeLocationIds) .CountAsync(x => x.CreationTime >= yesterdayStart && x.CreationTime < todayStart); - var activeTemplates = await LabelTemplateQueryHelper.ProjectListColumns( - _dbContext.SqlSugarClient.Queryable()) - .CountAsync(x => !x.IsDeleted && x.State); - var activeTemplatesPrevWeek = await LabelTemplateQueryHelper.ProjectListColumns( - _dbContext.SqlSugarClient.Queryable()) - .CountAsync(x => !x.IsDeleted && x.State && x.CreationTime < weekStart); + var activeTemplates = await DashboardScopeHelper.CountScopedActiveTemplatesAsync( + db, scopeLocationIds, createdBefore: null); + var activeTemplatesPrevWeek = await DashboardScopeHelper.CountScopedActiveTemplatesAsync( + db, scopeLocationIds, createdBefore: weekStart); var activeUsers = await DashboardScopeHelper.CountScopedRegisteredUsersAsync( db, scopeLocationIds, activeOnly: true, createdBefore: null); diff --git a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/GroupAppService.cs b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/GroupAppService.cs index e683bd8..467da3b 100644 --- a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/GroupAppService.cs +++ b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/GroupAppService.cs @@ -147,6 +147,7 @@ public class GroupAppService : ApplicationService, IGroupAppService throw new UserFriendlyException("Group not found."); } + var wasActive = entity.State; var oldGroupName = entity.GroupName; var oldPartnerIdForCascade = entity.PartnerId; var name = input.GroupName?.Trim(); @@ -194,6 +195,17 @@ public class GroupAppService : ApplicationService, IGroupAppService entity.LastModifierId = CurrentUser?.Id?.ToString(); await _dbContext.SqlSugarClient.Updateable(entity).ExecuteCommandAsync(); + + if (AccountStructureCascadeInactiveHelper.IsBecomingInactive(wasActive, entity.State)) + { + await AccountStructureCascadeInactiveHelper.CascadeGroupInactiveAsync( + _dbContext.SqlSugarClient, + groupId, + Clock.Now, + CurrentUser?.Id, + CurrentUser?.Id?.ToString()); + } + return await GetAsync(id); } diff --git a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/LabelAppService.cs b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/LabelAppService.cs index f71396c..56e1d53 100644 --- a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/LabelAppService.cs +++ b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/LabelAppService.cs @@ -223,7 +223,7 @@ public class LabelAppService : ApplicationService, ILabelAppService regionScopeMap[lid] = await LabelRegionScopeHelper.BuildScopeDisplayAsync( db, lid, applied, locIds); locationScopeMap[lid] = await LabelRegionScopeHelper.BuildLocationDisplayAsync( - db, applied, locIds); + db, applied, locIds, lid); locationIdsMap[lid] = locationScopeMap[lid].LocationIds; labelMap.TryGetValue(lid, out var partnerRow); partnerEchoMap[lid] = await BuildLabelPartnerEchoAsync( @@ -1198,16 +1198,22 @@ public class LabelAppService : ApplicationService, ILabelAppService partnerIds = !string.IsNullOrWhiteSpace(storedPartnerId) ? new List { storedPartnerId } : await LocationScopeBindingHelper.ResolvePartnerIdsFromLocationIdsAsync(db, locationIds); + var persistedLocationIds = locationIds; + var regionIdsFromDb = !string.IsNullOrWhiteSpace(labelId) + ? await LabelRegionScopeHelper.GetRegionIdsForLabelAsync(db, labelId) + : new List(); var storedRegionScope = !string.IsNullOrWhiteSpace(labelId) - ? await LabelRegionScopeHelper.BuildScopeDisplayAsync(db, labelId, appliedRegionType, locationIds) + ? await LabelRegionScopeHelper.BuildScopeDisplayAsync( + db, labelId, appliedRegionType, persistedLocationIds) : new LabelRegionScopeHelper.LabelRegionScopeDisplay { RegionIds = new List() }; regionIdsForDto = storedRegionScope.RegionIds; var collapsed = await ScopeAllEchoHelper.CollapseScopeIdsToAllSentinelAsync( db, partnerIds, regionIdsForDto, - locationIds, - ScopeAllEchoHelper.ForLabelRegionScope(appliedRegionType, locationIds)); + persistedLocationIds, + ScopeAllEchoHelper.ForLabelRegionScope( + appliedRegionType, persistedLocationIds, regionIdsFromDb)); if (string.IsNullOrWhiteSpace(storedPartnerId)) { partnerIds = collapsed.PartnerIds; @@ -1226,7 +1232,7 @@ public class LabelAppService : ApplicationService, ILabelAppService var locationDisplay = isDynamicAll ? LabelRegionScopeHelper.AllLocationsDisplay : (await LabelRegionScopeHelper.BuildLocationDisplayAsync( - db, appliedRegionType, locationIds)).Location; + db, appliedRegionType, locationIds, labelId)).Location; var companyIdsEcho = partnerIds.Count == 1 && !AllScopeBindingHelper.IsDeclaredAll(partnerIds[0]) diff --git a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/LabelTypeAppService.cs b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/LabelTypeAppService.cs index 8116793..5f02f51 100644 --- a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/LabelTypeAppService.cs +++ b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/LabelTypeAppService.cs @@ -61,7 +61,13 @@ public class LabelTypeAppService : ApplicationService, ILabelTypeAppService var entities = await query.ToPageListAsync(input.SkipCount, input.MaxResultCount, total); var ids = entities.Select(x => x.Id).ToList(); - var countMap = await BuildTypeLabelStatsMapAsync(ids, scopedLocationIds); + var countMap = await BuildTypeLabelStatsMapAsync( + ids, + scopedLocationIds, + scopedPartnerIds, + input.PartnerId, + input.GroupId, + input.LocationId); var scopeMap = await BuildTypeConfiguredScopeMapAsync(entities); var partnerScopeMap = await LabelEntityPartnerScopeHelper.BuildPartnerScopeDisplayMapAsync( _dbContext.SqlSugarClient, @@ -439,9 +445,16 @@ public class LabelTypeAppService : ApplicationService, ILabelTypeAppService await _dbContext.SqlSugarClient.Insertable(rows).ExecuteCommandAsync(); } + /// + /// 统计各类型下可见标签数量,范围与 Label 列表一致(Partner + Region/Location 动态命中)。 + /// private async Task> BuildTypeLabelStatsMapAsync( List typeIds, - List? scopedLocationIds) + List? scopedLocationIds, + List? scopedPartnerIds, + string? partnerId, + string? groupId, + string? locationId) { var result = new Dictionary(StringComparer.Ordinal); if (typeIds.Count == 0) @@ -449,11 +462,53 @@ public class LabelTypeAppService : ApplicationService, ILabelTypeAppService return result; } - var labelQuery = _dbContext.SqlSugarClient.Queryable() + var db = _dbContext.SqlSugarClient; + var regionSchema = await LabelRegionSchemaHelper.GetStatusAsync(db); + var labelQuery = db.Queryable() .Where(x => !x.IsDeleted) .Where(x => x.LabelTypeId != null && typeIds.Contains(x.LabelTypeId)); - labelQuery = ApplyLabelScopeOnLabels(labelQuery, scopedLocationIds); + labelQuery = LabelRegionScopeHelper.ApplyLabelPartnerListFilter(labelQuery, scopedPartnerIds); + + var filterGroupId = groupId?.Trim(); + var applyLocationFilter = LabelEntityListScopeHelper.ShouldApplyLocationAvailabilityFilter( + partnerId, groupId, locationId); + + if (scopedLocationIds is not null && applyLocationFilter) + { + if (scopedLocationIds.Count == 0) + { + labelQuery = LabelRegionScopeHelper.ApplyLabelAllRegionOnlyFilter( + db, labelQuery, regionSchema); + } + else if (!string.IsNullOrWhiteSpace(filterGroupId)) + { + labelQuery = LabelRegionScopeHelper.ApplyLabelRegionListFilter( + db, labelQuery, filterGroupId, scopedLocationIds, regionSchema); + } + else + { + labelQuery = LabelRegionScopeHelper.ApplyLabelLocationListFilter( + db, labelQuery, scopedLocationIds, regionSchema); + } + } + else if (!string.IsNullOrWhiteSpace(partnerId) && !applyLocationFilter) + { + if (scopedLocationIds is null) + { + // 管理员且未展开到门店:不过滤 + } + else if (scopedLocationIds.Count == 0) + { + labelQuery = LabelRegionScopeHelper.ApplyLabelAllRegionOnlyFilter( + db, labelQuery, regionSchema); + } + else + { + labelQuery = LabelRegionScopeHelper.ApplyLabelLocationListFilter( + db, labelQuery, scopedLocationIds, regionSchema); + } + } var rows = await labelQuery .Select(x => new { x.LabelTypeId, x.CreationTime, x.LastModificationTime }) @@ -596,20 +651,6 @@ public class LabelTypeAppService : ApplicationService, ILabelTypeAppService return result; } - private static ISugarQueryable ApplyLabelScopeOnLabels( - ISugarQueryable labelQuery, - List? scopedLocationIds) - { - if (scopedLocationIds is null) - { - return labelQuery; - } - - return scopedLocationIds.Count == 0 - ? labelQuery.Where(_ => false) - : labelQuery.Where(l => scopedLocationIds.Contains(l.LocationId)); - } - private sealed class TypeScopeData { public string Region { get; init; } = string.Empty; diff --git a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/LocationAppService.cs b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/LocationAppService.cs index 7e6bd83..796c2d9 100644 --- a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/LocationAppService.cs +++ b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/LocationAppService.cs @@ -138,6 +138,7 @@ public class LocationAppService : ApplicationService, ILocationAppService } /// + [UnitOfWork] public async Task UpdateAsync(Guid id, [FromBody] LocationUpdateInputVo input) { await AccountManagementStructureHelper.EnsureCanMutateRegionAndLocationAsync(CurrentUser, _dbContext); @@ -215,6 +216,16 @@ public class LocationAppService : ApplicationService, ILocationAppService await _locationRepository.UpdateAsync(entity); + // inactive 时始终解绑 Team Member(幂等):避免已 inactive 再保存时跳过,或历史残留绑定清不掉 + if (!entity.State) + { + await AccountStructureCascadeInactiveHelper.CascadeLocationInactiveAsync( + db, + id, + Clock.Now, + CurrentUser?.Id?.ToString()); + } + var saved = await _locationRepository.GetSingleAsync(x => x.Id == id && x.IsDeleted == false); return await ToListDtoAsync(saved ?? entity); } diff --git a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/PartnerAppService.cs b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/PartnerAppService.cs index 8db32aa..54e21b0 100644 --- a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/PartnerAppService.cs +++ b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/PartnerAppService.cs @@ -116,6 +116,7 @@ public class PartnerAppService : ApplicationService, IPartnerAppService throw new UserFriendlyException("Partner not found."); } + var wasActive = entity.State; var oldName = entity.PartnerName; var name = input.PartnerName?.Trim(); if (string.IsNullOrWhiteSpace(name)) @@ -156,6 +157,16 @@ public class PartnerAppService : ApplicationService, IPartnerAppService entity.LastModifierId = CurrentUser?.Id?.ToString(); await _dbContext.SqlSugarClient.Updateable(entity).ExecuteCommandAsync(); + + if (AccountStructureCascadeInactiveHelper.IsBecomingInactive(wasActive, entity.State)) + { + await AccountStructureCascadeInactiveHelper.CascadePartnerInactiveAsync( + _dbContext.SqlSugarClient, + partnerId, + Clock.Now, + CurrentUser?.Id); + } + return await GetAsync(id); } diff --git a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/ProductAppService.cs b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/ProductAppService.cs index 264bdb4..ecc1624 100644 --- a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/ProductAppService.cs +++ b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/ProductAppService.cs @@ -1177,7 +1177,12 @@ public class ProductAppService : ApplicationService, IProductAppService var regionHasAll = regionHasAllSentinel; var declaredSpecified = AllScopeBindingHelper.IsDeclaredSpecified(input.AvailabilityType); - if (!regionHasAll && groupIds.Count > 0 && explicitLocationIds.Count == 0 && !declaredSpecified) + var isScopedAllWithConcreteRegions = locationHasAll && groupIds.Count > 0 && !regionHasAllSentinel; + if (!regionHasAll + && groupIds.Count > 0 + && explicitLocationIds.Count == 0 + && !declaredSpecified + && !isScopedAllWithConcreteRegions) { var allRegions = await AllScopeBindingHelper.ResolveAllRegionIdsAsync( _dbContext.SqlSugarClient, partnerContext); @@ -1197,6 +1202,11 @@ public class ProductAppService : ApplicationService, IProductAppService if (locationHasAll) { + if (isScopedAllWithConcreteRegions) + { + regionHasAll = false; + } + if (regionHasAll) { return new ProductScopeSaveResult @@ -1208,6 +1218,7 @@ public class ProductAppService : ApplicationService, IProductAppService }; } + // Scoped ALL:部分 Region + Location ALL → SPECIFIED,不写门店快照(新区店靠 Region 动态匹配需 fl_product_region;此处展开区内门店快照) var expandRegions = groupIds.Count > 0 ? groupIds : null; var expanded = await LocationScopeBindingHelper.ExpandScopedAllLocationsForSaveAsync( _dbContext.SqlSugarClient, diff --git a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/UsAppLabelingAppService.cs b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/UsAppLabelingAppService.cs index 9931229..3ced38c 100644 --- a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/UsAppLabelingAppService.cs +++ b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/UsAppLabelingAppService.cs @@ -333,7 +333,7 @@ public class UsAppLabelingAppService : ApplicationService, IUsAppLabelingAppServ /// ``` /// /// 预览入参 - /// 顶部字段 + 预览模板结构 + /// 顶部字段 + 预览模板结构(含 nutritionByElementId 营养成分 JSON) /// 成功 /// 参数错误/数据不存在 /// 服务器错误 @@ -485,11 +485,25 @@ public class UsAppLabelingAppService : ApplicationService, IUsAppLabelingAppServ } } + var nutritionByElementId = ExtractNutritionByElementId( + template.Elements, + templateProductDefaultValues); + if (templateProductDefaultValues is { Count: > 0 }) { ApplyTemplateProductDefaultValuesToPreviewElements(template.Elements, templateProductDefaultValues); } + if (nutritionByElementId.Count > 0) + { + ApplyNutritionFactsJsonToPreviewElements(template.Elements, nutritionByElementId); + foreach (var (elementId, fields) in nutritionByElementId) + { + templateProductDefaultValues ??= new Dictionary(); + templateProductDefaultValues[elementId] = JsonSerializer.Serialize(fields); + } + } + return new UsAppLabelPreviewDto { LabelId = nextDailyLabelId, @@ -505,7 +519,8 @@ public class UsAppLabelingAppService : ApplicationService, IUsAppLabelingAppServ LabelLastEdited = labelRow.LastModificationTime ?? labelRow.CreationTime, PreviewImageBase64Png = null, Template = template, - TemplateProductDefaultValues = templateProductDefaultValues + TemplateProductDefaultValues = templateProductDefaultValues, + NutritionByElementId = nutritionByElementId }; } @@ -1258,6 +1273,10 @@ public class UsAppLabelingAppService : ApplicationService, IUsAppLabelingAppServ switch (type) { + case "NUTRITION": + case "NUTRITIONFACTS": + ApplyNutritionManualToConfig(cfg, ParseNutritionManualObject(stored)); + break; case "DATE": case "TIME": case "DURATION": @@ -1307,6 +1326,297 @@ public class UsAppLabelingAppService : ApplicationService, IUsAppLabelingAppServ } } + private const string NutritionCompositeSep = "###nut###"; + + private static bool IsNutritionPreviewElement(LabelTemplateElementDto el) + { + var type = (el.ElementType ?? string.Empty).Trim().ToUpperInvariant(); + if (type is "NUTRITION" or "NUTRITIONFACTS") + { + return true; + } + + var typeAdd = (el.TypeAdd ?? string.Empty).Trim().ToUpperInvariant(); + var name = (el.ElementName ?? string.Empty).Trim().ToUpperInvariant(); + return typeAdd.Contains("NUTRITION", StringComparison.Ordinal) + || name.Contains("NUTRITION", StringComparison.Ordinal); + } + + /// + /// 从标签/产品默认值中提取 Nutrition Facts JSON(elementId → 字段)。 + /// + private static Dictionary> ExtractNutritionByElementId( + IList? elements, + Dictionary? defaults) + { + var result = new Dictionary>(StringComparer.Ordinal); + if (elements is null || elements.Count == 0 || defaults is not { Count: > 0 }) + { + return result; + } + + foreach (var el in elements) + { + if (!IsNutritionPreviewElement(el) || string.IsNullOrWhiteSpace(el.Id)) + { + continue; + } + + var manual = ResolveNutritionManualForElement(el, defaults); + if (manual.Count == 0) + { + continue; + } + + result[el.Id.Trim()] = manual; + } + + return result; + } + + private static Dictionary ResolveNutritionManualForElement( + LabelTemplateElementDto el, + Dictionary defaults) + { + var stored = ResolveTemplateProductDefaultValueForElement(el, defaults); + var fromDirect = ParseNutritionManualObject(stored); + if (fromDirect.Count > 0) + { + return fromDirect; + } + + var id = el.Id?.Trim() ?? string.Empty; + if (string.IsNullOrWhiteSpace(id)) + { + return new Dictionary(StringComparer.Ordinal); + } + + var prefix = id + NutritionCompositeSep; + var composite = new Dictionary(StringComparer.Ordinal); + foreach (var kv in defaults) + { + if (kv.Key.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) + { + composite[kv.Key[prefix.Length..]] = TemplateProductDefaultValueToStoredString(kv.Value) ?? string.Empty; + } + } + + return composite; + } + + private static Dictionary ParseNutritionManualObject(string? raw) + { + var result = new Dictionary(StringComparer.Ordinal); + if (string.IsNullOrWhiteSpace(raw)) + { + return result; + } + + var text = raw.Trim(); + if (!text.StartsWith('{')) + { + return result; + } + + try + { + using var doc = JsonDocument.Parse(text); + if (doc.RootElement.ValueKind != JsonValueKind.Object) + { + return result; + } + + foreach (var prop in doc.RootElement.EnumerateObject()) + { + var key = prop.Name.Trim(); + if (string.IsNullOrWhiteSpace(key)) + { + continue; + } + + result[key] = prop.Value.ValueKind switch + { + JsonValueKind.String => prop.Value.GetString() ?? string.Empty, + JsonValueKind.Null => string.Empty, + JsonValueKind.True => "true", + JsonValueKind.False => "false", + JsonValueKind.Number => prop.Value.GetRawText(), + _ => prop.Value.GetRawText() + }; + } + } + catch + { + return result; + } + + return result; + } + + private static void ApplyNutritionFactsJsonToPreviewElements( + IList? elements, + Dictionary> nutritionByElementId) + { + if (elements is null || elements.Count == 0 || nutritionByElementId.Count == 0) + { + return; + } + + foreach (var el in elements) + { + if (!IsNutritionPreviewElement(el) || string.IsNullOrWhiteSpace(el.Id)) + { + continue; + } + + if (!nutritionByElementId.TryGetValue(el.Id.Trim(), out var manual) || manual.Count == 0) + { + continue; + } + + var cfg = ParsePreviewElementConfig(el.ConfigJson); + ApplyNutritionManualToConfig(cfg, manual); + el.ConfigJson = cfg; + } + } + + private static void ApplyNutritionManualToConfig( + Dictionary cfg, + Dictionary manual) + { + if (manual.Count == 0) + { + return; + } + + cfg["nutritionFactsJson"] = JsonSerializer.Serialize(manual); + foreach (var kv in manual) + { + var key = kv.Key?.Trim(); + if (string.IsNullOrWhiteSpace(key)) + { + continue; + } + + cfg[key] = kv.Value ?? string.Empty; + } + + if (TryPickNutritionField(manual, out var calories, "calories")) + { + cfg["calories"] = calories; + cfg["Calories"] = calories; + } + + if (TryPickNutritionField(manual, out var servings, "servingsPerContainer", "servings")) + { + cfg["servingsPerContainer"] = servings; + cfg["servings"] = servings; + } + + if (TryPickNutritionField(manual, out var servingSize, "servingSize", "serveSize")) + { + cfg["servingSize"] = servingSize; + cfg["serveSize"] = servingSize; + } + + if (TryPickNutritionField(manual, out var fat, "fat", "totalFat")) + { + cfg["fat"] = fat; + cfg["totalFat"] = fat; + } + + if (TryPickNutritionField(manual, out var carbs, "carbs", "totalCarbo", "totalCarbohydrate")) + { + cfg["carbs"] = carbs; + } + + if (TryPickNutritionField(manual, out var sugars, "totalSugar", "sugars")) + { + cfg["totalSugar"] = sugars; + } + + if (cfg.TryGetValue("fixedNutrients", out var fixedRaw) && fixedRaw is not null) + { + ApplyNutritionManualToFixedNutrients(cfg, manual); + } + } + + private static bool TryPickNutritionField( + Dictionary manual, + out string value, + params string[] keys) + { + foreach (var key in keys) + { + foreach (var kv in manual) + { + if (string.Equals(kv.Key, key, StringComparison.OrdinalIgnoreCase) + && !string.IsNullOrWhiteSpace(kv.Value)) + { + value = kv.Value; + return true; + } + } + } + + value = string.Empty; + return false; + } + + private static void ApplyNutritionManualToFixedNutrients( + Dictionary cfg, + Dictionary manual) + { + try + { + var json = JsonSerializer.Serialize(cfg["fixedNutrients"]); + var rows = JsonSerializer.Deserialize>>(json); + if (rows is null || rows.Count == 0) + { + return; + } + + foreach (var row in rows) + { + if (!row.TryGetValue("key", out var keyObj)) + { + continue; + } + + var key = Convert.ToString(keyObj, CultureInfo.InvariantCulture)?.Trim(); + if (string.IsNullOrWhiteSpace(key)) + { + continue; + } + + if (TryPickNutritionField(manual, out var amount, key, AliasForNutritionKey(key))) + { + row["value"] = amount; + } + + if (TryPickNutritionField(manual, out var pct, $"{key}Percent")) + { + row["dailyValuePercent"] = pct; + } + } + + cfg["fixedNutrients"] = rows; + } + catch + { + // keep original fixedNutrients when merge fails + } + } + + private static string AliasForNutritionKey(string key) => key switch + { + "fat" => "totalFat", + "totalFat" => "fat", + "carbs" => "totalCarbo", + "totalSugar" => "sugars", + _ => key + }; + private static string? ResolveTemplateProductDefaultValueForElement( LabelTemplateElementDto el, Dictionary defaults) diff --git a/美国版/Food Labeling Management Code/Yi.Abp.Net8/src/Yi.Abp.Web/appsettings.json b/美国版/Food Labeling Management Code/Yi.Abp.Net8/src/Yi.Abp.Web/appsettings.json index 4d9c5d6..ac190b3 100644 --- a/美国版/Food Labeling Management Code/Yi.Abp.Net8/src/Yi.Abp.Web/appsettings.json +++ b/美国版/Food Labeling Management Code/Yi.Abp.Net8/src/Yi.Abp.Web/appsettings.json @@ -20,14 +20,13 @@ }, //应用启动:SelfUrl 供 Program.cs UseUrls 绑定;用 0.0.0.0 避免写成固定局域网 IP 在本机无该网卡时启动失败(WinError 10049) "App": { - "SelfUrl": "http://192.168.31.89:19003", + "SelfUrl": "http://192.168.31.88:19003", "CorsOrigins": "http://localhost:19003;http://localhost:18000;http://localhost:5666;http://localhost:5174;http://localhost:5173;http://localhost:3000" }, //配置 "Settings": { "Test": "hello" }, - //数据库类型列表 "DbList": [ "Sqlite", "Mysql", "Sqlserver", "Oracle", "PostgreSQL" ],