Commit 5335f64f31f4123482d03f791d432578dd54a5e7

Authored by 李曜臣
1 parent c322f0a9

2026-12-3

Showing 30 changed files with 1437 additions and 181 deletions
AGENTS.md
... ... @@ -19,6 +19,10 @@
19 19 - 美国版:`美国版/Food Labeling Management Code/Yi.Abp.Net8/`(模块 `module/food-labeling-us`)
20 20 - 泰额版:`泰额版/Food Labeling Management Code/Yi.Abp.Net8/`(模块 `module/food-labeling`、`module/food-labeling-us`)
21 21 - 开发工具已从 Cursor 切换到 DeepSeek/DSH;`.cursor` 中的规则继续作为规范参考(见下方「从 `.cursor` 继承的关键约束」),落地时与各版本现有代码事实冲突则以代码事实为准。
  22 +- **改动范围只限于用户明确发来的接口**(2026-12 用户指定):
  23 + - 修 bug / 加能力只动该接口自身的方法、DTO、实体与专属 helper;
  24 + - 不顺带改其它接口、不主动扩展同类模块;
  25 + - 若必须动共享 helper(会影响其它接口),先说明影响面并等用户确认,不做默认放开。
22 26  
23 27 ## 本仓库对 Codex 的工作约束
24 28  
... ...
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/DashboardScopeHelper.cs
... ... @@ -148,8 +148,13 @@ public static class DashboardScopeHelper
148 148 if (LabelEntityListScopeHelper.ShouldApplyLocationAvailabilityFilter(null, null, null)
149 149 && scopedLocationIds is not null)
150 150 {
  151 + var hasCategoryRegionTable = await LabelEntityRegionScopeStore.HasTableAsync(
  152 + db, LabelEntityRegionScopeStore.Kind.Category);
  153 + var scopedGroupIds = scopedLocationIds is { Count: > 0 }
  154 + ? await LocationScopeBindingHelper.ResolveGroupIdsFromLocationIdsAsync(db, scopedLocationIds)
  155 + : new List<string>();
151 156 catQuery = LabelEntityListScopeHelper.ApplyCategoryLocationAvailabilityFilter(
152   - catQuery, scopedLocationIds);
  157 + catQuery, scopedLocationIds, hasCategoryRegionTable, scopedGroupIds);
153 158 }
154 159  
155 160 var categories = await catQuery.ToListAsync();
... ... @@ -333,6 +338,10 @@ public static class DashboardScopeHelper
333 338 var filterPartner = await ProductListScopeHelper.ResolveFilterPartnerContextAsync(
334 339 db, null, null, scopedLocationIds);
335 340 var partnerOnly = !LabelEntityListScopeHelper.ShouldApplyLocationAvailabilityFilter(null, null, null);
  341 + var hasProductRegionTable = await ProductScopeSchemaHelper.HasRegionTableAsync(db);
  342 + var scopedGroupIds = scopedLocationIds.Count > 0
  343 + ? await LocationScopeBindingHelper.ResolveGroupIdsFromLocationIdsAsync(db, scopedLocationIds)
  344 + : new List<string>();
336 345  
337 346 query = ProductListScopeHelper.ApplyProductLocationListFilter(
338 347 query,
... ... @@ -341,7 +350,9 @@ public static class DashboardScopeHelper
341 350 hasAvailabilityColumn,
342 351 hasAppliedRegionColumn,
343 352 hasPartnerIdColumn,
344   - partnerOnly);
  353 + partnerOnly,
  354 + hasProductRegionTable,
  355 + scopedGroupIds);
345 356 }
346 357  
347 358 return await query.CountAsync();
... ...
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/LabelCategoryManagePermissionHelper.cs 0 → 100644
  1 +using FoodLabeling.Application.Services.DbModels;
  2 +using Volo.Abp.Users;
  3 +using Yi.Framework.SqlSugarCore.Abstractions;
  4 +
  5 +namespace FoodLabeling.Application.Helpers;
  6 +
  7 +/// <summary>
  8 +/// 标签分类(Label Category)编辑/删除权限:平台管理员全部可管;
  9 +/// Scoped Admin 只能改「自己创建的」与「下级创建的」,上级(含 Super Admin)与同级创建的一律不可。
  10 +/// 具体判定见 <see cref="ScopedEntityManagePermissionHelper"/>。
  11 +/// </summary>
  12 +public static class LabelCategoryManagePermissionHelper
  13 +{
  14 + /// <summary>列表行 canManage。</summary>
  15 + public static bool EvaluateRow(
  16 + ICurrentUser currentUser,
  17 + PartnerScopedManagePermissionHelper.ListEvaluationContext context,
  18 + FlLabelCategoryDbEntity entity,
  19 + IReadOnlyList<string> entityPartnerIds) =>
  20 + ScopedEntityManagePermissionHelper.Evaluate(
  21 + currentUser,
  22 + context,
  23 + entity.Id,
  24 + entity.CreatorId,
  25 + entity.LastModifierId,
  26 + entityPartnerIds,
  27 + entity.AppliedPartnerType);
  28 +
  29 + /// <summary>编辑/删除前置校验。</summary>
  30 + public static Task EnsureCanManageAsync(
  31 + ICurrentUser currentUser,
  32 + ISqlSugarDbContext dbContext,
  33 + FlLabelCategoryDbEntity entity,
  34 + string unauthorizedMessage) =>
  35 + ScopedEntityManagePermissionHelper.EnsureCanManageAsync(
  36 + currentUser,
  37 + dbContext,
  38 + LabelEntityPartnerScopeHelper.LabelEntityPartnerKind.Category,
  39 + entity.Id,
  40 + entity.CreatorId,
  41 + entity.LastModifierId,
  42 + entity.AppliedPartnerType,
  43 + unauthorizedMessage);
  44 +}
... ...
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/LabelEntityListScopeHelper.cs
... ... @@ -58,7 +58,9 @@ public static class LabelEntityListScopeHelper
58 58 /// </summary>
59 59 public static ISugarQueryable<FlLabelTypeDbEntity> ApplyTypeLocationAvailabilityFilter(
60 60 ISugarQueryable<FlLabelTypeDbEntity> query,
61   - List<string>? scopedLocationIds)
  61 + List<string>? scopedLocationIds,
  62 + bool hasRegionTable = false,
  63 + IReadOnlyList<string>? scopedGroupIds = null)
62 64 {
63 65 if (scopedLocationIds is null)
64 66 {
... ... @@ -71,12 +73,27 @@ public static class LabelEntityListScopeHelper
71 73 return query.Where(t => t.AvailabilityType == AllScopeBindingHelper.ScopeAll);
72 74 }
73 75  
  76 + // 用 ORM 表达式生成子查询:分页计数时 SqlSugar 会给主表套别名,原生 SQL 的 fl_label_type.Id 会解析不到。
  77 + if (!hasRegionTable || scopedGroupIds is not { Count: > 0 })
  78 + {
  79 + return query.Where(t =>
  80 + t.AvailabilityType == AllScopeBindingHelper.ScopeAll
  81 + || (t.AvailabilityType == AllScopeBindingHelper.ScopeSpecified
  82 + && SqlFunc.Subqueryable<FlLabelTypeLocationDbEntity>()
  83 + .Where(tl => tl.LabelTypeId == t.Id && scopedLocationIds.Contains(tl.LocationId))
  84 + .Any()));
  85 + }
  86 +
  87 + var typeGroupIds = scopedGroupIds.ToList();
74 88 return query.Where(t =>
75 89 t.AvailabilityType == AllScopeBindingHelper.ScopeAll
76 90 || (t.AvailabilityType == AllScopeBindingHelper.ScopeSpecified
77   - && SqlFunc.Subqueryable<FlLabelTypeLocationDbEntity>()
78   - .Where(tl => tl.LabelTypeId == t.Id && scopedLocationIds.Contains(tl.LocationId))
79   - .Any()));
  91 + && (SqlFunc.Subqueryable<FlLabelTypeLocationDbEntity>()
  92 + .Where(tl => tl.LabelTypeId == t.Id && scopedLocationIds.Contains(tl.LocationId))
  93 + .Any()
  94 + || SqlFunc.Subqueryable<FlLabelTypeRegionDbEntity>()
  95 + .Where(tr => tr.LabelTypeId == t.Id && typeGroupIds.Contains(tr.GroupId))
  96 + .Any())));
80 97 }
81 98  
82 99 /// <summary>
... ... @@ -84,7 +101,9 @@ public static class LabelEntityListScopeHelper
84 101 /// </summary>
85 102 public static ISugarQueryable<FlLabelCategoryDbEntity> ApplyCategoryLocationAvailabilityFilter(
86 103 ISugarQueryable<FlLabelCategoryDbEntity> query,
87   - List<string>? scopedLocationIds)
  104 + List<string>? scopedLocationIds,
  105 + bool hasRegionTable = false,
  106 + IReadOnlyList<string>? scopedGroupIds = null)
88 107 {
89 108 if (scopedLocationIds is null)
90 109 {
... ... @@ -96,12 +115,28 @@ public static class LabelEntityListScopeHelper
96 115 return query.Where(c => c.AvailabilityType == AllScopeBindingHelper.ScopeAll);
97 116 }
98 117  
  118 + // 注意:这里必须用 ORM 表达式(SqlFunc.Subqueryable)而不是原生 SQL。
  119 + // 列表分页/计数时 SqlSugar 会给主表套用别名,原生 SQL 里的 fl_label_category.Id 在 count 子查询中解析不到。
  120 + if (!hasRegionTable || scopedGroupIds is not { Count: > 0 })
  121 + {
  122 + return query.Where(c =>
  123 + c.AvailabilityType == AllScopeBindingHelper.ScopeAll
  124 + || (c.AvailabilityType == AllScopeBindingHelper.ScopeSpecified
  125 + && SqlFunc.Subqueryable<FlLabelCategoryLocationDbEntity>()
  126 + .Where(cl => cl.CategoryId == c.Id && scopedLocationIds.Contains(cl.LocationId))
  127 + .Any()));
  128 + }
  129 +
  130 + var groupIds = scopedGroupIds.ToList();
99 131 return query.Where(c =>
100 132 c.AvailabilityType == AllScopeBindingHelper.ScopeAll
101 133 || (c.AvailabilityType == AllScopeBindingHelper.ScopeSpecified
102   - && SqlFunc.Subqueryable<FlLabelCategoryLocationDbEntity>()
103   - .Where(cl => cl.CategoryId == c.Id && scopedLocationIds.Contains(cl.LocationId))
104   - .Any()));
  134 + && (SqlFunc.Subqueryable<FlLabelCategoryLocationDbEntity>()
  135 + .Where(cl => cl.CategoryId == c.Id && scopedLocationIds.Contains(cl.LocationId))
  136 + .Any()
  137 + || SqlFunc.Subqueryable<FlLabelCategoryRegionDbEntity>()
  138 + .Where(cr => cr.CategoryId == c.Id && groupIds.Contains(cr.GroupId))
  139 + .Any())));
105 140 }
106 141  
107 142 /// <summary>
... ... @@ -109,7 +144,9 @@ public static class LabelEntityListScopeHelper
109 144 /// </summary>
110 145 public static ISugarQueryable<FlLabelMultipleOptionDbEntity> ApplyMultipleOptionLocationAvailabilityFilter(
111 146 ISugarQueryable<FlLabelMultipleOptionDbEntity> query,
112   - List<string>? scopedLocationIds)
  147 + List<string>? scopedLocationIds,
  148 + bool hasRegionTable = false,
  149 + IReadOnlyList<string>? scopedGroupIds = null)
113 150 {
114 151 if (scopedLocationIds is null)
115 152 {
... ... @@ -121,11 +158,26 @@ public static class LabelEntityListScopeHelper
121 158 return query.Where(o => o.AvailabilityType == AllScopeBindingHelper.ScopeAll);
122 159 }
123 160  
  161 + // 用 ORM 表达式生成子查询:分页计数时 SqlSugar 会给主表套别名,原生 SQL 的 fl_label_multiple_option.Id 会解析不到。
  162 + if (!hasRegionTable || scopedGroupIds is not { Count: > 0 })
  163 + {
  164 + return query.Where(o =>
  165 + o.AvailabilityType == AllScopeBindingHelper.ScopeAll
  166 + || (o.AvailabilityType == AllScopeBindingHelper.ScopeSpecified
  167 + && SqlFunc.Subqueryable<FlLabelMultipleOptionLocationDbEntity>()
  168 + .Where(ol => ol.MultipleOptionId == o.Id && scopedLocationIds.Contains(ol.LocationId))
  169 + .Any()));
  170 + }
  171 +
  172 + var optionGroupIds = scopedGroupIds.ToList();
124 173 return query.Where(o =>
125 174 o.AvailabilityType == AllScopeBindingHelper.ScopeAll
126 175 || (o.AvailabilityType == AllScopeBindingHelper.ScopeSpecified
127   - && SqlFunc.Subqueryable<FlLabelMultipleOptionLocationDbEntity>()
128   - .Where(ol => ol.MultipleOptionId == o.Id && scopedLocationIds.Contains(ol.LocationId))
129   - .Any()));
  176 + && (SqlFunc.Subqueryable<FlLabelMultipleOptionLocationDbEntity>()
  177 + .Where(ol => ol.MultipleOptionId == o.Id && scopedLocationIds.Contains(ol.LocationId))
  178 + .Any()
  179 + || SqlFunc.Subqueryable<FlLabelMultipleOptionRegionDbEntity>()
  180 + .Where(mr => mr.MultipleOptionId == o.Id && optionGroupIds.Contains(mr.GroupId))
  181 + .Any())));
130 182 }
131 183 }
... ...
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/LabelEntityRegionScopeStore.cs 0 → 100644
  1 +using SqlSugar;
  2 +using Volo.Abp.Guids;
  3 +
  4 +namespace FoodLabeling.Application.Helpers;
  5 +
  6 +/// <summary>
  7 +/// 标签实体(类型 / 分类 / 多选项)的 Region 绑定存储:
  8 +/// 用于表达「所选 Region 内全部门店」的范围 ALL —— 只落 Region 绑定、不落门店快照,
  9 +/// 该 Region 后续新增门店自动适用,详情/列表回显 <c>locationIds=["ALL"]</c>。
  10 +/// 未执行建表脚本的环境会自动回退为「展开区内门店快照」的旧行为。
  11 +/// </summary>
  12 +public static class LabelEntityRegionScopeStore
  13 +{
  14 + public enum Kind
  15 + {
  16 + /// <summary>标签类型:fl_label_type_region.LabelTypeId</summary>
  17 + Type,
  18 +
  19 + /// <summary>标签分类:fl_label_category_region.CategoryId</summary>
  20 + Category,
  21 +
  22 + /// <summary>标签多选项:fl_label_multiple_option_region.MultipleOptionId</summary>
  23 + MultipleOption
  24 + }
  25 +
  26 + private static readonly Dictionary<Kind, (string Table, string Column)> Map = new()
  27 + {
  28 + [Kind.Type] = ("fl_label_type_region", "LabelTypeId"),
  29 + [Kind.Category] = ("fl_label_category_region", "CategoryId"),
  30 + [Kind.MultipleOption] = ("fl_label_multiple_option_region", "MultipleOptionId")
  31 + };
  32 +
  33 + private static readonly Dictionary<Kind, bool> TableCache = new();
  34 +
  35 + public static string TableName(Kind kind) => Map[kind].Table;
  36 +
  37 + public static string EntityColumn(Kind kind) => Map[kind].Column;
  38 +
  39 + public static async Task<bool> HasTableAsync(ISqlSugarClient db, Kind kind)
  40 + {
  41 + if (TableCache.TryGetValue(kind, out var cached))
  42 + {
  43 + return cached;
  44 + }
  45 +
  46 + bool exists;
  47 + try
  48 + {
  49 + var count = await db.Ado.GetIntAsync(
  50 + """
  51 + SELECT COUNT(*)
  52 + FROM information_schema.TABLES
  53 + WHERE TABLE_SCHEMA = DATABASE()
  54 + AND TABLE_NAME = @table
  55 + """,
  56 + new { table = Map[kind].Table });
  57 + exists = count > 0;
  58 + }
  59 + catch
  60 + {
  61 + exists = false;
  62 + }
  63 +
  64 + TableCache[kind] = exists;
  65 + return exists;
  66 + }
  67 +
  68 + public static async Task<List<string>> LoadRegionIdsAsync(ISqlSugarClient db, Kind kind, string entityId)
  69 + {
  70 + if (string.IsNullOrWhiteSpace(entityId) || !await HasTableAsync(db, kind))
  71 + {
  72 + return new List<string>();
  73 + }
  74 +
  75 + var (table, column) = Map[kind];
  76 + var rows = await db.Ado.SqlQueryAsync<string>(
  77 + $"SELECT GroupId FROM {table} WHERE {column} = @id",
  78 + new { id = entityId.Trim() });
  79 + return LocationScopeBindingHelper.NormalizeIds(rows);
  80 + }
  81 +
  82 + public static async Task<Dictionary<string, List<string>>> LoadRegionIdsMapAsync(
  83 + ISqlSugarClient db,
  84 + Kind kind,
  85 + IReadOnlyList<string> entityIds)
  86 + {
  87 + var result = new Dictionary<string, List<string>>(StringComparer.Ordinal);
  88 + if (entityIds.Count == 0 || !await HasTableAsync(db, kind))
  89 + {
  90 + return result;
  91 + }
  92 +
  93 + var ids = LocationScopeBindingHelper.NormalizeIds(entityIds);
  94 + if (ids.Count == 0)
  95 + {
  96 + return result;
  97 + }
  98 +
  99 + var (table, column) = Map[kind];
  100 + var rows = await db.Ado.SqlQueryAsync<LabelEntityRegionRow>(
  101 + $"SELECT {column} AS EntityId, GroupId FROM {table} WHERE {column} IN (@ids)",
  102 + new { ids });
  103 +
  104 + foreach (var g in rows.GroupBy(x => x.EntityId ?? string.Empty, StringComparer.Ordinal))
  105 + {
  106 + var regionIds = LocationScopeBindingHelper.NormalizeIds(g.Select(x => x.GroupId).ToList());
  107 + if (regionIds.Count > 0)
  108 + {
  109 + result[g.Key] = regionIds;
  110 + }
  111 + }
  112 +
  113 + return result;
  114 + }
  115 +
  116 + public static async Task ReplaceAsync(
  117 + ISqlSugarClient db,
  118 + Kind kind,
  119 + string entityId,
  120 + IReadOnlyList<string> regionIds,
  121 + IGuidGenerator guidGenerator,
  122 + string? currentUserId,
  123 + DateTime now)
  124 + {
  125 + if (!await HasTableAsync(db, kind))
  126 + {
  127 + return;
  128 + }
  129 +
  130 + var (table, column) = Map[kind];
  131 + await db.Ado.ExecuteCommandAsync(
  132 + $"DELETE FROM {table} WHERE {column} = @id",
  133 + new { id = entityId.Trim() });
  134 +
  135 + var ids = LocationScopeBindingHelper.FilterConcreteScopeIds(
  136 + LocationScopeBindingHelper.NormalizeIds(regionIds));
  137 + foreach (var groupId in ids)
  138 + {
  139 + await db.Ado.ExecuteCommandAsync(
  140 + $"INSERT INTO {table} (Id, {column}, GroupId, CreationTime, CreatorId) VALUES (@id, @entityId, @groupId, @now, @creatorId)",
  141 + new
  142 + {
  143 + id = guidGenerator.Create().ToString(),
  144 + entityId = entityId.Trim(),
  145 + groupId,
  146 + now,
  147 + creatorId = currentUserId
  148 + });
  149 + }
  150 + }
  151 +
  152 + public static async Task DeleteByEntityAsync(ISqlSugarClient db, Kind kind, string entityId)
  153 + {
  154 + if (!await HasTableAsync(db, kind))
  155 + {
  156 + return;
  157 + }
  158 +
  159 + var (table, column) = Map[kind];
  160 + await db.Ado.ExecuteCommandAsync(
  161 + $"DELETE FROM {table} WHERE {column} = @id",
  162 + new { id = entityId.Trim() });
  163 + }
  164 +
  165 + /// <summary>单元测试或切换库后调用。</summary>
  166 + public static void ResetCacheForTests() => TableCache.Clear();
  167 +
  168 + private sealed class LabelEntityRegionRow
  169 + {
  170 + public string? EntityId { get; set; }
  171 +
  172 + public string? GroupId { get; set; }
  173 + }
  174 +}
... ...
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/LabelRegionScopeHelper.cs
... ... @@ -865,6 +865,18 @@ public static class LabelRegionScopeHelper
865 865 return true;
866 866 }
867 867  
  868 + // 有门店快照时,Region 绑定只代表门店所属区域,不能据此放行同 Region 的其它门店
  869 + if (!string.IsNullOrWhiteSpace(label.LocationId))
  870 + {
  871 + return false;
  872 + }
  873 +
  874 + if (schema.HasLabelLocationTable
  875 + && await db.Queryable<FlLabelLocationDbEntity>().AnyAsync(x => x.LabelId == label.Id))
  876 + {
  877 + return false;
  878 + }
  879 +
868 880 if (groupIdsForLocation.Count == 0)
869 881 {
870 882 return false;
... ... @@ -942,11 +954,13 @@ public static class LabelRegionScopeHelper
942 954  
943 955 if (hasRegTable && groupIds.Count > 0)
944 956 {
  957 + // 有门店快照时 Region 绑定不再放大范围(与列表筛选保持一致)
945 958 specifiedParts.Add(
946   - """
947   - EXISTS (SELECT 1 FROM fl_label_region lr
948   - WHERE lr.LabelId = l.Id AND lr.GroupId IN (@groupIds))
949   - """);
  959 + $"""
  960 + (EXISTS (SELECT 1 FROM fl_label_region lr
  961 + WHERE lr.LabelId = l.Id AND lr.GroupId IN (@groupIds))
  962 + AND {noLocationSnapshotSql})
  963 + """);
950 964 }
951 965  
952 966 var specifiedBranchSql = string.Join(" OR ", specifiedParts);
... ... @@ -976,11 +990,19 @@ public static class LabelRegionScopeHelper
976 990  
977 991 if (hasRegTable && groupIds.Count > 0)
978 992 {
  993 + // 有门店快照时 Region 绑定不再放大范围(与列表筛选保持一致)
  994 + var noSnapshot = hasLocTable
  995 + ? """
  996 + ((l.LocationId IS NULL OR l.LocationId = '')
  997 + AND NOT EXISTS (SELECT 1 FROM fl_label_location ll0 WHERE ll0.LabelId = l.Id))
  998 + """
  999 + : "(l.LocationId IS NULL OR l.LocationId = '')";
979 1000 parts.Add(
980   - """
981   - EXISTS (SELECT 1 FROM fl_label_region lr
982   - WHERE lr.LabelId = l.Id AND lr.GroupId IN (@groupIds))
983   - """);
  1001 + $"""
  1002 + (EXISTS (SELECT 1 FROM fl_label_region lr
  1003 + WHERE lr.LabelId = l.Id AND lr.GroupId IN (@groupIds))
  1004 + AND {noSnapshot})
  1005 + """);
984 1006 }
985 1007  
986 1008 return $"({string.Join(" OR ", parts)})";
... ... @@ -993,9 +1015,12 @@ public static class LabelRegionScopeHelper
993 1015 LabelRegionSchemaHelper.LabelRegionSchemaStatus schema)
994 1016 {
995 1017 var includeRegionMatch = schema.HasLabelRegionTable && scopedGroupIds.Count > 0;
996   - var specifiedBranch = BuildSpecifiedLocationRegionMatchSql(
997   - schema.HasLabelLocationTable,
998   - includeRegionMatch);
  1018 + // 门店快照优先:标签同时有门店快照与 Region 绑定时,Region 仅表示门店所属区域,
  1019 + // 不能再放行同 Region 的其它门店(与 BuildLocationDisplayAsync「有门店快照则回显具体门店」一致)。
  1020 + var locationMatch = BuildSpecifiedLocationMatchSql(schema.HasLabelLocationTable);
  1021 + var specifiedBranch = includeRegionMatch
  1022 + ? $"({locationMatch} OR ({BuildRegionWithoutLocationSnapshotMatchSql(schema.HasLabelLocationTable)}))"
  1023 + : locationMatch;
999 1024  
1000 1025 // 对齐 BuildAppLabelingTreeStoreFilterSql / LabelAppliesToLocationAsync:
1001 1026 // ALL 无门店快照 → 全局;ALL 有快照 → 须命中 scoped 门店(不可无条件放行,否则跨公司泄漏)。
... ... @@ -1057,7 +1082,10 @@ public static class LabelRegionScopeHelper
1057 1082 return query.Where(l => scopedLocationIds.Contains(l.LocationId));
1058 1083 }
1059 1084  
1060   - private static string BuildSpecifiedLocationRegionMatchSql(bool hasLabelLocationTable, bool includeRegionMatch)
  1085 + /// <summary>
  1086 + /// 门店命中 SQL:<c>fl_label.LocationId</c> 主键或 <c>fl_label_location</c> 门店快照。
  1087 + /// </summary>
  1088 + private static string BuildSpecifiedLocationMatchSql(bool hasLabelLocationTable)
1061 1089 {
1062 1090 var parts = new List<string> { "LocationId IN (@locs)" };
1063 1091 if (hasLabelLocationTable)
... ... @@ -1066,15 +1094,25 @@ public static class LabelRegionScopeHelper
1066 1094 "EXISTS (SELECT 1 FROM fl_label_location ll WHERE ll.LabelId = fl_label.Id AND ll.LocationId IN (@locs))");
1067 1095 }
1068 1096  
1069   - if (includeRegionMatch)
1070   - {
1071   - parts.Add(
1072   - "EXISTS (SELECT 1 FROM fl_label_region lr WHERE lr.LabelId = fl_label.Id AND lr.GroupId IN (@scopedGroupIds))");
1073   - }
1074   -
1075 1097 return string.Join(" OR ", parts);
1076 1098 }
1077 1099  
  1100 + /// <summary>
  1101 + /// Region 命中 SQL:仅当标签没有门店快照时生效(Scoped ALL)。
  1102 + /// 有门店快照时 Region 只代表门店所属区域,不能再让同 Region 其它门店命中。
  1103 + /// </summary>
  1104 + private static string BuildRegionWithoutLocationSnapshotMatchSql(bool hasLabelLocationTable)
  1105 + {
  1106 + var noSnapshot = hasLabelLocationTable
  1107 + ? "(LocationId IS NULL OR LocationId = '') AND NOT EXISTS (SELECT 1 FROM fl_label_location ll0 WHERE ll0.LabelId = fl_label.Id)"
  1108 + : "(LocationId IS NULL OR LocationId = '')";
  1109 +
  1110 + return $"""
  1111 + EXISTS (SELECT 1 FROM fl_label_region lr WHERE lr.LabelId = fl_label.Id AND lr.GroupId IN (@scopedGroupIds))
  1112 + AND {noSnapshot}
  1113 + """;
  1114 + }
  1115 +
1078 1116 private static List<string> MergeExplicitLocationIds(string? locationId, IReadOnlyList<string>? locationIds)
1079 1117 {
1080 1118 var merged = LocationScopeBindingHelper.NormalizeIds(locationIds);
... ...
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/LabelTemplateManagePermissionHelper.cs
... ... @@ -79,7 +79,8 @@ public static class LabelTemplateManagePermissionHelper
79 79 string? creatorId = null,
80 80 TeamMemberListAccessHelper.MemberRoleTier? viewerRoleTier = null,
81 81 TeamMemberListAccessHelper.MemberRoleTier? creatorRoleTier = null,
82   - bool allowSelfCreatedWithoutConcretePartner = false)
  82 + bool allowSelfCreatedWithoutConcretePartner = false,
  83 + bool allowSystemAdminCreated = false)
83 84 {
84 85 if (ReportsRoleHelper.IsAdminRole(currentUser))
85 86 {
... ... @@ -101,7 +102,13 @@ public static class LabelTemplateManagePermissionHelper
101 102  
102 103 if (createdBySystemAdmin)
103 104 {
104   - return false;
  105 + if (!allowSystemAdminCreated)
  106 + {
  107 + return false;
  108 + }
  109 +
  110 + // 标签类型等指定场景:超管创建不再硬拒,仅按实体自身 Company 范围判定
  111 + return MeetsPartnerScopeForManage(partnerIds, allowedPartnerIds, allowEmptyPartnerIds: false);
105 112 }
106 113  
107 114 // 创建者角色更高(System/Company 相对 Regional/Location)→ 下级不可管。
... ...
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/LabelTypeManagePermissionHelper.cs 0 → 100644
  1 +using FoodLabeling.Application.Services.DbModels;
  2 +using Volo.Abp.Users;
  3 +using Yi.Framework.SqlSugarCore.Abstractions;
  4 +
  5 +namespace FoodLabeling.Application.Helpers;
  6 +
  7 +/// <summary>
  8 +/// 标签类型(Label Type)编辑/删除权限:平台管理员全部可管;
  9 +/// Scoped Admin 只能改「自己创建的」与「下级创建的」,上级(含 Super Admin)与同级创建的一律不可。
  10 +/// 具体判定见 <see cref="ScopedEntityManagePermissionHelper"/>。
  11 +/// </summary>
  12 +public static class LabelTypeManagePermissionHelper
  13 +{
  14 + /// <summary>列表行 canManage。</summary>
  15 + public static bool EvaluateRow(
  16 + ICurrentUser currentUser,
  17 + PartnerScopedManagePermissionHelper.ListEvaluationContext context,
  18 + FlLabelTypeDbEntity entity,
  19 + IReadOnlyList<string> entityPartnerIds) =>
  20 + ScopedEntityManagePermissionHelper.Evaluate(
  21 + currentUser,
  22 + context,
  23 + entity.Id,
  24 + entity.CreatorId,
  25 + entity.LastModifierId,
  26 + entityPartnerIds,
  27 + entity.AppliedPartnerType);
  28 +
  29 + /// <summary>编辑/删除前置校验。</summary>
  30 + public static Task EnsureCanManageAsync(
  31 + ICurrentUser currentUser,
  32 + ISqlSugarDbContext dbContext,
  33 + FlLabelTypeDbEntity entity,
  34 + string unauthorizedMessage) =>
  35 + ScopedEntityManagePermissionHelper.EnsureCanManageAsync(
  36 + currentUser,
  37 + dbContext,
  38 + LabelEntityPartnerScopeHelper.LabelEntityPartnerKind.Type,
  39 + entity.Id,
  40 + entity.CreatorId,
  41 + entity.LastModifierId,
  42 + entity.AppliedPartnerType,
  43 + unauthorizedMessage);
  44 +}
... ...
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/PartnerScopedManagePermissionHelper.cs
... ... @@ -16,6 +16,9 @@ public static class PartnerScopedManagePermissionHelper
16 16 {
17 17 public bool IsScopedAdmin { get; init; }
18 18  
  19 + /// <summary>是否为 Company Admin(超管创建的全局 Label Type 放开给 Company Admin 维护)。</summary>
  20 + public bool IsCompanyAdmin { get; init; }
  21 +
19 22 public IReadOnlyList<string>? AllowedPartnerIds { get; init; }
20 23  
21 24 public HashSet<Guid> SystemAdminCreatorIds { get; init; } = new();
... ... @@ -40,6 +43,8 @@ public static class PartnerScopedManagePermissionHelper
40 43  
41 44 var isScopedAdmin = await TeamMemberRoleHelper.IsScopedAdminUserAsync(
42 45 dbContext.SqlSugarClient, currentUser);
  46 + var isCompanyAdmin = await TeamMemberRoleHelper.IsCompanyAdminUserAsync(
  47 + dbContext.SqlSugarClient, currentUser);
43 48 var currentPartnerScope = await PartnerScopeHelper.ResolvePartnerScopeAsync(currentUser, dbContext);
44 49 var systemAdminCreatorIds = await TeamMemberRoleHelper.ResolveSystemAdminCreatorIdSetAsync(
45 50 dbContext.SqlSugarClient, allUserIds);
... ... @@ -79,6 +84,7 @@ public static class PartnerScopedManagePermissionHelper
79 84 return new ListEvaluationContext
80 85 {
81 86 IsScopedAdmin = isScopedAdmin,
  87 + IsCompanyAdmin = isCompanyAdmin,
82 88 AllowedPartnerIds = currentPartnerScope.AllowedPartnerIds,
83 89 SystemAdminCreatorIds = systemAdminCreatorIds,
84 90 CreatorPartnerMap = creatorPartnerMap,
... ... @@ -122,7 +128,8 @@ public static class PartnerScopedManagePermissionHelper
122 128 string? creatorId,
123 129 IReadOnlyList<string>? partnerIds,
124 130 string? entityId = null,
125   - string? lastModifierId = null)
  131 + string? lastModifierId = null,
  132 + bool allowSystemAdminCreated = false)
126 133 {
127 134 creatorId = ResolveCreatorIdForPermission(entityId, creatorId, lastModifierId);
128 135 var createdBySystemAdmin =
... ... @@ -152,7 +159,8 @@ public static class PartnerScopedManagePermissionHelper
152 159 creatorId,
153 160 context.ViewerRoleTier,
154 161 creatorRoleTier,
155   - allowSelfCreatedWithoutConcretePartner: true);
  162 + allowSelfCreatedWithoutConcretePartner: true,
  163 + allowSystemAdminCreated: allowSystemAdminCreated);
156 164 }
157 165  
158 166 public static async Task EnsureCanManageAsync(
... ...
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/ProductAppLabelingScopeHelper.cs
... ... @@ -26,7 +26,8 @@ public static class ProductAppLabelingScopeHelper
26 26 string locationId,
27 27 string? storePartnerId,
28 28 string? storePartnerName,
29   - string? storeGroupName)
  29 + string? storeGroupName,
  30 + IReadOnlyList<string>? storeGroupIds = null)
30 31 {
31 32 var loc = locationId.Trim();
32 33 var productIds = new HashSet<string>(StringComparer.Ordinal);
... ... @@ -40,6 +41,25 @@ public static class ProductAppLabelingScopeHelper
40 41 productIds.Add(id);
41 42 }
42 43  
  44 + // Region 范围 ALL(fl_product_region):门店所属 Region 命中即适用,区内新增门店自动生效
  45 + var groupIds = LocationScopeBindingHelper.NormalizeIds(storeGroupIds ?? Array.Empty<string>());
  46 + if (groupIds.Count > 0
  47 + && await ProductScopeSchemaHelper.HasRegionTableAsync(db))
  48 + {
  49 + var regionProductIds = await db.Queryable<FlProductDbEntity>()
  50 + .InnerJoin<FlProductRegionDbEntity>((p, pr) => p.Id == pr.ProductId)
  51 + .Where((p, pr) => !p.IsDeleted && p.State && groupIds.Contains(pr.GroupId))
  52 + .Select((p, pr) => p.Id)
  53 + .ToListAsync();
  54 + foreach (var id in regionProductIds)
  55 + {
  56 + if (!string.IsNullOrWhiteSpace(id))
  57 + {
  58 + productIds.Add(id.Trim());
  59 + }
  60 + }
  61 + }
  62 +
43 63 var hasAvailabilityColumn = await ProductScopeSchemaHelper.HasAvailabilityTypeColumnAsync(db);
44 64 if (!hasAvailabilityColumn)
45 65 {
... ...
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/ProductListScopeHelper.cs
... ... @@ -97,13 +97,23 @@ public static class ProductListScopeHelper
97 97 bool hasAvailabilityColumn,
98 98 bool hasAppliedRegionTypeColumn,
99 99 bool hasPartnerIdColumn,
100   - bool partnerOnlyFilter)
  100 + bool partnerOnlyFilter,
  101 + bool hasProductRegionTable = false,
  102 + IReadOnlyList<string>? scopedGroupIds = null)
101 103 {
102 104 if (scopedLocationIds is null)
103 105 {
104 106 return query;
105 107 }
106 108  
  109 + // Region 范围 ALL(fl_product_region):门店所属 Region 命中即视为可用
  110 + var regionExistsSql = hasProductRegionTable && scopedGroupIds is { Count: > 0 }
  111 + ? $"""
  112 + EXISTS (SELECT 1 FROM fl_product_region pr
  113 + WHERE pr.ProductId = fl_product.Id AND pr.GroupId IN (@scopedGroupIds))
  114 + """
  115 + : null;
  116 +
107 117 if (scopedLocationIds.Count == 0)
108 118 {
109 119 if (partnerOnlyFilter && hasAvailabilityColumn)
... ... @@ -141,6 +151,7 @@ public static class ProductListScopeHelper
141 151  
142 152 if (hasAvailabilityColumn && hasAppliedRegionTypeColumn && filterPartner is not null)
143 153 {
  154 + var regionOr = regionExistsSql is null ? string.Empty : $" OR {regionExistsSql}";
144 155 if (hasPartnerIdColumn)
145 156 {
146 157 return query.Where(
... ... @@ -149,7 +160,7 @@ public static class ProductListScopeHelper
149 160 OR (AppliedRegionType = @regionAll AND (PartnerId = @partnerId OR {ProductLocationUnderPartnerExistsSql}))
150 161 OR EXISTS (
151 162 SELECT 1 FROM fl_location_product lp
152   - WHERE lp.ProductId = fl_product.Id AND lp.LocationId IN (@locs)))
  163 + WHERE lp.ProductId = fl_product.Id AND lp.LocationId IN (@locs)){regionOr})
153 164 """,
154 165 new
155 166 {
... ... @@ -157,7 +168,8 @@ public static class ProductListScopeHelper
157 168 regionAll = AllScopeBindingHelper.ScopeAll,
158 169 partnerId = filterPartner.PartnerId,
159 170 partnerName = filterPartner.PartnerName,
160   - locs = scopedLocationIds
  171 + locs = scopedLocationIds,
  172 + scopedGroupIds = scopedGroupIds ?? new List<string>()
161 173 });
162 174 }
163 175  
... ... @@ -167,19 +179,38 @@ public static class ProductListScopeHelper
167 179 OR (AppliedRegionType = @regionAll AND {ProductLocationUnderPartnerExistsSql})
168 180 OR EXISTS (
169 181 SELECT 1 FROM fl_location_product lp
170   - WHERE lp.ProductId = fl_product.Id AND lp.LocationId IN (@locs)))
  182 + WHERE lp.ProductId = fl_product.Id AND lp.LocationId IN (@locs)){regionOr})
171 183 """,
172 184 new
173 185 {
174 186 availAll = AllScopeBindingHelper.ScopeAll,
175 187 regionAll = AllScopeBindingHelper.ScopeAll,
176 188 partnerName = filterPartner.PartnerName,
177   - locs = scopedLocationIds
  189 + locs = scopedLocationIds,
  190 + scopedGroupIds = scopedGroupIds ?? new List<string>()
178 191 });
179 192 }
180 193  
181 194 if (hasAvailabilityColumn)
182 195 {
  196 + if (regionExistsSql is not null)
  197 + {
  198 + return query.Where(
  199 + $"""
  200 + (AvailabilityType = @availAll
  201 + OR EXISTS (
  202 + SELECT 1 FROM fl_location_product lp
  203 + WHERE lp.ProductId = fl_product.Id AND lp.LocationId IN (@locs))
  204 + OR {regionExistsSql})
  205 + """,
  206 + new
  207 + {
  208 + availAll = AllScopeBindingHelper.ScopeAll,
  209 + locs = scopedLocationIds,
  210 + scopedGroupIds = scopedGroupIds ?? new List<string>()
  211 + });
  212 + }
  213 +
183 214 return query.Where(p =>
184 215 p.AvailabilityType == AllScopeBindingHelper.ScopeAll
185 216 || SqlFunc.Subqueryable<FlLocationProductDbEntity>()
... ...
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/ProductScopeSchemaHelper.cs
... ... @@ -10,6 +10,7 @@ public static class ProductScopeSchemaHelper
10 10 private static bool? _hasAvailabilityTypeColumn;
11 11 private static bool? _hasAppliedRegionTypeColumn;
12 12 private static bool? _hasPartnerIdColumn;
  13 + private static bool? _hasRegionTable;
13 14  
14 15 public static async Task<bool> HasAvailabilityTypeColumnAsync(ISqlSugarClient db)
15 16 {
... ... @@ -92,10 +93,41 @@ public static class ProductScopeSchemaHelper
92 93 return _hasPartnerIdColumn.Value;
93 94 }
94 95  
  96 + /// <summary>
  97 + /// 探测 <c>fl_product_region</c> 是否已落库,兼容未执行 DDL 的环境
  98 + /// (未迁移时回退为门店快照展开)。
  99 + /// </summary>
  100 + public static async Task<bool> HasRegionTableAsync(ISqlSugarClient db)
  101 + {
  102 + if (_hasRegionTable is not null)
  103 + {
  104 + return _hasRegionTable.Value;
  105 + }
  106 +
  107 + try
  108 + {
  109 + var tableCount = await db.Ado.GetIntAsync(
  110 + """
  111 + SELECT COUNT(*)
  112 + FROM information_schema.TABLES
  113 + WHERE TABLE_SCHEMA = DATABASE()
  114 + AND TABLE_NAME = 'fl_product_region'
  115 + """);
  116 + _hasRegionTable = tableCount > 0;
  117 + }
  118 + catch
  119 + {
  120 + _hasRegionTable = false;
  121 + }
  122 +
  123 + return _hasRegionTable.Value;
  124 + }
  125 +
95 126 public static void ResetCacheForTests()
96 127 {
97 128 _hasAvailabilityTypeColumn = null;
98 129 _hasAppliedRegionTypeColumn = null;
99 130 _hasPartnerIdColumn = null;
  131 + _hasRegionTable = null;
100 132 }
101 133 }
... ...
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/ScopedEntityManagePermissionHelper.cs 0 → 100644
  1 +using Volo.Abp;
  2 +using Volo.Abp.Users;
  3 +using Yi.Framework.SqlSugarCore.Abstractions;
  4 +
  5 +namespace FoodLabeling.Application.Helpers;
  6 +
  7 +/// <summary>
  8 +/// 标签实体(Type / Category 等)编辑/删除权限的共用判定:
  9 +/// <list type="bullet">
  10 +/// <item>平台管理员:全部可管;</item>
  11 +/// <item>Scoped Admin(Company / Regional / Location Admin):只能管理「自己创建的」与「下级创建的」;</item>
  12 +/// <item>上级创建的(含 Super Admin)、同级创建的(如另一个 Company Admin)一律不可管理;</item>
  13 +/// <item>下级创建的还要求:创建人属于当前用户公司范围,且实体本身也在当前用户公司范围内。</item>
  14 +/// </list>
  15 +/// 角色层级:System(0) &gt; Company(1) &gt; Regional(2) &gt; Location(3) &gt; Staff(4),数值越小权限越高。
  16 +/// </summary>
  17 +public static class ScopedEntityManagePermissionHelper
  18 +{
  19 + /// <summary>列表行 canManage。</summary>
  20 + public static bool Evaluate(
  21 + ICurrentUser currentUser,
  22 + PartnerScopedManagePermissionHelper.ListEvaluationContext context,
  23 + string entityId,
  24 + string? creatorId,
  25 + string? lastModifierId,
  26 + IReadOnlyList<string>? entityPartnerIds,
  27 + string? appliedPartnerType)
  28 + {
  29 + if (ReportsRoleHelper.IsAdminRole(currentUser))
  30 + {
  31 + return true;
  32 + }
  33 +
  34 + if (!context.IsScopedAdmin)
  35 + {
  36 + return false;
  37 + }
  38 +
  39 + var creatorIdForManage = PartnerScopedManagePermissionHelper.ResolveCreatorIdForPermission(
  40 + entityId, creatorId, lastModifierId);
  41 +
  42 + // 自己创建的:可管
  43 + if (LabelTemplateManagePermissionHelper.IsCreatorCurrentUser(currentUser, creatorIdForManage))
  44 + {
  45 + return true;
  46 + }
  47 +
  48 + // 下级创建的:可管(同级 / 上级一律不可),且实体本身须在本人公司范围内
  49 + return CanManageSubordinateCreated(context, creatorIdForManage)
  50 + && EntityInViewerCompany(appliedPartnerType, entityPartnerIds, context.AllowedPartnerIds);
  51 + }
  52 +
  53 + /// <summary>编辑/删除前置校验。</summary>
  54 + public static async Task EnsureCanManageAsync(
  55 + ICurrentUser currentUser,
  56 + ISqlSugarDbContext dbContext,
  57 + LabelEntityPartnerScopeHelper.LabelEntityPartnerKind kind,
  58 + string entityId,
  59 + string? creatorId,
  60 + string? lastModifierId,
  61 + string? appliedPartnerType,
  62 + string unauthorizedMessage)
  63 + {
  64 + if (ReportsRoleHelper.IsAdminRole(currentUser))
  65 + {
  66 + return;
  67 + }
  68 +
  69 + var creatorIdForManage = PartnerScopedManagePermissionHelper.ResolveCreatorIdForPermission(
  70 + entityId, creatorId, lastModifierId);
  71 +
  72 + var context = await PartnerScopedManagePermissionHelper.BuildListContextAsync(
  73 + currentUser,
  74 + dbContext,
  75 + new[] { creatorIdForManage },
  76 + new[] { lastModifierId });
  77 +
  78 + var entityPartnerIds = await LoadEntityPartnerIdsAsync(dbContext, kind, entityId);
  79 +
  80 + if (LabelTemplateManagePermissionHelper.IsCreatorCurrentUser(currentUser, creatorIdForManage)
  81 + || (CanManageSubordinateCreated(context, creatorIdForManage)
  82 + && EntityInViewerCompany(appliedPartnerType, entityPartnerIds, context.AllowedPartnerIds)))
  83 + {
  84 + return;
  85 + }
  86 +
  87 + throw new UserFriendlyException(unauthorizedMessage);
  88 + }
  89 +
  90 + private static async Task<List<string>> LoadEntityPartnerIdsAsync(
  91 + ISqlSugarDbContext dbContext,
  92 + LabelEntityPartnerScopeHelper.LabelEntityPartnerKind kind,
  93 + string entityId)
  94 + {
  95 + var map = await LabelEntityPartnerScopeHelper.BuildPartnerScopeDisplayMapAsync(
  96 + dbContext.SqlSugarClient,
  97 + kind,
  98 + new List<string> { entityId });
  99 + return map.TryGetValue(entityId, out var scope)
  100 + ? scope.PartnerIds ?? new List<string>()
  101 + : new List<string>();
  102 + }
  103 +
  104 + /// <summary>实体 Company 范围是否包含当前用户公司(全局 ALL 视为包含)。</summary>
  105 + private static bool EntityInViewerCompany(
  106 + string? appliedPartnerType,
  107 + IReadOnlyList<string>? entityPartnerIds,
  108 + IReadOnlyList<string>? allowedPartnerIds)
  109 + {
  110 + if (AllScopeBindingHelper.IsDeclaredAll(appliedPartnerType))
  111 + {
  112 + return true;
  113 + }
  114 +
  115 + var entityIds = Normalize(entityPartnerIds);
  116 + if (entityIds.Any(id => string.Equals(id, AllScopeBindingHelper.ScopeAll, StringComparison.OrdinalIgnoreCase)))
  117 + {
  118 + return true;
  119 + }
  120 +
  121 + var allowed = Normalize(allowedPartnerIds);
  122 + return allowed.Count > 0
  123 + && entityIds.Any(id => allowed.Contains(id, StringComparer.OrdinalIgnoreCase));
  124 + }
  125 +
  126 + /// <summary>
  127 + /// 创建人是否为当前用户的下级(层级数值更大),且创建人属于当前用户的公司范围。
  128 + /// </summary>
  129 + private static bool CanManageSubordinateCreated(
  130 + PartnerScopedManagePermissionHelper.ListEvaluationContext context,
  131 + string? creatorId)
  132 + {
  133 + if (!Guid.TryParse(creatorId?.Trim(), out var creatorGuid))
  134 + {
  135 + return false;
  136 + }
  137 +
  138 + // 当前用户必须能解析出层级(平台管理员已在上层返回)
  139 + if (context.ViewerRoleTier is not { } viewerTier)
  140 + {
  141 + return false;
  142 + }
  143 +
  144 + // 创建人层级必须低于当前用户;查不到层级(如 Super Admin / 无角色)视为上级,不放行
  145 + if (!context.CreatorRoleTierMap.TryGetValue(creatorGuid, out var creatorTier)
  146 + || viewerTier >= creatorTier)
  147 + {
  148 + return false;
  149 + }
  150 +
  151 + // 创建人必须属于当前用户的公司范围(系统管理员创建人不在此 map 中)
  152 + if (!context.CreatorPartnerMap.TryGetValue(creatorGuid, out var creatorPartnerIds))
  153 + {
  154 + return false;
  155 + }
  156 +
  157 + var allowed = Normalize(context.AllowedPartnerIds);
  158 + if (allowed.Count == 0)
  159 + {
  160 + return false;
  161 + }
  162 +
  163 + return creatorPartnerIds.Any(pid => allowed.Contains(pid?.Trim() ?? string.Empty, StringComparer.OrdinalIgnoreCase));
  164 + }
  165 +
  166 + private static List<string> Normalize(IReadOnlyList<string>? ids) =>
  167 + (ids ?? Array.Empty<string>())
  168 + .Select(x => x?.Trim())
  169 + .Where(x => !string.IsNullOrWhiteSpace(x))
  170 + .Select(x => x!)
  171 + .Distinct(StringComparer.OrdinalIgnoreCase)
  172 + .ToList();
  173 +}
... ...
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/DbModels/FlLabelCategoryRegionDbEntity.cs 0 → 100644
  1 +using SqlSugar;
  2 +
  3 +namespace FoodLabeling.Application.Services.DbModels;
  4 +
  5 +/// <summary>
  6 +/// 标签分类适用 Region 关联(对应表:fl_label_category_region,<c>GroupId</c> 为 <c>fl_group.Id</c>)。
  7 +/// 用于表达「所选 Region 内全部门店」的范围 ALL:只落 Region 绑定、不落门店快照。
  8 +/// </summary>
  9 +[SugarTable("fl_label_category_region")]
  10 +public class FlLabelCategoryRegionDbEntity
  11 +{
  12 + [SugarColumn(IsPrimaryKey = true)]
  13 + public string Id { get; set; } = string.Empty;
  14 +
  15 + public string CategoryId { get; set; } = string.Empty;
  16 +
  17 + public string GroupId { get; set; } = string.Empty;
  18 +
  19 + public DateTime CreationTime { get; set; }
  20 +
  21 + public string? CreatorId { get; set; }
  22 +}
... ...
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/DbModels/FlLabelMultipleOptionRegionDbEntity.cs 0 → 100644
  1 +using SqlSugar;
  2 +
  3 +namespace FoodLabeling.Application.Services.DbModels;
  4 +
  5 +/// <summary>
  6 +/// 标签多选项适用 Region 关联(对应表:fl_label_multiple_option_region,<c>GroupId</c> 为 <c>fl_group.Id</c>)。
  7 +/// 用于表达「所选 Region 内全部门店」的范围 ALL:只落 Region 绑定、不落门店快照。
  8 +/// </summary>
  9 +[SugarTable("fl_label_multiple_option_region")]
  10 +public class FlLabelMultipleOptionRegionDbEntity
  11 +{
  12 + [SugarColumn(IsPrimaryKey = true)]
  13 + public string Id { get; set; } = string.Empty;
  14 +
  15 + public string MultipleOptionId { get; set; } = string.Empty;
  16 +
  17 + public string GroupId { get; set; } = string.Empty;
  18 +
  19 + public DateTime CreationTime { get; set; }
  20 +
  21 + public string? CreatorId { get; set; }
  22 +}
... ...
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/DbModels/FlLabelTypeRegionDbEntity.cs 0 → 100644
  1 +using SqlSugar;
  2 +
  3 +namespace FoodLabeling.Application.Services.DbModels;
  4 +
  5 +/// <summary>
  6 +/// 标签类型适用 Region 关联(对应表:fl_label_type_region,<c>GroupId</c> 为 <c>fl_group.Id</c>)。
  7 +/// 用于表达「所选 Region 内全部门店」的范围 ALL:只落 Region 绑定、不落门店快照。
  8 +/// </summary>
  9 +[SugarTable("fl_label_type_region")]
  10 +public class FlLabelTypeRegionDbEntity
  11 +{
  12 + [SugarColumn(IsPrimaryKey = true)]
  13 + public string Id { get; set; } = string.Empty;
  14 +
  15 + public string LabelTypeId { get; set; } = string.Empty;
  16 +
  17 + public string GroupId { get; set; } = string.Empty;
  18 +
  19 + public DateTime CreationTime { get; set; }
  20 +
  21 + public string? CreatorId { get; set; }
  22 +}
... ...
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/DbModels/FlProductRegionDbEntity.cs 0 → 100644
  1 +using SqlSugar;
  2 +
  3 +namespace FoodLabeling.Application.Services.DbModels;
  4 +
  5 +/// <summary>
  6 +/// 产品适用 Region 关联(对应表:fl_product_region,<c>GroupId</c> 为 <c>fl_group.Id</c>)。
  7 +/// 用于表达「所选 Region 下全部门店」的范围 ALL:只落 Region 绑定、不落门店快照,
  8 +/// 该 Region 后续新增门店可自动适用。
  9 +/// </summary>
  10 +[SugarTable("fl_product_region")]
  11 +public class FlProductRegionDbEntity
  12 +{
  13 + [SugarColumn(IsPrimaryKey = true)]
  14 + public string Id { get; set; } = string.Empty;
  15 +
  16 + public string ProductId { get; set; } = string.Empty;
  17 +
  18 + public string GroupId { get; set; } = string.Empty;
  19 +
  20 + public DateTime CreationTime { get; set; }
  21 +
  22 + public string? CreatorId { get; set; }
  23 +}
... ...
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/LabelAppService.cs
... ... @@ -87,13 +87,15 @@ public class LabelAppService : ApplicationService, ILabelAppService
87 87 labelIdsQuery = LabelRegionScopeHelper.ApplyLabelAllRegionOnlyFilter(
88 88 db, labelIdsQuery, regionSchema);
89 89 }
90   - else if (!string.IsNullOrWhiteSpace(filterGroupId))
  90 + else if (!string.IsNullOrWhiteSpace(filterGroupId) && string.IsNullOrWhiteSpace(locationId))
91 91 {
  92 + // 仅按 Region 筛选:区域内全部标签(含 Region 绑定、无门店快照的标签)
92 93 labelIdsQuery = await LabelRegionScopeHelper.ApplyLabelRegionListFilterAsync(
93 94 db, labelIdsQuery, filterGroupId, scopedLocationIds, regionSchema);
94 95 }
95 96 else
96 97 {
  98 + // 指定了 Location(即使同时传了 GroupId):按门店精确筛选,Region 不放大范围
97 99 labelIdsQuery = await LabelRegionScopeHelper.ApplyLabelLocationListFilterAsync(
98 100 db, labelIdsQuery, scopedLocationIds, regionSchema);
99 101 }
... ...
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/LabelCategoryAppService.cs
... ... @@ -86,23 +86,14 @@ public class LabelCategoryAppService : ApplicationService, ILabelCategoryAppServ
86 86 labelStatsMap.TryGetValue(x.Id, out var labelStats);
87 87 var creationTime = ResolveCategoryCreationTime(x);
88 88 var partnerIds = partnerScope?.PartnerIds ?? new List<string>();
89   - var partnerIdsForManage = PartnerScopedManagePermissionHelper.ResolvePartnerScopedEntityPartnerIdsForManageFromEcho(
90   - x.AvailabilityType,
91   - x.AppliedRegionType,
92   - partnerScope?.AppliedPartnerType ?? x.AppliedPartnerType,
93   - scope?.RegionIds,
94   - scope?.LocationIds,
95   - partnerIds);
96 89 var createdBySystemAdmin =
97 90 Guid.TryParse(x.CreatorId?.Trim(), out var creatorGuid) &&
98 91 manageCtx.SystemAdminCreatorIds.Contains(creatorGuid);
99   - var canManage = PartnerScopedManagePermissionHelper.EvaluateCanManage(
  92 + var canManage = LabelCategoryManagePermissionHelper.EvaluateRow(
100 93 CurrentUser,
101 94 manageCtx,
102   - x.CreatorId,
103   - partnerIdsForManage,
104   - x.Id,
105   - x.LastModifierId);
  95 + x,
  96 + partnerIds);
106 97 return new LabelCategoryGetListOutputDto
107 98 {
108 99 Id = x.Id,
... ... @@ -161,8 +152,14 @@ public class LabelCategoryAppService : ApplicationService, ILabelCategoryAppServ
161 152 .Select(x => x.LocationId)
162 153 .ToListAsync();
163 154 dto.LocationIds = LocationScopeBindingHelper.NormalizeIds(locationIds);
164   - var regionIds = await LocationScopeBindingHelper.ResolveGroupIdsFromLocationIdsAsync(
165   - _dbContext.SqlSugarClient, dto.LocationIds);
  155 + // Region 范围 ALL:只落了 Region 绑定、无门店快照时用持久化 Region 回显,
  156 + // 再由 ScopeAllEchoHelper 折叠为 locationIds=["ALL"]。
  157 + var persistedRegionIds = await LabelEntityRegionScopeStore.LoadRegionIdsAsync(
  158 + _dbContext.SqlSugarClient, LabelEntityRegionScopeStore.Kind.Category, entity.Id);
  159 + var regionIds = persistedRegionIds.Count > 0
  160 + ? persistedRegionIds
  161 + : await LocationScopeBindingHelper.ResolveGroupIdsFromLocationIdsAsync(
  162 + _dbContext.SqlSugarClient, dto.LocationIds);
166 163 dto.RegionIds = regionIds;
167 164 dto.GroupIds = regionIds;
168 165 if (dto.LocationIds.Count > 0 || dto.RegionIds.Count > 0)
... ... @@ -202,7 +199,7 @@ public class LabelCategoryAppService : ApplicationService, ILabelCategoryAppServ
202 199  
203 200 var displayText = input.DisplayText?.Trim();
204 201 var appearance = CategoryAppearanceStorageHelper.NormalizeButtonAppearanceForStorage(input.ButtonAppearance);
205   - var (partnerScope, availabilityType, appliedRegionType, mergedLocationIds) = await ResolveCategoryScopeForSaveAsync(input);
  202 + var (partnerScope, availabilityType, appliedRegionType, mergedLocationIds, mergedRegionIds) = await ResolveCategoryScopeForSaveAsync(input);
206 203  
207 204 await EnsureLabelCategoryNotDuplicatedAsync(code, name, partnerScope);
208 205  
... ... @@ -234,6 +231,14 @@ public class LabelCategoryAppService : ApplicationService, ILabelCategoryAppServ
234 231 await _dbContext.SqlSugarClient.Insertable(entity).ExecuteCommandAsync();
235 232 await SaveCategoryPartnerScopeAsync(entity.Id, partnerScope, currentUserId, now);
236 233 await SaveCategoryLocationsAsync(entity.Id, availabilityType, mergedLocationIds, currentUserId, now);
  234 + await LabelEntityRegionScopeStore.ReplaceAsync(
  235 + _dbContext.SqlSugarClient,
  236 + LabelEntityRegionScopeStore.Kind.Category,
  237 + entity.Id,
  238 + mergedRegionIds,
  239 + _guidGenerator,
  240 + currentUserId,
  241 + now);
237 242 return await GetAsync(entity.Id);
238 243 }
239 244  
... ... @@ -246,12 +251,10 @@ public class LabelCategoryAppService : ApplicationService, ILabelCategoryAppServ
246 251 throw new UserFriendlyException("Label category not found.");
247 252 }
248 253  
249   - await PartnerScopedManagePermissionHelper.EnsureCanManagePartnerEntityAsync(
  254 + await LabelCategoryManagePermissionHelper.EnsureCanManageAsync(
250 255 CurrentUser,
251 256 _dbContext,
252   - LabelEntityPartnerScopeHelper.LabelEntityPartnerKind.Category,
253   - entity.Id,
254   - entity.CreatorId,
  257 + entity,
255 258 "You are not authorized to edit or delete this Label Category.");
256 259  
257 260 var code = input.CategoryCode?.Trim();
... ... @@ -263,7 +266,7 @@ public class LabelCategoryAppService : ApplicationService, ILabelCategoryAppServ
263 266  
264 267 var displayText = input.DisplayText?.Trim();
265 268 var appearance = CategoryAppearanceStorageHelper.NormalizeButtonAppearanceForStorage(input.ButtonAppearance);
266   - var (partnerScope, availabilityType, appliedRegionType, mergedLocationIds) = await ResolveCategoryScopeForSaveAsync(input);
  269 + var (partnerScope, availabilityType, appliedRegionType, mergedLocationIds, mergedRegionIds) = await ResolveCategoryScopeForSaveAsync(input);
267 270  
268 271 await EnsureLabelCategoryNotDuplicatedAsync(code, name, partnerScope, id);
269 272  
... ... @@ -301,6 +304,14 @@ public class LabelCategoryAppService : ApplicationService, ILabelCategoryAppServ
301 304 entity.LastModificationTime ?? DateTime.Now);
302 305 await SaveCategoryLocationsAsync(entity.Id, availabilityType, mergedLocationIds, entity.LastModifierId,
303 306 entity.LastModificationTime ?? DateTime.Now);
  307 + await LabelEntityRegionScopeStore.ReplaceAsync(
  308 + _dbContext.SqlSugarClient,
  309 + LabelEntityRegionScopeStore.Kind.Category,
  310 + entity.Id,
  311 + mergedRegionIds,
  312 + _guidGenerator,
  313 + entity.LastModifierId,
  314 + entity.LastModificationTime ?? DateTime.Now);
304 315 return await GetAsync(id);
305 316 }
306 317  
... ... @@ -313,12 +324,10 @@ public class LabelCategoryAppService : ApplicationService, ILabelCategoryAppServ
313 324 return;
314 325 }
315 326  
316   - await PartnerScopedManagePermissionHelper.EnsureCanManagePartnerEntityAsync(
  327 + await LabelCategoryManagePermissionHelper.EnsureCanManageAsync(
317 328 CurrentUser,
318 329 _dbContext,
319   - LabelEntityPartnerScopeHelper.LabelEntityPartnerKind.Category,
320   - entity.Id,
321   - entity.CreatorId,
  330 + entity,
322 331 "You are not authorized to edit or delete this Label Category.");
323 332  
324 333 var used = await _dbContext.SqlSugarClient.Queryable<FlLabelDbEntity>()
... ... @@ -335,6 +344,8 @@ public class LabelCategoryAppService : ApplicationService, ILabelCategoryAppServ
335 344 await _dbContext.SqlSugarClient.Deleteable<FlLabelCategoryLocationDbEntity>()
336 345 .Where(x => x.CategoryId == id)
337 346 .ExecuteCommandAsync();
  347 + await LabelEntityRegionScopeStore.DeleteByEntityAsync(
  348 + _dbContext.SqlSugarClient, LabelEntityRegionScopeStore.Kind.Category, id);
338 349  
339 350 entity.IsDeleted = true;
340 351 entity.LastModificationTime = DateTime.Now;
... ... @@ -362,7 +373,7 @@ public class LabelCategoryAppService : ApplicationService, ILabelCategoryAppServ
362 373 };
363 374 }
364 375  
365   - private async Task<(LabelEntityPartnerScopeHelper.LabelEntityPartnerScopeSaveResult PartnerScope, string AvailabilityType, string AppliedRegionType, List<string> LocationIds)> ResolveCategoryScopeForSaveAsync(
  376 + private async Task<(LabelEntityPartnerScopeHelper.LabelEntityPartnerScopeSaveResult PartnerScope, string AvailabilityType, string AppliedRegionType, List<string> LocationIds, List<string> RegionIds)> ResolveCategoryScopeForSaveAsync(
366 377 LabelCategoryCreateInputVo input)
367 378 {
368 379 var partnerScope = await LabelEntityPartnerScopeHelper.ResolvePartnerScopeForSaveAsync(
... ... @@ -389,6 +400,7 @@ public class LabelCategoryAppService : ApplicationService, ILabelCategoryAppServ
389 400 partnerScope,
390 401 AllScopeBindingHelper.ScopeAll,
391 402 AllScopeBindingHelper.ScopeAll,
  403 + new List<string>(),
392 404 new List<string>());
393 405 }
394 406  
... ... @@ -400,12 +412,19 @@ public class LabelCategoryAppService : ApplicationService, ILabelCategoryAppServ
400 412 input.LocationIds,
401 413 hasScopeArrays);
402 414  
403   - locScope = await AllScopeBindingHelper.ExpandScopedRegionLocationAllForLegacyEntitySaveAsync(
404   - _dbContext.SqlSugarClient,
405   - locScope,
406   - partnerContext);
  415 + // 「所选 Region 内全部门店」:有 fl_label_category_region 时只落 Region 绑定,
  416 + // 未迁移时回退为展开区内门店快照。
  417 + if (!locScope.IsScopedRegionLocationAll
  418 + || !await LabelEntityRegionScopeStore.HasTableAsync(
  419 + _dbContext.SqlSugarClient, LabelEntityRegionScopeStore.Kind.Category))
  420 + {
  421 + locScope = await AllScopeBindingHelper.ExpandScopedRegionLocationAllForLegacyEntitySaveAsync(
  422 + _dbContext.SqlSugarClient,
  423 + locScope,
  424 + partnerContext);
  425 + }
407 426  
408   - return (partnerScope, locScope.AvailabilityType, locScope.AppliedRegionType, locScope.LocationIds);
  427 + return (partnerScope, locScope.AvailabilityType, locScope.AppliedRegionType, locScope.LocationIds, locScope.RegionIds);
409 428 }
410 429  
411 430 private static List<string> NormalizeRegionIds(LabelCategoryCreateInputVo input)
... ... @@ -450,7 +469,14 @@ public class LabelCategoryAppService : ApplicationService, ILabelCategoryAppServ
450 469 return query;
451 470 }
452 471  
453   - return LabelEntityListScopeHelper.ApplyCategoryLocationAvailabilityFilter(query, scopedLocationIds);
  472 + var hasCategoryRegionTable = await LabelEntityRegionScopeStore.HasTableAsync(
  473 + _dbContext.SqlSugarClient, LabelEntityRegionScopeStore.Kind.Category);
  474 + var scopedGroupIds = scopedLocationIds is { Count: > 0 }
  475 + ? await LocationScopeBindingHelper.ResolveGroupIdsFromLocationIdsAsync(
  476 + _dbContext.SqlSugarClient, scopedLocationIds)
  477 + : new List<string>();
  478 + return LabelEntityListScopeHelper.ApplyCategoryLocationAvailabilityFilter(
  479 + query, scopedLocationIds, hasCategoryRegionTable, scopedGroupIds);
454 480 }
455 481  
456 482 private async Task SaveCategoryPartnerScopeAsync(
... ... @@ -531,6 +557,8 @@ public class LabelCategoryAppService : ApplicationService, ILabelCategoryAppServ
531 557 await _dbContext.SqlSugarClient.Deleteable<FlLabelCategoryLocationDbEntity>()
532 558 .Where(x => x.CategoryId == row.Id)
533 559 .ExecuteCommandAsync();
  560 + await LabelEntityRegionScopeStore.DeleteByEntityAsync(
  561 + _dbContext.SqlSugarClient, LabelEntityRegionScopeStore.Kind.Category, row.Id);
534 562 await _dbContext.SqlSugarClient.Deleteable<FlLabelCategoryDbEntity>()
535 563 .Where(x => x.Id == row.Id)
536 564 .ExecuteCommandAsync();
... ... @@ -577,6 +605,26 @@ public class LabelCategoryAppService : ApplicationService, ILabelCategoryAppServ
577 605 .Where(x => specifiedIds.Contains(x.CategoryId))
578 606 .ToListAsync();
579 607  
  608 + // Region 范围 ALL:分类可能只落 fl_label_category_region、没有门店快照
  609 + var regionIdsByCategory = await LabelEntityRegionScopeStore.LoadRegionIdsMapAsync(
  610 + _dbContext.SqlSugarClient, LabelEntityRegionScopeStore.Kind.Category, specifiedIds);
  611 + var persistedGroupIds = regionIdsByCategory.Values
  612 + .SelectMany(x => x)
  613 + .Distinct(StringComparer.Ordinal)
  614 + .ToList();
  615 + var groupNameById = new Dictionary<string, string>(StringComparer.Ordinal);
  616 + if (persistedGroupIds.Count > 0)
  617 + {
  618 + var groups = await _dbContext.SqlSugarClient.Queryable<FlGroupDbEntity>()
  619 + .Where(g => !g.IsDeleted && persistedGroupIds.Contains(g.Id))
  620 + .Select(g => new { g.Id, g.GroupName })
  621 + .ToListAsync();
  622 + foreach (var g in groups)
  623 + {
  624 + groupNameById[g.Id] = g.GroupName?.Trim() ?? string.Empty;
  625 + }
  626 + }
  627 +
580 628 var locIdSet = links
581 629 .Select(x => x.LocationId)
582 630 .Where(x => !string.IsNullOrWhiteSpace(x))
... ... @@ -605,8 +653,10 @@ public class LabelCategoryAppService : ApplicationService, ILabelCategoryAppServ
605 653 var catLinks = links.Where(x => x.CategoryId == catId).ToList();
606 654 var locationIds = LocationScopeBindingHelper.NormalizeIds(
607 655 catLinks.Select(x => x.LocationId).ToList());
  656 + regionIdsByCategory.TryGetValue(catId, out var persistedRegionIds);
  657 + persistedRegionIds ??= new List<string>();
608 658  
609   - if (catLinks.Count == 0)
  659 + if (catLinks.Count == 0 && persistedRegionIds.Count == 0)
610 660 {
611 661 result[catId] = new CategoryScopeData
612 662 {
... ... @@ -646,8 +696,17 @@ public class LabelCategoryAppService : ApplicationService, ILabelCategoryAppServ
646 696 }
647 697 }
648 698  
649   - var regionIds = await LocationScopeBindingHelper.ResolveGroupIdsFromLocationIdsAsync(
650   - _dbContext.SqlSugarClient, locationIds);
  699 + var regionIds = persistedRegionIds.Count > 0
  700 + ? persistedRegionIds
  701 + : await LocationScopeBindingHelper.ResolveGroupIdsFromLocationIdsAsync(
  702 + _dbContext.SqlSugarClient, locationIds);
  703 + foreach (var gid in regionIds)
  704 + {
  705 + if (groupNameById.TryGetValue(gid, out var groupName) && !string.IsNullOrWhiteSpace(groupName))
  706 + {
  707 + regions.Add(groupName!);
  708 + }
  709 + }
651 710  
652 711 entityById.TryGetValue(catId, out var entity);
653 712 partnerScopeMap.TryGetValue(catId, out var partnerScope);
... ...
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/LabelMultipleOptionAppService.cs
... ... @@ -47,8 +47,14 @@ public class LabelMultipleOptionAppService : ApplicationService, ILabelMultipleO
47 47 if (LabelEntityListScopeHelper.ShouldApplyLocationAvailabilityFilterForList(
48 48 input.PartnerId, input.GroupId, input.LocationId, !userPartnerScope.IsUnrestricted))
49 49 {
  50 + var hasOptionRegionTable = await LabelEntityRegionScopeStore.HasTableAsync(
  51 + _dbContext.SqlSugarClient, LabelEntityRegionScopeStore.Kind.MultipleOption);
  52 + var scopedGroupIds = scopedLocationIds is { Count: > 0 }
  53 + ? await LocationScopeBindingHelper.ResolveGroupIdsFromLocationIdsAsync(
  54 + _dbContext.SqlSugarClient, scopedLocationIds)
  55 + : new List<string>();
50 56 query = LabelEntityListScopeHelper.ApplyMultipleOptionLocationAvailabilityFilter(
51   - query, scopedLocationIds);
  57 + query, scopedLocationIds, hasOptionRegionTable, scopedGroupIds);
52 58 }
53 59  
54 60 if (!string.IsNullOrWhiteSpace(input.Sorting))
... ... @@ -149,8 +155,14 @@ public class LabelMultipleOptionAppService : ApplicationService, ILabelMultipleO
149 155 .Select(x => x.LocationId)
150 156 .ToListAsync();
151 157 dto.LocationIds = LocationScopeBindingHelper.NormalizeIds(locationIds);
152   - var regionIds = await LocationScopeBindingHelper.ResolveGroupIdsFromLocationIdsAsync(
153   - _dbContext.SqlSugarClient, locationIds);
  158 + // Region 范围 ALL:只落了 Region 绑定、无门店快照时用持久化 Region 回显,
  159 + // 再由 ScopeAllEchoHelper 折叠为 locationIds=["ALL"]。
  160 + var persistedRegionIds = await LabelEntityRegionScopeStore.LoadRegionIdsAsync(
  161 + _dbContext.SqlSugarClient, LabelEntityRegionScopeStore.Kind.MultipleOption, entity.Id);
  162 + var regionIds = persistedRegionIds.Count > 0
  163 + ? persistedRegionIds
  164 + : await LocationScopeBindingHelper.ResolveGroupIdsFromLocationIdsAsync(
  165 + _dbContext.SqlSugarClient, locationIds);
154 166 dto.RegionIds = regionIds;
155 167 dto.GroupIds = regionIds;
156 168 // 有具体门店/Region 快照时,即使历史误存 AppliedRegionType=ALL 也按 SPECIFIED 回显
... ... @@ -193,7 +205,7 @@ public class LabelMultipleOptionAppService : ApplicationService, ILabelMultipleO
193 205 throw new UserFriendlyException("Multiple option name is required.");
194 206 }
195 207  
196   - var (partnerScope, availabilityType, appliedRegionType, mergedLocationIds) = await ResolveMultipleOptionScopeForSaveAsync(input);
  208 + var (partnerScope, availabilityType, appliedRegionType, mergedLocationIds, mergedRegionIds) = await ResolveMultipleOptionScopeForSaveAsync(input);
197 209  
198 210 await EnsureMultipleOptionNotDuplicatedAsync(code, name, partnerScope);
199 211  
... ... @@ -227,6 +239,14 @@ public class LabelMultipleOptionAppService : ApplicationService, ILabelMultipleO
227 239 await _dbContext.SqlSugarClient.Insertable(entity).ExecuteCommandAsync();
228 240 await SaveMultipleOptionPartnerScopeAsync(entity.Id, partnerScope, currentUserId, now);
229 241 await SaveMultipleOptionLocationsAsync(entity.Id, availabilityType, mergedLocationIds, currentUserId, now);
  242 + await LabelEntityRegionScopeStore.ReplaceAsync(
  243 + _dbContext.SqlSugarClient,
  244 + LabelEntityRegionScopeStore.Kind.MultipleOption,
  245 + entity.Id,
  246 + mergedRegionIds,
  247 + _guidGenerator,
  248 + currentUserId,
  249 + now);
230 250 return await GetAsync(entity.Id);
231 251 }
232 252  
... ... @@ -252,7 +272,7 @@ public class LabelMultipleOptionAppService : ApplicationService, ILabelMultipleO
252 272 throw new UserFriendlyException("Multiple option name is required.");
253 273 }
254 274  
255   - var (partnerScope, availabilityType, appliedRegionType, mergedLocationIds) = await ResolveMultipleOptionScopeForSaveAsync(input);
  275 + var (partnerScope, availabilityType, appliedRegionType, mergedLocationIds, mergedRegionIds) = await ResolveMultipleOptionScopeForSaveAsync(input);
256 276  
257 277 await EnsureMultipleOptionNotDuplicatedAsync(code, name, partnerScope, id);
258 278  
... ... @@ -286,6 +306,14 @@ public class LabelMultipleOptionAppService : ApplicationService, ILabelMultipleO
286 306 entity.LastModificationTime ?? DateTime.Now);
287 307 await SaveMultipleOptionLocationsAsync(entity.Id, availabilityType, mergedLocationIds, entity.LastModifierId,
288 308 entity.LastModificationTime ?? DateTime.Now);
  309 + await LabelEntityRegionScopeStore.ReplaceAsync(
  310 + _dbContext.SqlSugarClient,
  311 + LabelEntityRegionScopeStore.Kind.MultipleOption,
  312 + entity.Id,
  313 + mergedRegionIds,
  314 + _guidGenerator,
  315 + entity.LastModifierId,
  316 + entity.LastModificationTime ?? DateTime.Now);
289 317 return await GetAsync(id);
290 318 }
291 319  
... ... @@ -307,6 +335,8 @@ public class LabelMultipleOptionAppService : ApplicationService, ILabelMultipleO
307 335 await _dbContext.SqlSugarClient.Deleteable<FlLabelMultipleOptionLocationDbEntity>()
308 336 .Where(x => x.MultipleOptionId == id)
309 337 .ExecuteCommandAsync();
  338 + await LabelEntityRegionScopeStore.DeleteByEntityAsync(
  339 + _dbContext.SqlSugarClient, LabelEntityRegionScopeStore.Kind.MultipleOption, id);
310 340  
311 341 entity.IsDeleted = true;
312 342 entity.LastModificationTime = DateTime.Now;
... ... @@ -340,13 +370,15 @@ public class LabelMultipleOptionAppService : ApplicationService, ILabelMultipleO
340 370 await _dbContext.SqlSugarClient.Deleteable<FlLabelMultipleOptionLocationDbEntity>()
341 371 .Where(x => x.MultipleOptionId == row.Id)
342 372 .ExecuteCommandAsync();
  373 + await LabelEntityRegionScopeStore.DeleteByEntityAsync(
  374 + _dbContext.SqlSugarClient, LabelEntityRegionScopeStore.Kind.MultipleOption, row.Id);
343 375 await _dbContext.SqlSugarClient.Deleteable<FlLabelMultipleOptionDbEntity>()
344 376 .Where(x => x.Id == row.Id)
345 377 .ExecuteCommandAsync();
346 378 }
347 379 }
348 380  
349   - private async Task<(LabelEntityPartnerScopeHelper.LabelEntityPartnerScopeSaveResult PartnerScope, string AvailabilityType, string AppliedRegionType, List<string> LocationIds)> ResolveMultipleOptionScopeForSaveAsync(
  381 + private async Task<(LabelEntityPartnerScopeHelper.LabelEntityPartnerScopeSaveResult PartnerScope, string AvailabilityType, string AppliedRegionType, List<string> LocationIds, List<string> RegionIds)> ResolveMultipleOptionScopeForSaveAsync(
350 382 LabelMultipleOptionCreateInputVo input)
351 383 {
352 384 var partnerScope = await LabelEntityPartnerScopeHelper.ResolvePartnerScopeForSaveAsync(
... ... @@ -373,6 +405,7 @@ public class LabelMultipleOptionAppService : ApplicationService, ILabelMultipleO
373 405 partnerScope,
374 406 AllScopeBindingHelper.ScopeAll,
375 407 AllScopeBindingHelper.ScopeAll,
  408 + new List<string>(),
376 409 new List<string>());
377 410 }
378 411  
... ... @@ -384,10 +417,17 @@ public class LabelMultipleOptionAppService : ApplicationService, ILabelMultipleO
384 417 input.LocationIds,
385 418 hasScopeArrays);
386 419  
387   - locScope = await AllScopeBindingHelper.ExpandScopedRegionLocationAllForLegacyEntitySaveAsync(
388   - _dbContext.SqlSugarClient,
389   - locScope,
390   - partnerContext);
  420 + // 「所选 Region 内全部门店」:有 fl_label_multiple_option_region 时只落 Region 绑定,
  421 + // 未迁移时回退为展开区内门店快照。
  422 + if (!locScope.IsScopedRegionLocationAll
  423 + || !await LabelEntityRegionScopeStore.HasTableAsync(
  424 + _dbContext.SqlSugarClient, LabelEntityRegionScopeStore.Kind.MultipleOption))
  425 + {
  426 + locScope = await AllScopeBindingHelper.ExpandScopedRegionLocationAllForLegacyEntitySaveAsync(
  427 + _dbContext.SqlSugarClient,
  428 + locScope,
  429 + partnerContext);
  430 + }
391 431  
392 432 // 多选项:显式 SPECIFIED + 具体 Region/门店时强制 AppliedRegionType=SPECIFIED,禁止误存 ALL
393 433 // 有 Region/Location ALL 哨兵时不做该强制(上面已归档或 helper 已处理)
... ... @@ -405,7 +445,7 @@ public class LabelMultipleOptionAppService : ApplicationService, ILabelMultipleO
405 445 appliedRegionType = AllScopeBindingHelper.ScopeSpecified;
406 446 }
407 447  
408   - return (partnerScope, locScope.AvailabilityType, appliedRegionType, locScope.LocationIds);
  448 + return (partnerScope, locScope.AvailabilityType, appliedRegionType, locScope.LocationIds, locScope.RegionIds);
409 449 }
410 450  
411 451 private async Task SaveMultipleOptionPartnerScopeAsync(
... ... @@ -587,6 +627,31 @@ public class LabelMultipleOptionAppService : ApplicationService, ILabelMultipleO
587 627 .Where(x => specifiedIds.Contains(x.MultipleOptionId))
588 628 .ToListAsync();
589 629  
  630 + // Region 范围 ALL:多选项可能只落 fl_label_multiple_option_region、没有门店快照
  631 + var regionIdsByOption = await LabelEntityRegionScopeStore.LoadRegionIdsMapAsync(
  632 + _dbContext.SqlSugarClient, LabelEntityRegionScopeStore.Kind.MultipleOption, specifiedIds);
  633 + var persistedGroupIds = regionIdsByOption.Values
  634 + .SelectMany(x => x)
  635 + .Distinct(StringComparer.Ordinal)
  636 + .ToList();
  637 + var groupNameById = new Dictionary<string, string>(StringComparer.Ordinal);
  638 + var groupPartnerById = new Dictionary<string, string>(StringComparer.Ordinal);
  639 + if (persistedGroupIds.Count > 0)
  640 + {
  641 + var groups = await _dbContext.SqlSugarClient.Queryable<FlGroupDbEntity>()
  642 + .Where(g => !g.IsDeleted && persistedGroupIds.Contains(g.Id))
  643 + .Select(g => new { g.Id, g.GroupName, g.PartnerId })
  644 + .ToListAsync();
  645 + foreach (var g in groups)
  646 + {
  647 + groupNameById[g.Id] = g.GroupName?.Trim() ?? string.Empty;
  648 + if (!string.IsNullOrWhiteSpace(g.PartnerId))
  649 + {
  650 + groupPartnerById[g.Id] = g.PartnerId.Trim();
  651 + }
  652 + }
  653 + }
  654 +
590 655 var locIdSet = links
591 656 .Select(x => x.LocationId)
592 657 .Where(x => !string.IsNullOrWhiteSpace(x))
... ... @@ -615,8 +680,10 @@ public class LabelMultipleOptionAppService : ApplicationService, ILabelMultipleO
615 680 var optionLinks = links.Where(x => x.MultipleOptionId == optionId).ToList();
616 681 var locationIds = LocationScopeBindingHelper.NormalizeIds(
617 682 optionLinks.Select(x => x.LocationId).ToList());
  683 + regionIdsByOption.TryGetValue(optionId, out var persistedRegionIds);
  684 + persistedRegionIds ??= new List<string>();
618 685  
619   - if (optionLinks.Count == 0)
  686 + if (optionLinks.Count == 0 && persistedRegionIds.Count == 0)
620 687 {
621 688 result[optionId] = new MultipleOptionScopeData
622 689 {
... ... @@ -655,10 +722,26 @@ public class LabelMultipleOptionAppService : ApplicationService, ILabelMultipleO
655 722 }
656 723 }
657 724  
658   - var regionIds = await LocationScopeBindingHelper.ResolveGroupIdsFromLocationIdsAsync(
659   - _dbContext.SqlSugarClient, locationIds);
660   - var partnerIds = await LocationScopeBindingHelper.ResolvePartnerIdsFromLocationIdsAsync(
661   - _dbContext.SqlSugarClient, locationIds);
  725 + var regionIds = persistedRegionIds.Count > 0
  726 + ? persistedRegionIds
  727 + : await LocationScopeBindingHelper.ResolveGroupIdsFromLocationIdsAsync(
  728 + _dbContext.SqlSugarClient, locationIds);
  729 + foreach (var gid in regionIds)
  730 + {
  731 + if (groupNameById.TryGetValue(gid, out var groupName) && !string.IsNullOrWhiteSpace(groupName))
  732 + {
  733 + regions.Add(groupName);
  734 + }
  735 + }
  736 +
  737 + var partnerIds = persistedRegionIds.Count > 0
  738 + ? persistedRegionIds
  739 + .Select(gid => groupPartnerById.GetValueOrDefault(gid, string.Empty))
  740 + .Where(x => !string.IsNullOrWhiteSpace(x))
  741 + .Distinct(StringComparer.Ordinal)
  742 + .ToList()
  743 + : await LocationScopeBindingHelper.ResolvePartnerIdsFromLocationIdsAsync(
  744 + _dbContext.SqlSugarClient, locationIds);
662 745 var entity = entities.FirstOrDefault(x => x.Id == optionId);
663 746 var collapsed = await ScopeAllEchoHelper.CollapseScopeIdsToAllSentinelAsync(
664 747 _dbContext.SqlSugarClient,
... ... @@ -672,14 +755,22 @@ public class LabelMultipleOptionAppService : ApplicationService, ILabelMultipleO
672 755 regionIds,
673 756 locationIds));
674 757  
  758 + var isScopedLocationAll = collapsed.LocationIds.Count == 1
  759 + && string.Equals(
  760 + collapsed.LocationIds[0],
  761 + AllScopeBindingHelper.ScopeAll,
  762 + StringComparison.OrdinalIgnoreCase);
  763 +
675 764 result[optionId] = new MultipleOptionScopeData
676 765 {
677 766 Region = regions.Count > 0
678 767 ? string.Join(", ", regions.OrderBy(x => x, StringComparer.OrdinalIgnoreCase))
679 768 : EmptyDisplay,
680   - Location = locationNames.Count > 0
681   - ? string.Join(", ", locationNames.OrderBy(x => x, StringComparer.OrdinalIgnoreCase))
682   - : EmptyDisplay,
  769 + Location = isScopedLocationAll
  770 + ? AllLocationsDisplay
  771 + : locationNames.Count > 0
  772 + ? string.Join(", ", locationNames.OrderBy(x => x, StringComparer.OrdinalIgnoreCase))
  773 + : EmptyDisplay,
683 774 RegionIds = collapsed.RegionIds,
684 775 LocationIds = collapsed.LocationIds
685 776 };
... ...
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/LabelTypeAppService.cs
... ... @@ -47,7 +47,14 @@ public class LabelTypeAppService : ApplicationService, ILabelTypeAppService
47 47 if (LabelEntityListScopeHelper.ShouldApplyLocationAvailabilityFilterForList(
48 48 input.PartnerId, input.GroupId, input.LocationId, !partnerScope.IsUnrestricted))
49 49 {
50   - query = LabelEntityListScopeHelper.ApplyTypeLocationAvailabilityFilter(query, scopedLocationIds);
  50 + var hasTypeRegionTable = await LabelEntityRegionScopeStore.HasTableAsync(
  51 + _dbContext.SqlSugarClient, LabelEntityRegionScopeStore.Kind.Type);
  52 + var scopedGroupIds = scopedLocationIds is { Count: > 0 }
  53 + ? await LocationScopeBindingHelper.ResolveGroupIdsFromLocationIdsAsync(
  54 + _dbContext.SqlSugarClient, scopedLocationIds)
  55 + : new List<string>();
  56 + query = LabelEntityListScopeHelper.ApplyTypeLocationAvailabilityFilter(
  57 + query, scopedLocationIds, hasTypeRegionTable, scopedGroupIds);
51 58 }
52 59  
53 60 if (!string.IsNullOrWhiteSpace(input.Sorting))
... ... @@ -85,23 +92,14 @@ public class LabelTypeAppService : ApplicationService, ILabelTypeAppService
85 92 countMap.TryGetValue(x.Id, out var stats);
86 93 var locationDisplay = scope?.Location ?? EmptyDisplay;
87 94 var partnerIds = partnerScope?.PartnerIds ?? new List<string>();
88   - var partnerIdsForManage = PartnerScopedManagePermissionHelper.ResolvePartnerScopedEntityPartnerIdsForManageFromEcho(
89   - x.AvailabilityType,
90   - x.AppliedRegionType,
91   - partnerScope?.AppliedPartnerType ?? x.AppliedPartnerType,
92   - scope?.RegionIds,
93   - scope?.LocationIds,
94   - partnerIds);
95 95 var createdBySystemAdmin =
96 96 Guid.TryParse(x.CreatorId?.Trim(), out var creatorGuid) &&
97 97 manageCtx.SystemAdminCreatorIds.Contains(creatorGuid);
98   - var canManage = PartnerScopedManagePermissionHelper.EvaluateCanManage(
  98 + var canManage = LabelTypeManagePermissionHelper.EvaluateRow(
99 99 CurrentUser,
100 100 manageCtx,
101   - x.CreatorId,
102   - partnerIdsForManage,
103   - x.Id,
104   - x.LastModifierId);
  101 + x,
  102 + partnerIds);
105 103 return new LabelTypeGetListOutputDto
106 104 {
107 105 Id = x.Id,
... ... @@ -157,8 +155,14 @@ public class LabelTypeAppService : ApplicationService, ILabelTypeAppService
157 155 .Select(x => x.LocationId)
158 156 .ToListAsync();
159 157 dto.LocationIds = LocationScopeBindingHelper.NormalizeIds(locationIds);
160   - var regionIds = await LocationScopeBindingHelper.ResolveGroupIdsFromLocationIdsAsync(
161   - _dbContext.SqlSugarClient, locationIds);
  158 + // Region 范围 ALL:只落了 Region 绑定、无门店快照时,用持久化 Region 回显;后续由
  159 + // ScopeAllEchoHelper 折叠为 locationIds=["ALL"](区内 ALL)。
  160 + var persistedRegionIds = await LabelEntityRegionScopeStore.LoadRegionIdsAsync(
  161 + _dbContext.SqlSugarClient, LabelEntityRegionScopeStore.Kind.Type, entity.Id);
  162 + var regionIds = persistedRegionIds.Count > 0
  163 + ? persistedRegionIds
  164 + : await LocationScopeBindingHelper.ResolveGroupIdsFromLocationIdsAsync(
  165 + _dbContext.SqlSugarClient, locationIds);
162 166 dto.RegionIds = regionIds;
163 167 dto.GroupIds = regionIds;
164 168 if (dto.LocationIds.Count > 0 || dto.RegionIds.Count > 0)
... ... @@ -196,7 +200,7 @@ public class LabelTypeAppService : ApplicationService, ILabelTypeAppService
196 200 throw new UserFriendlyException("Type code and name are required.");
197 201 }
198 202  
199   - var (partnerScope, availabilityType, appliedRegionType, mergedLocationIds) = await ResolveTypeScopeForSaveAsync(input);
  203 + var (partnerScope, availabilityType, appliedRegionType, mergedLocationIds, mergedRegionIds) = await ResolveTypeScopeForSaveAsync(input);
200 204  
201 205 await EnsureLabelTypeNotDuplicatedAsync(code, name, partnerScope);
202 206  
... ... @@ -226,6 +230,14 @@ public class LabelTypeAppService : ApplicationService, ILabelTypeAppService
226 230 await _dbContext.SqlSugarClient.Insertable(entity).ExecuteCommandAsync();
227 231 await SaveTypePartnerScopeAsync(entity.Id, partnerScope, currentUserId, now);
228 232 await SaveTypeLocationsAsync(entity.Id, availabilityType, mergedLocationIds, currentUserId, now);
  233 + await LabelEntityRegionScopeStore.ReplaceAsync(
  234 + _dbContext.SqlSugarClient,
  235 + LabelEntityRegionScopeStore.Kind.Type,
  236 + entity.Id,
  237 + mergedRegionIds,
  238 + _guidGenerator,
  239 + currentUserId,
  240 + now);
229 241 return await GetAsync(entity.Id);
230 242 }
231 243  
... ... @@ -238,12 +250,10 @@ public class LabelTypeAppService : ApplicationService, ILabelTypeAppService
238 250 throw new UserFriendlyException("Label type not found.");
239 251 }
240 252  
241   - await PartnerScopedManagePermissionHelper.EnsureCanManagePartnerEntityAsync(
  253 + await LabelTypeManagePermissionHelper.EnsureCanManageAsync(
242 254 CurrentUser,
243 255 _dbContext,
244   - LabelEntityPartnerScopeHelper.LabelEntityPartnerKind.Type,
245   - entity.Id,
246   - entity.CreatorId,
  256 + entity,
247 257 "You are not authorized to edit or delete this Label Type.");
248 258  
249 259 var code = input.TypeCode?.Trim();
... ... @@ -253,7 +263,7 @@ public class LabelTypeAppService : ApplicationService, ILabelTypeAppService
253 263 throw new UserFriendlyException("Type code and name are required.");
254 264 }
255 265  
256   - var (partnerScope, availabilityType, appliedRegionType, mergedLocationIds) = await ResolveTypeScopeForSaveAsync(input);
  266 + var (partnerScope, availabilityType, appliedRegionType, mergedLocationIds, mergedRegionIds) = await ResolveTypeScopeForSaveAsync(input);
257 267  
258 268 await EnsureLabelTypeNotDuplicatedAsync(code, name, partnerScope, id);
259 269  
... ... @@ -285,6 +295,14 @@ public class LabelTypeAppService : ApplicationService, ILabelTypeAppService
285 295 entity.LastModificationTime ?? DateTime.Now);
286 296 await SaveTypeLocationsAsync(entity.Id, availabilityType, mergedLocationIds, entity.LastModifierId,
287 297 entity.LastModificationTime ?? DateTime.Now);
  298 + await LabelEntityRegionScopeStore.ReplaceAsync(
  299 + _dbContext.SqlSugarClient,
  300 + LabelEntityRegionScopeStore.Kind.Type,
  301 + entity.Id,
  302 + mergedRegionIds,
  303 + _guidGenerator,
  304 + entity.LastModifierId,
  305 + entity.LastModificationTime ?? DateTime.Now);
288 306 return await GetAsync(id);
289 307 }
290 308  
... ... @@ -297,12 +315,10 @@ public class LabelTypeAppService : ApplicationService, ILabelTypeAppService
297 315 return;
298 316 }
299 317  
300   - await PartnerScopedManagePermissionHelper.EnsureCanManagePartnerEntityAsync(
  318 + await LabelTypeManagePermissionHelper.EnsureCanManageAsync(
301 319 CurrentUser,
302 320 _dbContext,
303   - LabelEntityPartnerScopeHelper.LabelEntityPartnerKind.Type,
304   - entity.Id,
305   - entity.CreatorId,
  321 + entity,
306 322 "You are not authorized to edit or delete this Label Type.");
307 323  
308 324 var used = await _dbContext.SqlSugarClient.Queryable<FlLabelDbEntity>()
... ... @@ -319,6 +335,8 @@ public class LabelTypeAppService : ApplicationService, ILabelTypeAppService
319 335 await _dbContext.SqlSugarClient.Deleteable<FlLabelTypeLocationDbEntity>()
320 336 .Where(x => x.LabelTypeId == id)
321 337 .ExecuteCommandAsync();
  338 + await LabelEntityRegionScopeStore.DeleteByEntityAsync(
  339 + _dbContext.SqlSugarClient, LabelEntityRegionScopeStore.Kind.Type, id);
322 340  
323 341 entity.IsDeleted = true;
324 342 entity.LastModificationTime = DateTime.Now;
... ... @@ -377,13 +395,15 @@ public class LabelTypeAppService : ApplicationService, ILabelTypeAppService
377 395 await _dbContext.SqlSugarClient.Deleteable<FlLabelTypeLocationDbEntity>()
378 396 .Where(x => x.LabelTypeId == row.Id)
379 397 .ExecuteCommandAsync();
  398 + await LabelEntityRegionScopeStore.DeleteByEntityAsync(
  399 + _dbContext.SqlSugarClient, LabelEntityRegionScopeStore.Kind.Type, row.Id);
380 400 await _dbContext.SqlSugarClient.Deleteable<FlLabelTypeDbEntity>()
381 401 .Where(x => x.Id == row.Id)
382 402 .ExecuteCommandAsync();
383 403 }
384 404 }
385 405  
386   - private async Task<(LabelEntityPartnerScopeHelper.LabelEntityPartnerScopeSaveResult PartnerScope, string AvailabilityType, string AppliedRegionType, List<string> LocationIds)> ResolveTypeScopeForSaveAsync(
  406 + private async Task<(LabelEntityPartnerScopeHelper.LabelEntityPartnerScopeSaveResult PartnerScope, string AvailabilityType, string AppliedRegionType, List<string> LocationIds, List<string> RegionIds)> ResolveTypeScopeForSaveAsync(
387 407 LabelTypeCreateInputVo input)
388 408 {
389 409 var partnerScope = await LabelEntityPartnerScopeHelper.ResolvePartnerScopeForSaveAsync(
... ... @@ -410,6 +430,7 @@ public class LabelTypeAppService : ApplicationService, ILabelTypeAppService
410 430 partnerScope,
411 431 AllScopeBindingHelper.ScopeAll,
412 432 AllScopeBindingHelper.ScopeAll,
  433 + new List<string>(),
413 434 new List<string>());
414 435 }
415 436  
... ... @@ -421,12 +442,19 @@ public class LabelTypeAppService : ApplicationService, ILabelTypeAppService
421 442 input.LocationIds,
422 443 hasScopeArrays);
423 444  
424   - locScope = await AllScopeBindingHelper.ExpandScopedRegionLocationAllForLegacyEntitySaveAsync(
425   - _dbContext.SqlSugarClient,
426   - locScope,
427   - partnerContext);
  445 + // 「所选 Region 内全部门店」:有 fl_label_type_region 时只落 Region 绑定(区内新店自动适用),
  446 + // 未迁移时回退为展开区内门店快照。
  447 + if (!locScope.IsScopedRegionLocationAll
  448 + || !await LabelEntityRegionScopeStore.HasTableAsync(
  449 + _dbContext.SqlSugarClient, LabelEntityRegionScopeStore.Kind.Type))
  450 + {
  451 + locScope = await AllScopeBindingHelper.ExpandScopedRegionLocationAllForLegacyEntitySaveAsync(
  452 + _dbContext.SqlSugarClient,
  453 + locScope,
  454 + partnerContext);
  455 + }
428 456  
429   - return (partnerScope, locScope.AvailabilityType, locScope.AppliedRegionType, locScope.LocationIds);
  457 + return (partnerScope, locScope.AvailabilityType, locScope.AppliedRegionType, locScope.LocationIds, locScope.RegionIds);
430 458 }
431 459  
432 460 private async Task SaveTypePartnerScopeAsync(
... ... @@ -645,13 +673,40 @@ public class LabelTypeAppService : ApplicationService, ILabelTypeAppService
645 673 }
646 674 }
647 675  
  676 + // Region 范围 ALL:类型可能只落 fl_label_type_region、没有门店快照
  677 + var regionIdsByType = await LabelEntityRegionScopeStore.LoadRegionIdsMapAsync(
  678 + _dbContext.SqlSugarClient, LabelEntityRegionScopeStore.Kind.Type, specifiedIds);
  679 + var persistedGroupIds = regionIdsByType.Values
  680 + .SelectMany(x => x)
  681 + .Distinct(StringComparer.Ordinal)
  682 + .ToList();
  683 + var groupNameById = new Dictionary<string, string>(StringComparer.Ordinal);
  684 + var groupPartnerById = new Dictionary<string, string>(StringComparer.Ordinal);
  685 + if (persistedGroupIds.Count > 0)
  686 + {
  687 + var groups = await _dbContext.SqlSugarClient.Queryable<FlGroupDbEntity>()
  688 + .Where(g => !g.IsDeleted && persistedGroupIds.Contains(g.Id))
  689 + .Select(g => new { g.Id, g.GroupName, g.PartnerId })
  690 + .ToListAsync();
  691 + foreach (var g in groups)
  692 + {
  693 + groupNameById[g.Id] = g.GroupName?.Trim() ?? string.Empty;
  694 + if (!string.IsNullOrWhiteSpace(g.PartnerId))
  695 + {
  696 + groupPartnerById[g.Id] = g.PartnerId.Trim();
  697 + }
  698 + }
  699 + }
  700 +
648 701 foreach (var typeId in specifiedIds)
649 702 {
650 703 var typeLinks = links.Where(x => x.LabelTypeId == typeId).ToList();
651 704 var locationIds = LocationScopeBindingHelper.NormalizeIds(
652 705 typeLinks.Select(x => x.LocationId).ToList());
  706 + regionIdsByType.TryGetValue(typeId, out var persistedRegionIds);
  707 + persistedRegionIds ??= new List<string>();
653 708  
654   - if (typeLinks.Count == 0)
  709 + if (typeLinks.Count == 0 && persistedRegionIds.Count == 0)
655 710 {
656 711 result[typeId] = new TypeScopeData
657 712 {
... ... @@ -690,21 +745,53 @@ public class LabelTypeAppService : ApplicationService, ILabelTypeAppService
690 745 }
691 746 }
692 747  
693   - var regionIds = await LocationScopeBindingHelper.ResolveGroupIdsFromLocationIdsAsync(
694   - _dbContext.SqlSugarClient, locationIds);
695   - var partnerIds = await LocationScopeBindingHelper.ResolvePartnerIdsFromLocationIdsAsync(
696   - _dbContext.SqlSugarClient, locationIds);
  748 + var regionIds = persistedRegionIds.Count > 0
  749 + ? persistedRegionIds
  750 + : await LocationScopeBindingHelper.ResolveGroupIdsFromLocationIdsAsync(
  751 + _dbContext.SqlSugarClient, locationIds);
  752 + foreach (var gid in regionIds)
  753 + {
  754 + if (groupNameById.TryGetValue(gid, out var groupName) && !string.IsNullOrWhiteSpace(groupName))
  755 + {
  756 + regions.Add(groupName);
  757 + }
  758 + }
  759 +
  760 + var partnerIds = persistedRegionIds.Count > 0
  761 + ? persistedRegionIds
  762 + .Select(gid => groupPartnerById.GetValueOrDefault(gid, string.Empty))
  763 + .Where(x => !string.IsNullOrWhiteSpace(x))
  764 + .Distinct(StringComparer.Ordinal)
  765 + .ToList()
  766 + : await LocationScopeBindingHelper.ResolvePartnerIdsFromLocationIdsAsync(
  767 + _dbContext.SqlSugarClient, locationIds);
697 768 var collapsed = await ScopeAllEchoHelper.CollapseScopeIdsToAllSentinelAsync(
698   - _dbContext.SqlSugarClient, partnerIds, regionIds, locationIds);
  769 + _dbContext.SqlSugarClient,
  770 + partnerIds,
  771 + regionIds,
  772 + locationIds,
  773 + ScopeAllEchoHelper.ForLabelEntityScope(
  774 + null,
  775 + AllScopeBindingHelper.ScopeSpecified,
  776 + AllScopeBindingHelper.ScopeSpecified,
  777 + regionIds,
  778 + locationIds));
  779 + var isScopedLocationAll = collapsed.LocationIds.Count == 1
  780 + && string.Equals(
  781 + collapsed.LocationIds[0],
  782 + AllScopeBindingHelper.ScopeAll,
  783 + StringComparison.OrdinalIgnoreCase);
699 784  
700 785 result[typeId] = new TypeScopeData
701 786 {
702 787 Region = regions.Count > 0
703 788 ? string.Join(", ", regions.OrderBy(x => x, StringComparer.OrdinalIgnoreCase))
704 789 : EmptyDisplay,
705   - Location = locationNames.Count > 0
706   - ? string.Join(", ", locationNames.OrderBy(x => x, StringComparer.OrdinalIgnoreCase))
707   - : EmptyDisplay,
  790 + Location = isScopedLocationAll
  791 + ? AllLocationsDisplay
  792 + : locationNames.Count > 0
  793 + ? string.Join(", ", locationNames.OrderBy(x => x, StringComparer.OrdinalIgnoreCase))
  794 + : EmptyDisplay,
708 795 RegionIds = collapsed.RegionIds,
709 796 LocationIds = collapsed.LocationIds
710 797 };
... ...
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/ProductAppService.cs
... ... @@ -141,6 +141,7 @@ public class ProductAppService : ApplicationService, IProductAppService
141 141 entity.AvailabilityType,
142 142 AllScopeBindingHelper.ScopeAll,
143 143 StringComparison.OrdinalIgnoreCase);
  144 + var persistedRegionIds = await GetProductRegionIdsAsync(productId);
144 145  
145 146 List<string> partnerIds;
146 147 List<string> groupIds;
... ... @@ -161,34 +162,54 @@ public class ProductAppService : ApplicationService, IProductAppService
161 162 {
162 163 partnerIds = new List<string> { entity.PartnerId.Trim() };
163 164 }
164   - else
  165 + else if (locationIds.Count > 0)
165 166 {
166 167 partnerIds = await LocationScopeBindingHelper.ResolvePartnerIdsFromLocationIdsAsync(
167 168 _dbContext.SqlSugarClient, locationIds);
168 169 }
  170 + else
  171 + {
  172 + var partnerFromRegions = await ResolvePartnerIdFromRegionIdsAsync(persistedRegionIds);
  173 + partnerIds = string.IsNullOrWhiteSpace(partnerFromRegions)
  174 + ? new List<string>()
  175 + : new List<string> { partnerFromRegions! };
  176 + }
169 177  
170   - groupIds = await LocationScopeBindingHelper.ResolveGroupIdsFromLocationIdsAsync(
171   - _dbContext.SqlSugarClient, locationIds);
172   - var isLocationAll = await ScopeAllEchoHelper.ShouldEchoProductLocationAsAllAsync(
173   - _dbContext.SqlSugarClient,
174   - entity.AvailabilityType,
175   - entity.AppliedRegionType,
176   - partnerIds,
177   - groupIds,
178   - locationIds,
179   - entity.PartnerId);
180   - var concreteEchoLocations = LocationScopeBindingHelper.FilterConcreteScopeIds(locationIds);
181   - (_, groupIds, locationIds) = await ScopeAllEchoHelper.CollapseScopeIdsToAllSentinelAsync(
182   - _dbContext.SqlSugarClient,
183   - partnerIds,
184   - groupIds,
185   - locationIds,
186   - new ScopeAllEchoHelper.ScopeAllEchoOptions
187   - {
188   - IsRegionAll = AllScopeBindingHelper.IsDeclaredAll(entity.AppliedRegionType)
189   - && concreteEchoLocations.Count == 0,
190   - IsLocationAll = isLocationAll
191   - });
  178 + groupIds = persistedRegionIds.Count > 0
  179 + ? new List<string>(persistedRegionIds)
  180 + : await LocationScopeBindingHelper.ResolveGroupIdsFromLocationIdsAsync(
  181 + _dbContext.SqlSugarClient, locationIds);
  182 +
  183 + // Region 范围 ALL:只落了 Region 绑定、无门店快照 → 回显 ["ALL"]
  184 + var isRegionScopedAll = persistedRegionIds.Count > 0
  185 + && LocationScopeBindingHelper.FilterConcreteScopeIds(locationIds).Count == 0;
  186 + if (isRegionScopedAll)
  187 + {
  188 + locationIds = new List<string> { AllScopeBindingHelper.ScopeAll };
  189 + }
  190 + else
  191 + {
  192 + var isLocationAll = await ScopeAllEchoHelper.ShouldEchoProductLocationAsAllAsync(
  193 + _dbContext.SqlSugarClient,
  194 + entity.AvailabilityType,
  195 + entity.AppliedRegionType,
  196 + partnerIds,
  197 + groupIds,
  198 + locationIds,
  199 + entity.PartnerId);
  200 + var concreteEchoLocations = LocationScopeBindingHelper.FilterConcreteScopeIds(locationIds);
  201 + (_, groupIds, locationIds) = await ScopeAllEchoHelper.CollapseScopeIdsToAllSentinelAsync(
  202 + _dbContext.SqlSugarClient,
  203 + partnerIds,
  204 + groupIds,
  205 + locationIds,
  206 + new ScopeAllEchoHelper.ScopeAllEchoOptions
  207 + {
  208 + IsRegionAll = AllScopeBindingHelper.IsDeclaredAll(entity.AppliedRegionType)
  209 + && concreteEchoLocations.Count == 0,
  210 + IsLocationAll = isLocationAll
  211 + });
  212 + }
192 213 }
193 214  
194 215 List<string> companyIdsForEcho;
... ... @@ -281,6 +302,7 @@ public class ProductAppService : ApplicationService, IProductAppService
281 302 if (ShouldPersistProductScope(input))
282 303 {
283 304 await ReplaceProductLocationLinksAsync(entity.Id, scope.LocationIds);
  305 + await ReplaceProductRegionLinksAsync(entity.Id, scope.RegionIds);
284 306 }
285 307  
286 308 return await GetAsync(Guid.Parse(entity.Id));
... ... @@ -365,6 +387,7 @@ public class ProductAppService : ApplicationService, IProductAppService
365 387 if (ShouldPersistProductScope(input))
366 388 {
367 389 await ReplaceProductLocationLinksAsync(productId, scope.LocationIds);
  390 + await ReplaceProductRegionLinksAsync(productId, scope.RegionIds);
368 391 }
369 392  
370 393 return await GetAsync(id);
... ... @@ -730,7 +753,7 @@ public class ProductAppService : ApplicationService, IProductAppService
730 753 categoryMap = categories.ToDictionary(x => x.Id, x => x);
731 754 }
732 755  
733   - var (locationIdsByProduct, locationNameByProduct) =
  756 + var (locationIdsByProduct, locationNameByProduct, regionIdsByProduct) =
734 757 await BuildProductLocationDisplayMapsAsync(ids);
735 758 var manageCtx = await PartnerScopedManagePermissionHelper.BuildListContextAsync(
736 759 CurrentUser, _dbContext, entities.Select(x => x.CreatorId));
... ... @@ -745,7 +768,9 @@ public class ProductAppService : ApplicationService, IProductAppService
745 768 }
746 769  
747 770 locationIdsByProduct.TryGetValue(x.Id, out var rawLocationIds);
748   - var locationIds = await EchoProductLocationIdsAsync(x, rawLocationIds ?? new List<string>());
  771 + regionIdsByProduct.TryGetValue(x.Id, out var rawRegionIds);
  772 + var locationIds = await EchoProductLocationIdsAsync(
  773 + x, rawLocationIds ?? new List<string>(), rawRegionIds ?? new List<string>());
749 774 locationNameByProduct.TryGetValue(x.Id, out var locationName);
750 775 var isAllLocations = AllScopeBindingHelper.IsDeclaredAll(x.AvailabilityType)
751 776 || AllScopeBindingHelper.HasAllScopeSentinelSelection(locationIds)
... ... @@ -833,6 +858,12 @@ public class ProductAppService : ApplicationService, IProductAppService
833 858 input.PartnerId,
834 859 input.GroupId,
835 860 locationIds);
  861 + var hasProductRegionTable = await ProductScopeSchemaHelper.HasRegionTableAsync(
  862 + _dbContext.SqlSugarClient);
  863 + var scopedGroupIds = locationIds.Count > 0
  864 + ? await LocationScopeBindingHelper.ResolveGroupIdsFromLocationIdsAsync(
  865 + _dbContext.SqlSugarClient, locationIds)
  866 + : new List<string>();
836 867  
837 868 query = ProductListScopeHelper.ApplyProductLocationListFilter(
838 869 query,
... ... @@ -841,7 +872,9 @@ public class ProductAppService : ApplicationService, IProductAppService
841 872 hasAvailabilityColumn,
842 873 hasAppliedRegionColumn,
843 874 hasPartnerIdColumn,
844   - partnerOnly);
  875 + partnerOnly,
  876 + hasProductRegionTable,
  877 + scopedGroupIds);
845 878 scopeFilterApplied = true;
846 879 }
847 880  
... ... @@ -926,20 +959,50 @@ public class ProductAppService : ApplicationService, IProductAppService
926 959 .Where(x => x.ProductId == entity.Id)
927 960 .Select(x => x.LocationId)
928 961 .ToListAsync();
929   - if (!productLocationIds.Any(id => scopedLocationIds.Contains(id)))
  962 + if (productLocationIds.Any(id => scopedLocationIds.Contains(id)))
930 963 {
931   - throw new UserFriendlyException("You do not have permission to access this product.");
  964 + return;
  965 + }
  966 +
  967 + // Region 范围 ALL:产品只落 Region 绑定,命中用户可见门店所属 Region 即可访问
  968 + var productRegionIds = await GetProductRegionIdsAsync(entity.Id);
  969 + if (productRegionIds.Count > 0)
  970 + {
  971 + var scopedGroupIds = await LocationScopeBindingHelper.ResolveGroupIdsFromLocationIdsAsync(
  972 + _dbContext.SqlSugarClient, scopedLocationIds);
  973 + if (productRegionIds.Any(id => scopedGroupIds.Contains(id, StringComparer.OrdinalIgnoreCase)))
  974 + {
  975 + return;
  976 + }
932 977 }
  978 +
  979 + throw new UserFriendlyException("You do not have permission to access this product.");
933 980 }
934 981  
935   - private async Task<(Dictionary<string, List<string>> LocationIdsByProduct, Dictionary<string, string> LocationNameByProduct)>
  982 + private async Task<(
  983 + Dictionary<string, List<string>> LocationIdsByProduct,
  984 + Dictionary<string, string> LocationNameByProduct,
  985 + Dictionary<string, List<string>> RegionIdsByProduct)>
936 986 BuildProductLocationDisplayMapsAsync(IReadOnlyList<string> productIds)
937 987 {
938 988 var locationIdsByProduct = new Dictionary<string, List<string>>(StringComparer.Ordinal);
939 989 var locationNameByProduct = new Dictionary<string, string>(StringComparer.Ordinal);
  990 + var regionIdsByProduct = new Dictionary<string, List<string>>(StringComparer.Ordinal);
940 991 if (productIds.Count == 0)
941 992 {
942   - return (locationIdsByProduct, locationNameByProduct);
  993 + return (locationIdsByProduct, locationNameByProduct, regionIdsByProduct);
  994 + }
  995 +
  996 + if (await ProductScopeSchemaHelper.HasRegionTableAsync(_dbContext.SqlSugarClient))
  997 + {
  998 + var regionLinks = await _dbContext.SqlSugarClient.Queryable<FlProductRegionDbEntity>()
  999 + .Where(x => productIds.Contains(x.ProductId))
  1000 + .ToListAsync();
  1001 + foreach (var g in regionLinks.GroupBy(x => x.ProductId, StringComparer.Ordinal))
  1002 + {
  1003 + regionIdsByProduct[g.Key] = LocationScopeBindingHelper.NormalizeIds(
  1004 + g.Select(x => x.GroupId).ToList());
  1005 + }
943 1006 }
944 1007  
945 1008 var links = await _dbContext.SqlSugarClient.Queryable<FlLocationProductDbEntity>()
... ... @@ -988,21 +1051,28 @@ public class ProductAppService : ApplicationService, IProductAppService
988 1051 : string.Empty;
989 1052 }
990 1053  
991   - return (locationIdsByProduct, locationNameByProduct);
  1054 + return (locationIdsByProduct, locationNameByProduct, regionIdsByProduct);
992 1055 }
993 1056  
994 1057 /// <summary>
995   - /// 产品门店范围回显:范围内 ALL 快照折叠为 <c>["ALL"]</c>。
  1058 + /// 产品门店范围回显:范围内 ALL 快照折叠为 <c>["ALL"]</c>;Region 范围 ALL(只落 Region 绑定)直接回显 ALL。
996 1059 /// </summary>
997 1060 private async Task<List<string>> EchoProductLocationIdsAsync(
998 1061 FlProductDbEntity entity,
999   - IReadOnlyList<string> persistedLocationIds)
  1062 + IReadOnlyList<string> persistedLocationIds,
  1063 + IReadOnlyList<string> persistedRegionIds)
1000 1064 {
1001 1065 if (AllScopeBindingHelper.IsDeclaredAll(entity.AvailabilityType))
1002 1066 {
1003 1067 return new List<string> { AllScopeBindingHelper.ScopeAll };
1004 1068 }
1005 1069  
  1070 + if (persistedRegionIds.Count > 0
  1071 + && LocationScopeBindingHelper.FilterConcreteScopeIds(persistedLocationIds).Count == 0)
  1072 + {
  1073 + return new List<string> { AllScopeBindingHelper.ScopeAll };
  1074 + }
  1075 +
1006 1076 var locationIds = LocationScopeBindingHelper.NormalizeIds(persistedLocationIds);
1007 1077 if (locationIds.Count == 0)
1008 1078 {
... ... @@ -1069,7 +1139,7 @@ public class ProductAppService : ApplicationService, IProductAppService
1069 1139 }
1070 1140  
1071 1141 var productIds = entities.Select(x => x.Id).ToList();
1072   - var (_, locationNameByProduct) = await BuildProductLocationDisplayMapsAsync(productIds);
  1142 + var (_, locationNameByProduct, _) = await BuildProductLocationDisplayMapsAsync(productIds);
1073 1143  
1074 1144 var rows = new List<ProductBatchExcelHelper.ExportRow>();
1075 1145 foreach (var e in entities)
... ... @@ -1345,6 +1415,13 @@ public class ProductAppService : ApplicationService, IProductAppService
1345 1415 await _dbContext.SqlSugarClient.Deleteable<FlLocationProductDbEntity>()
1346 1416 .Where(x => x.ProductId == row.Id)
1347 1417 .ExecuteCommandAsync();
  1418 + if (await ProductScopeSchemaHelper.HasRegionTableAsync(_dbContext.SqlSugarClient))
  1419 + {
  1420 + await _dbContext.SqlSugarClient.Deleteable<FlProductRegionDbEntity>()
  1421 + .Where(x => x.ProductId == row.Id)
  1422 + .ExecuteCommandAsync();
  1423 + }
  1424 +
1348 1425 await _dbContext.SqlSugarClient.Deleteable<FlProductDbEntity>()
1349 1426 .Where(x => x.Id == row.Id)
1350 1427 .ExecuteCommandAsync();
... ... @@ -1434,6 +1511,9 @@ public class ProductAppService : ApplicationService, IProductAppService
1434 1511  
1435 1512 public List<string> LocationIds { get; init; } = new();
1436 1513  
  1514 + /// <summary>适用 Region(<c>fl_group.Id</c>),落 <c>fl_product_region</c>;非空表示「所选 Region 内全部门店」动态范围。</summary>
  1515 + public List<string> RegionIds { get; init; } = new();
  1516 +
1437 1517 /// <summary>Company 级 ALL 锚点;全局 ALL 或未指定 Company 时为 null。</summary>
1438 1518 public string? PartnerId { get; init; }
1439 1519 }
... ... @@ -1501,7 +1581,14 @@ public class ProductAppService : ApplicationService, IProductAppService
1501 1581 };
1502 1582 }
1503 1583  
1504   - // Scoped ALL:部分 Region + Location ALL → SPECIFIED,不写门店快照(新区店靠 Region 动态匹配需 fl_product_region;此处展开区内门店快照)
  1584 + // Scoped ALL:部分 Region + Location ALL → SPECIFIED;有 fl_product_region 时只落 Region 绑定
  1585 + // (该 Region 后续新增门店自动适用),未迁移时回退为展开区内门店快照。
  1586 + if (groupIds.Count > 0
  1587 + && await ProductScopeSchemaHelper.HasRegionTableAsync(_dbContext.SqlSugarClient))
  1588 + {
  1589 + return await BuildRegionScopedAllScopeAsync(groupIds, partnerId, hasConcretePartner);
  1590 + }
  1591 +
1505 1592 var expandRegions = groupIds.Count > 0 ? groupIds : null;
1506 1593 var expanded = await LocationScopeBindingHelper.ExpandScopedAllLocationsForSaveAsync(
1507 1594 _dbContext.SqlSugarClient,
... ... @@ -1563,6 +1650,12 @@ public class ProductAppService : ApplicationService, IProductAppService
1563 1650  
1564 1651 if (groupIds.Count > 0)
1565 1652 {
  1653 + // 只选 Region(Location 未选/ALL):有 fl_product_region 时落 Region 绑定,动态覆盖区内门店
  1654 + if (await ProductScopeSchemaHelper.HasRegionTableAsync(_dbContext.SqlSugarClient))
  1655 + {
  1656 + return await BuildRegionScopedAllScopeAsync(groupIds, partnerId, hasConcretePartner);
  1657 + }
  1658 +
1566 1659 var expanded = await LocationScopeBindingHelper.ExpandScopedAllLocationsForSaveAsync(
1567 1660 _dbContext.SqlSugarClient,
1568 1661 partnerContext,
... ... @@ -1620,6 +1713,93 @@ public class ProductAppService : ApplicationService, IProductAppService
1620 1713 PartnerId = partnerId.Trim()
1621 1714 };
1622 1715  
  1716 + /// <summary>
  1717 + /// 「所选 Region 内全部门店」:落 <c>fl_product_region</c>、不落门店快照,回显 <c>locationIds=["ALL"]</c>,
  1718 + /// 区内后续新增门店自动适用。
  1719 + /// </summary>
  1720 + private async Task<ProductScopeSaveResult> BuildRegionScopedAllScopeAsync(
  1721 + IReadOnlyList<string> regionIds,
  1722 + string? partnerId,
  1723 + bool hasConcretePartner)
  1724 + {
  1725 + var regions = LocationScopeBindingHelper.FilterConcreteScopeIds(
  1726 + LocationScopeBindingHelper.NormalizeIds(regionIds));
  1727 + return new ProductScopeSaveResult
  1728 + {
  1729 + AvailabilityType = AllScopeBindingHelper.ScopeSpecified,
  1730 + AppliedRegionType = AllScopeBindingHelper.ScopeSpecified,
  1731 + RegionIds = regions,
  1732 + LocationIds = new List<string>(),
  1733 + PartnerId = hasConcretePartner && !string.IsNullOrWhiteSpace(partnerId)
  1734 + ? partnerId!.Trim()
  1735 + : await ResolvePartnerIdFromRegionIdsAsync(regions)
  1736 + };
  1737 + }
  1738 +
  1739 + /// <summary>由 Region 反推 Company(<c>fl_group.PartnerId</c>)。</summary>
  1740 + private async Task<string?> ResolvePartnerIdFromRegionIdsAsync(IReadOnlyList<string> regionIds)
  1741 + {
  1742 + var ids = LocationScopeBindingHelper.NormalizeIds(regionIds);
  1743 + if (ids.Count == 0)
  1744 + {
  1745 + return null;
  1746 + }
  1747 +
  1748 + var partnerIds = await _dbContext.SqlSugarClient.Queryable<FlGroupDbEntity>()
  1749 + .Where(g => !g.IsDeleted && ids.Contains(g.Id))
  1750 + .Select(g => g.PartnerId)
  1751 + .ToListAsync();
  1752 + var normalized = LocationScopeBindingHelper.NormalizeIds(partnerIds);
  1753 + return normalized.Count > 0 ? normalized[0] : null;
  1754 + }
  1755 +
  1756 + /// <summary>读取产品已落库的 Region 范围(<c>fl_product_region</c>)。</summary>
  1757 + private async Task<List<string>> GetProductRegionIdsAsync(string productId)
  1758 + {
  1759 + if (!await ProductScopeSchemaHelper.HasRegionTableAsync(_dbContext.SqlSugarClient))
  1760 + {
  1761 + return new List<string>();
  1762 + }
  1763 +
  1764 + return LocationScopeBindingHelper.NormalizeIds(
  1765 + await _dbContext.SqlSugarClient.Queryable<FlProductRegionDbEntity>()
  1766 + .Where(x => x.ProductId == productId)
  1767 + .Select(x => x.GroupId)
  1768 + .ToListAsync());
  1769 + }
  1770 +
  1771 + /// <summary>覆盖写入产品 Region 范围(空集合表示清除)。</summary>
  1772 + private async Task ReplaceProductRegionLinksAsync(string productId, IReadOnlyList<string> regionIds)
  1773 + {
  1774 + if (!await ProductScopeSchemaHelper.HasRegionTableAsync(_dbContext.SqlSugarClient))
  1775 + {
  1776 + return;
  1777 + }
  1778 +
  1779 + await _dbContext.SqlSugarClient.Deleteable<FlProductRegionDbEntity>()
  1780 + .Where(x => x.ProductId == productId)
  1781 + .ExecuteCommandAsync();
  1782 +
  1783 + var ids = LocationScopeBindingHelper.FilterConcreteScopeIds(
  1784 + LocationScopeBindingHelper.NormalizeIds(regionIds));
  1785 + if (ids.Count == 0)
  1786 + {
  1787 + return;
  1788 + }
  1789 +
  1790 + var now = Clock.Now;
  1791 + var currentUserId = FoodLabelingStringAuditHelper.ResolveUserIdString(CurrentUser);
  1792 + var rows = ids.Select(gid => new FlProductRegionDbEntity
  1793 + {
  1794 + Id = _guidGenerator.Create().ToString(),
  1795 + ProductId = productId,
  1796 + GroupId = gid,
  1797 + CreationTime = now,
  1798 + CreatorId = currentUserId
  1799 + }).ToList();
  1800 + await _dbContext.SqlSugarClient.Insertable(rows).ExecuteCommandAsync();
  1801 + }
  1802 +
1623 1803 private async Task<string?> ResolvePartnerIdForProductSaveAsync(
1624 1804 string? inputPartnerId,
1625 1805 IReadOnlyList<string> locationIds,
... ...
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/UsAppLabelingAppService.cs
... ... @@ -77,13 +77,16 @@ public class UsAppLabelingAppService : ApplicationService, IUsAppLabelingAppServ
77 77 var (storePartnerId, storePartnerName, storeGroupName) =
78 78 await ProductAppLabelingScopeHelper.ResolveStoreContextAsync(
79 79 _dbContext.SqlSugarClient, locationId);
  80 + var storeGroupIds = await LocationScopeBindingHelper.ResolveGroupIdsFromLocationIdsAsync(
  81 + _dbContext.SqlSugarClient, new List<string> { locationId });
80 82  
81 83 var productIds = await ProductAppLabelingScopeHelper.ResolveProductIdsForAppLabelingTreeAsync(
82 84 _dbContext.SqlSugarClient,
83 85 locationId,
84 86 storePartnerId,
85 87 storePartnerName,
86   - storeGroupName);
  88 + storeGroupName,
  89 + storeGroupIds);
87 90  
88 91 if (productIds.Count == 0)
89 92 {
... ... @@ -1961,15 +1964,69 @@ public class UsAppLabelingAppService : ApplicationService, IUsAppLabelingAppServ
1961 1964 .Where((lp, l, p, c, t, tpl, pc) => productIds.Contains(p.Id))
1962 1965 .Where(storeFilter.Sql, storeFilter.Parameters);
1963 1966  
  1967 + var hasCategoryRegionTable = await LabelEntityRegionScopeStore.HasTableAsync(
  1968 + _dbContext.SqlSugarClient, LabelEntityRegionScopeStore.Kind.Category);
  1969 +
  1970 + // 分类可用门店门禁的四种组合分开写:未建 fl_label_category_region 时不能把该表写进 SQL,
  1971 + // 否则 SqlSugar 仍会渲染子查询导致 "Table ... doesn't exist"。
  1972 + var hasLabelLocationTable = regionSchema.HasLabelLocationTable;
  1973 + var useCategoryRegion = hasCategoryRegionTable && storeGroupIds.Count > 0;
  1974 +
1964 1975 q = q
1965 1976 .Where((lp, l, p, c, t, tpl, pc) => !l.IsDeleted && l.State)
1966 1977 .Where((lp, l, p, c, t, tpl, pc) => !p.IsDeleted && p.State)
1967   - .Where((lp, l, p, c, t, tpl, pc) => !c.IsDeleted && c.State)
1968   - .Where((lp, l, p, c, t, tpl, pc) =>
  1978 + .Where((lp, l, p, c, t, tpl, pc) => !c.IsDeleted && c.State);
  1979 +
  1980 + if (hasLabelLocationTable && useCategoryRegion)
  1981 + {
  1982 + q = q.Where((lp, l, p, c, t, tpl, pc) =>
  1983 + c.AvailabilityType == "ALL" ||
  1984 + SqlFunc.Subqueryable<FlLabelCategoryLocationDbEntity>()
  1985 + .Where(cl => cl.CategoryId == c.Id && cl.LocationId == locationId)
  1986 + .Any() ||
  1987 + SqlFunc.Subqueryable<FlLabelCategoryRegionDbEntity>()
  1988 + .Where(cr => cr.CategoryId == c.Id && storeGroupIds.Contains(cr.GroupId))
  1989 + .Any() ||
  1990 + l.LocationId == locationId ||
  1991 + SqlFunc.Subqueryable<FlLabelLocationDbEntity>()
  1992 + .Where(ll => ll.LabelId == l.Id && ll.LocationId == locationId)
  1993 + .Any());
  1994 + }
  1995 + else if (hasLabelLocationTable)
  1996 + {
  1997 + q = q.Where((lp, l, p, c, t, tpl, pc) =>
  1998 + c.AvailabilityType == "ALL" ||
  1999 + SqlFunc.Subqueryable<FlLabelCategoryLocationDbEntity>()
  2000 + .Where(cl => cl.CategoryId == c.Id && cl.LocationId == locationId)
  2001 + .Any() ||
  2002 + l.LocationId == locationId ||
  2003 + SqlFunc.Subqueryable<FlLabelLocationDbEntity>()
  2004 + .Where(ll => ll.LabelId == l.Id && ll.LocationId == locationId)
  2005 + .Any());
  2006 + }
  2007 + else if (useCategoryRegion)
  2008 + {
  2009 + q = q.Where((lp, l, p, c, t, tpl, pc) =>
  2010 + c.AvailabilityType == "ALL" ||
  2011 + SqlFunc.Subqueryable<FlLabelCategoryLocationDbEntity>()
  2012 + .Where(cl => cl.CategoryId == c.Id && cl.LocationId == locationId)
  2013 + .Any() ||
  2014 + SqlFunc.Subqueryable<FlLabelCategoryRegionDbEntity>()
  2015 + .Where(cr => cr.CategoryId == c.Id && storeGroupIds.Contains(cr.GroupId))
  2016 + .Any() ||
  2017 + l.LocationId == locationId);
  2018 + }
  2019 + else
  2020 + {
  2021 + q = q.Where((lp, l, p, c, t, tpl, pc) =>
1969 2022 c.AvailabilityType == "ALL" ||
1970 2023 SqlFunc.Subqueryable<FlLabelCategoryLocationDbEntity>()
1971 2024 .Where(cl => cl.CategoryId == c.Id && cl.LocationId == locationId)
1972   - .Any())
  2025 + .Any() ||
  2026 + l.LocationId == locationId);
  2027 + }
  2028 +
  2029 + q = q
1973 2030 .Where((lp, l, p, c, t, tpl, pc) =>
1974 2031 l.LabelTypeId == null || l.LabelTypeId == "" || (!t.IsDeleted && t.State))
1975 2032 .Where((lp, l, p, c, t, tpl, pc) => !tpl.IsDeleted)
... ...
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/scripts/fl_label_entity_region_create.sql 0 → 100644
  1 +-- 标签类型 / 标签分类 / 标签多选项 的 Region 关联表(结构对齐 fl_product_category_region)
  2 +-- 用途:表达「所选 Region 内全部门店」的范围 ALL —— 只落 Region 绑定、不落门店快照,
  3 +-- 区内后续新增门店自动适用;详情/列表回显 locationIds = ["ALL"]。
  4 +-- 兼容:未执行本脚本时后端仍会回退为「展开区内门店快照」的旧行为。
  5 +
  6 +CREATE TABLE IF NOT EXISTS `fl_label_type_region` (
  7 + `Id` varchar(36) NOT NULL COMMENT '主键',
  8 + `LabelTypeId` varchar(36) NOT NULL COMMENT 'fl_label_type.Id',
  9 + `GroupId` varchar(36) NOT NULL COMMENT 'Region Id(fl_group.Id)',
  10 + `CreationTime` datetime NOT NULL COMMENT '创建时间',
  11 + `CreatorId` varchar(36) DEFAULT NULL COMMENT '创建者',
  12 + PRIMARY KEY (`Id`),
  13 + KEY `idx_fl_ltr_type` (`LabelTypeId`),
  14 + KEY `idx_fl_ltr_group` (`GroupId`)
  15 +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='标签类型适用 Region';
  16 +
  17 +CREATE TABLE IF NOT EXISTS `fl_label_category_region` (
  18 + `Id` varchar(36) NOT NULL COMMENT '主键',
  19 + `CategoryId` varchar(36) NOT NULL COMMENT 'fl_label_category.Id',
  20 + `GroupId` varchar(36) NOT NULL COMMENT 'Region Id(fl_group.Id)',
  21 + `CreationTime` datetime NOT NULL COMMENT '创建时间',
  22 + `CreatorId` varchar(36) DEFAULT NULL COMMENT '创建者',
  23 + PRIMARY KEY (`Id`),
  24 + KEY `idx_fl_lcr_category` (`CategoryId`),
  25 + KEY `idx_fl_lcr_group` (`GroupId`)
  26 +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='标签分类适用 Region';
  27 +
  28 +CREATE TABLE IF NOT EXISTS `fl_label_multiple_option_region` (
  29 + `Id` varchar(36) NOT NULL COMMENT '主键',
  30 + `MultipleOptionId` varchar(36) NOT NULL COMMENT 'fl_label_multiple_option.Id',
  31 + `GroupId` varchar(36) NOT NULL COMMENT 'Region Id(fl_group.Id)',
  32 + `CreationTime` datetime NOT NULL COMMENT '创建时间',
  33 + `CreatorId` varchar(36) DEFAULT NULL COMMENT '创建者',
  34 + PRIMARY KEY (`Id`),
  35 + KEY `idx_fl_lmor_option` (`MultipleOptionId`),
  36 + KEY `idx_fl_lmor_group` (`GroupId`)
  37 +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='标签多选项适用 Region';
... ...
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/scripts/fl_product_region_create.sql 0 → 100644
  1 +-- 产品适用 Region 关联表(与 fl_product_category_region 结构对齐)
  2 +-- 用途:表达「所选 Region 内全部门店」的产品范围 ALL —— 只落 Region 绑定、不落门店快照,
  3 +-- 区内后续新增门店自动适用;详情/列表回显 locationIds = ["ALL"]。
  4 +-- 兼容:未执行本脚本时后端仍会回退为「展开区内门店快照」的旧行为。
  5 +
  6 +CREATE TABLE IF NOT EXISTS `fl_product_region` (
  7 + `Id` varchar(36) NOT NULL COMMENT '主键',
  8 + `ProductId` varchar(36) NOT NULL COMMENT 'fl_product.Id',
  9 + `GroupId` varchar(36) NOT NULL COMMENT 'Region Id(fl_group.Id)',
  10 + `CreationTime` datetime NOT NULL COMMENT '创建时间',
  11 + `CreatorId` varchar(36) DEFAULT NULL COMMENT '创建者',
  12 + PRIMARY KEY (`Id`),
  13 + KEY `idx_fl_pr_product` (`ProductId`),
  14 + KEY `idx_fl_pr_group` (`GroupId`)
  15 +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='产品适用 Region';
... ...
美国版/Food Labeling Management Code/Yi.Abp.Net8/src/Yi.Abp.Web/appsettings.json
... ... @@ -20,7 +20,7 @@
20 20 },
21 21 //应用启动:SelfUrl 供 Program.cs UseUrls 绑定;用 0.0.0.0 避免写成固定局域网 IP 在本机无该网卡时启动失败(WinError 10049)
22 22 "App": {
23   - "SelfUrl": "http://172.18.23.63:19001",
  23 + "SelfUrl": "http://192.168.31.229:19001",
24 24 "CorsOrigins": "http://localhost:19001;http://localhost:18000;http://localhost:5666;http://localhost:5174;http://localhost:5173;http://localhost:3000;http://flus-test.3flabeling.com;https://flus-test.3flabeling.com;http://flus.3flabeling.com;https://flus.3flabeling.com;http://flus-teustest.3flabeling.com;https://flus-teustest.3flabeling.com;http://flus-test.3ffoodsafety.com;https://flus-test.3ffoodsafety.com;http://flus.3ffoodsafety.com;https://flus.3ffoodsafety.com"
25 25 },
26 26 //配置
... ... @@ -32,7 +32,7 @@
32 32  
33 33 "DbConnOptions": {
34 34 // 美国版数据库:本地/测试 antis-foodlabeling-test-us;正式 antis-foodlabeling-us(由正式环境部署脚本改写)
35   - "Url": "server=rm-bp19ohrgc6111ynzh1o.mysql.rds.aliyuncs.com;port=3306;database=antis-foodlabeling-us;uid=netteam;pwd=netteam;CharSet=utf8mb4;",
  35 + "Url": "server=rm-bp19ohrgc6111ynzh1o.mysql.rds.aliyuncs.com;port=3306;database=antis-foodlabeling-test-us;uid=netteam;pwd=netteam;CharSet=utf8mb4;",
36 36 "DbType": "Mysql",
37 37 "EnabledReadWrite": false,//是否启用读写分离
38 38 "EnabledCodeFirst": false,//是否通过代码优先创建数据库表结构
... ... @@ -40,6 +40,7 @@
40 40 "EnabledDbSeed": false,//是否启用数据库种子数据
41 41 "EnableUnderLine": false, // 是否启用驼峰转下划线
42 42  
  43 +
43 44 //SAAS多租户
44 45 "EnabledSaasMultiTenancy": false,//是否启用多租户
45 46 "EnabledConcurrencyException": false //是否启用并发异常处理
... ...
美国版/scripts/_deploy-ustest-now.ps1
1   -#Requires -Version 5.1
  1 +#Requires -Version 5.1
2 2 $ErrorActionPreference = "Stop"
3 3 $HostName = "47.253.11.59"
4 4 $UserName = "root"
... ...
美国版/scripts/泰鄂测试版部署.ps1
1   -#Requires -Version 5.1
  1 +#Requires -Version 5.1
2 2 <#
3 3 .SYNOPSIS
4 4 Te test API deploy
... ...
美国版/scripts/泰鄂美国测试版部署.ps1
1   -#Requires -Version 5.1
  1 +#Requires -Version 5.1
2 2 <#
3 3 .SYNOPSIS
4 4 Te US test API deploy
... ...
美国版/scripts/美国版本正式环境部署.ps1
1   -#Requires -Version 5.1
  1 +#Requires -Version 5.1
2 2 <#
3 3 .SYNOPSIS
4 4 美国版本正式环境 API 一键部署
... ...