Commit 4e6f4ed86f7331e3c3880583cc2ad18104358f8a

Authored by 李曜臣
1 parent 59b980c3

2026-09-04代码提交

Showing 21 changed files with 795 additions and 60 deletions
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/Dtos/UsAppLabeling/UsAppLabelPreviewDto.cs
... ... @@ -49,8 +49,16 @@ public class UsAppLabelPreviewDto
49 49  
50 50 /// <summary>
51 51 /// 当前预览上下文(模板+产品+标签类型)命中的默认值配置。
52   - /// 数据来源:fl_label_template_product_default.DefaultValuesJson
  52 + /// 数据来源:fl_label_template_product_default.DefaultValuesJson,并与标签
  53 + /// <c>LabelInfoJson.templateInputValues</c> 合并(标签级优先)。
  54 + /// Nutrition Facts 元素的值为营养成分 JSON 字符串。
53 55 /// </summary>
54 56 public Dictionary<string, object?>? TemplateProductDefaultValues { get; set; }
  57 +
  58 + /// <summary>
  59 + /// Nutrition Facts 元素已保存的营养成分表(elementId → 字段字典)。
  60 + /// 来源:标签 <c>templateInputValues</c> / 产品模板默认值中该元素对应的 JSON。
  61 + /// </summary>
  62 + public Dictionary<string, Dictionary<string, string>> NutritionByElementId { get; set; } = new();
55 63 }
56 64  
... ...
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/IServices/IDashboardAppService.cs
... ... @@ -15,6 +15,7 @@ public interface IDashboardAppService : IApplicationService
15 15 /// 按 Token 数据范围统计:<b>系统管理员</b>为全平台;<b>其它账号</b>仅统计其 <c>userlocation</c> 绑定门店所属公司范围内数据。
16 16 /// <c>companies</c> 统计可见 <c>fl_partner</c> 数;<c>regions</c> 统计可见 <c>fl_group</c> 数(与 Region 列表同一套 scope)。
17 17 /// <c>labels</c> 统计可见 <c>fl_label</c> 总数(与 Label 列表无额外筛选时同一套 scope)。
  18 + /// <c>activeTemplates</c> 统计可见且启用的 <c>fl_label_template</c> 数(与 Label Templates 列表无额外筛选时同一套 scope)。
18 19 /// <c>people</c> 为注册用户数(与 Team Member 列表 TotalCount 一致);<c>activeUsers</c> 为其中 <c>State=true</c> 的用户数。
19 20 /// 系统 Admin 统计全部未删 User;非 Admin 仅统计在可见门店有 <c>userlocation</c> 绑定的用户。
20 21 /// <c>recentLabels[].labelCode</c> 为门店当日打印序号 <c>yyyyMMdd-n</c>,规则与 <c>POST /api/app/us-app-labeling/preview</c>、print-log 一致。
... ...
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/IServices/IGroupAppService.cs
... ... @@ -44,6 +44,10 @@ public interface IGroupAppService : IApplicationService
44 44 /// 若 <c>groupName</c> 相对原值发生变化(忽略大小写与首尾空格),会同步更新未删除门店
45 45 /// <c>location.GroupName</c>(精确匹配旧 Region 名称,且 <c>location.Partner</c> 与当前 Region 所属公司名称一致),
46 46 /// 避免跨公司同名 Region 误更新。
  47 + /// 若 <c>State</c> 从 <c>true</c> 变为 <c>false</c>,级联停用其下全部 Location,
  48 + /// 软删这些门店的 <c>userlocation</c> 绑定(不停用成员、不解绑其它门店);
  49 + /// 若存在 <c>fl_team_member_region</c> 则删除该 Region 的成员关联;
  50 + /// inactive→active 不自动恢复下级或绑定;已 inactive 再次保存不重复级联。
47 51 /// </remarks>
48 52 Task<GroupGetOutputDto> UpdateAsync(Guid id, GroupUpdateInputVo input);
49 53  
... ...
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/IServices/ILocationAppService.cs
... ... @@ -28,6 +28,10 @@ public interface ILocationAppService : IApplicationService
28 28 /// </summary>
29 29 /// <param name="id">门店Id</param>
30 30 /// <param name="input">门店信息</param>
  31 + /// <remarks>
  32 + /// 若 <c>State</c> 从 <c>true</c> 变为 <c>false</c>,软删该门店的 <c>userlocation</c> 绑定(不停用成员);
  33 + /// inactive→active 不自动恢复绑定;已 inactive 再次保存不重复级联。批量编辑经本方法逐条处理,同样生效。
  34 + /// </remarks>
31 35 Task<LocationGetListOutputDto> UpdateAsync(Guid id, LocationUpdateInputVo input);
32 36  
33 37 /// <summary>
... ...
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/IServices/IPartnerAppService.cs
... ... @@ -74,6 +74,9 @@ public interface IPartnerAppService : IApplicationService
74 74 /// <remarks>
75 75 /// 若 <c>partnerName</c> 相对原值发生变化(忽略大小写与首尾空格),会同步更新未删除门店
76 76 /// <c>location.Partner</c>(精确匹配旧公司名称),以保持门店/产品/标签按名称解析的绑定关系。
  77 + /// 若 <c>State</c> 从 <c>true</c> 变为 <c>false</c>,级联停用其下全部 Region、Location,
  78 + /// 并将经该公司门店 <c>userlocation</c> 绑定的 Team Member 设为 <c>State=false</c>;
  79 + /// inactive→active 不自动恢复下级或绑定;已 inactive 再次保存不重复级联。
77 80 /// </remarks>
78 81 /// <response code="200">成功</response>
79 82 /// <response code="400">校验失败或记录不存在</response>
... ...
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/IServices/IUsAppLabelingAppService.cs
... ... @@ -18,6 +18,7 @@ public interface IUsAppLabelingAppService : IApplicationService
18 18 /// <summary>
19 19 /// App 打印预览:按标签编码解析模板并返回顶部展示字段 + 预览模板结构。
20 20 /// 出参 <c>labelId</c> 为门店当日**下一个**打印序号(<c>yyyyMMdd-n</c>),非 <c>fl_label.Id</c>。
  21 + /// 出参 <c>nutritionByElementId</c> / <c>templateProductDefaultValues</c> 含 Nutrition Facts 已保存 JSON。
21 22 /// </summary>
22 23 Task<UsAppLabelPreviewDto> PreviewAsync(UsAppLabelPreviewInputVo input);
23 24  
... ...
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/AccountStructureCascadeDeleteHelper.cs
... ... @@ -204,6 +204,16 @@ public static class AccountStructureCascadeDeleteHelper
204 204 }
205 205  
206 206 /// <summary>
  207 + /// 清理指定门店 Id 列表对应的 <c>userlocation</c> 绑定(逻辑删除)。
  208 + /// </summary>
  209 + public static Task SoftDeleteUserLocationBindingsAsync(
  210 + ISqlSugarClient db,
  211 + IReadOnlyList<Guid> locationIds,
  212 + DateTime now,
  213 + string? modifierId) =>
  214 + SoftDeleteUserLocationBindingsCoreAsync(db, locationIds, now, modifierId);
  215 +
  216 + /// <summary>
207 217 /// Region 存在下级门店且未确认级联删除时的提示文案。
208 218 /// </summary>
209 219 public static string BuildGroupCascadeRequiredMessage(int locationCount) =>
... ... @@ -240,7 +250,7 @@ public static class AccountStructureCascadeDeleteHelper
240 250 .ExecuteCommandAsync();
241 251 }
242 252  
243   - private static async Task SoftDeleteUserLocationBindingsAsync(
  253 + private static async Task SoftDeleteUserLocationBindingsCoreAsync(
244 254 ISqlSugarClient db,
245 255 IReadOnlyList<Guid> locationIds,
246 256 DateTime now,
... ... @@ -251,11 +261,15 @@ public static class AccountStructureCascadeDeleteHelper
251 261 return;
252 262 }
253 263  
254   - var normalizedKeys = locationIds
255   - .Select(g => TeamMemberListScopeHelper.NormalizeScopeKey(g.ToString("D")))
256   - .Where(x => !string.IsNullOrEmpty(x))
257   - .Distinct(StringComparer.OrdinalIgnoreCase)
258   - .ToList();
  264 + var normalizedKeys = new HashSet<string>(
  265 + locationIds
  266 + .SelectMany(g => new[]
  267 + {
  268 + TeamMemberListScopeHelper.NormalizeScopeKey(g.ToString("D")),
  269 + TeamMemberListScopeHelper.NormalizeScopeKey(g.ToString("N"))
  270 + })
  271 + .Where(x => !string.IsNullOrEmpty(x)),
  272 + StringComparer.OrdinalIgnoreCase);
259 273  
260 274 if (normalizedKeys.Count == 0)
261 275 {
... ... @@ -268,8 +282,13 @@ public static class AccountStructureCascadeDeleteHelper
268 282 .ToListAsync();
269 283  
270 284 var bindingIds = bindings
271   - .Where(x => normalizedKeys.Contains(TeamMemberListScopeHelper.NormalizeScopeKey(x.LocationId)))
  285 + .Where(x =>
  286 + {
  287 + var key = TeamMemberListScopeHelper.NormalizeScopeKey(x.LocationId);
  288 + return !string.IsNullOrEmpty(key) && normalizedKeys.Contains(key);
  289 + })
272 290 .Select(x => x.Id)
  291 + .Distinct(StringComparer.OrdinalIgnoreCase)
273 292 .ToList();
274 293  
275 294 if (bindingIds.Count == 0)
... ...
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/AccountStructureCascadeInactiveHelper.cs 0 → 100644
  1 +using FoodLabeling.Application.Services.DbModels;
  2 +using FoodLabeling.Domain.Entities;
  3 +using SqlSugar;
  4 +using Yi.Framework.Rbac.Domain.Entities;
  5 +
  6 +namespace FoodLabeling.Application.Helpers;
  7 +
  8 +/// <summary>
  9 +/// Account Management 结构(Company / Region / Location)停用(<c>State=false</c>)时的级联处理。
  10 +/// 仅在 <c>旧 State==true</c> 且 <c>新 State==false</c> 时触发;inactive→active 不自动恢复下级或绑定。
  11 +/// </summary>
  12 +public static class AccountStructureCascadeInactiveHelper
  13 +{
  14 + /// <summary>
  15 + /// 判断是否从启用变为停用。
  16 + /// </summary>
  17 + public static bool IsBecomingInactive(bool wasActive, bool newState) => wasActive && !newState;
  18 +
  19 + /// <summary>
  20 + /// Company 停用时:其下全部 Region、Location 设为 <c>State=false</c>;
  21 + /// 经该公司门店 <c>userlocation</c> 绑定的 Team Member 设为 <c>State=false</c>(不解绑 <c>userlocation</c>)。
  22 + /// </summary>
  23 + public static async Task CascadePartnerInactiveAsync(
  24 + ISqlSugarClient db,
  25 + string partnerId,
  26 + DateTime now,
  27 + Guid? modifierId)
  28 + {
  29 + var modifierIdString = modifierId?.ToString();
  30 +
  31 + await db.Updateable<FlGroupDbEntity>()
  32 + .SetColumns(x => new FlGroupDbEntity
  33 + {
  34 + State = false,
  35 + LastModificationTime = now,
  36 + LastModifierId = modifierIdString
  37 + })
  38 + .Where(x => !x.IsDeleted && x.PartnerId == partnerId && x.State)
  39 + .ExecuteCommandAsync();
  40 +
  41 + var locationIdStrings = await LocationScopeBindingHelper.ResolveLocationIdsFromPartnerIdsAsync(
  42 + db,
  43 + new[] { partnerId });
  44 +
  45 + await DeactivateLocationsByIdsAsync(db, locationIdStrings, now, modifierId);
  46 + await DeactivateUsersBoundToLocationsAsync(db, locationIdStrings, now, modifierId);
  47 + }
  48 +
  49 + /// <summary>
  50 + /// Region 停用时:其下全部 Location 设为 <c>State=false</c>;
  51 + /// 软删这些门店的 <c>userlocation</c> 绑定(不解绑其它门店、不停用成员);
  52 + /// 若存在 <c>fl_team_member_region</c> 表则删除该 Region 的成员关联。
  53 + /// </summary>
  54 + public static async Task CascadeGroupInactiveAsync(
  55 + ISqlSugarClient db,
  56 + string groupId,
  57 + DateTime now,
  58 + Guid? modifierId,
  59 + string? userLocationModifierId)
  60 + {
  61 + var locationIdStrings = await LocationScopeBindingHelper.ResolveLocationIdsFromGroupIdsAsync(
  62 + db,
  63 + new[] { groupId });
  64 +
  65 + await DeactivateLocationsByIdsAsync(db, locationIdStrings, now, modifierId);
  66 +
  67 + var locationGuids = ParseLocationGuids(locationIdStrings);
  68 + if (locationGuids.Count > 0)
  69 + {
  70 + await AccountStructureCascadeDeleteHelper.SoftDeleteUserLocationBindingsAsync(
  71 + db,
  72 + locationGuids,
  73 + now,
  74 + userLocationModifierId);
  75 + }
  76 +
  77 + await TryDeleteTeamMemberRegionByGroupIdAsync(db, groupId);
  78 + }
  79 +
  80 + /// <summary>
  81 + /// Location 停用时:软删该门店的 <c>userlocation</c> 绑定(不停用成员)。
  82 + /// </summary>
  83 + public static Task CascadeLocationInactiveAsync(
  84 + ISqlSugarClient db,
  85 + Guid locationId,
  86 + DateTime now,
  87 + string? userLocationModifierId) =>
  88 + AccountStructureCascadeDeleteHelper.SoftDeleteUserLocationBindingsForLocationAsync(
  89 + db,
  90 + locationId,
  91 + now,
  92 + userLocationModifierId);
  93 +
  94 + private static async Task DeactivateLocationsByIdsAsync(
  95 + ISqlSugarClient db,
  96 + IReadOnlyList<string> locationIdStrings,
  97 + DateTime now,
  98 + Guid? modifierId)
  99 + {
  100 + var locationGuids = ParseLocationGuids(locationIdStrings);
  101 + if (locationGuids.Count == 0)
  102 + {
  103 + return;
  104 + }
  105 +
  106 + await db.Updateable<LocationAggregateRoot>()
  107 + .SetColumns(x => new LocationAggregateRoot
  108 + {
  109 + State = false,
  110 + LastModificationTime = now,
  111 + LastModifierId = modifierId
  112 + })
  113 + .Where(x => !x.IsDeleted && locationGuids.Contains(x.Id) && x.State)
  114 + .ExecuteCommandAsync();
  115 + }
  116 +
  117 + private static async Task DeactivateUsersBoundToLocationsAsync(
  118 + ISqlSugarClient db,
  119 + IReadOnlyList<string> locationIdStrings,
  120 + DateTime now,
  121 + Guid? modifierId)
  122 + {
  123 + var userIds = await ResolveUserIdsBoundToLocationIdsAsync(db, locationIdStrings);
  124 + if (userIds.Count == 0)
  125 + {
  126 + return;
  127 + }
  128 +
  129 + await db.Updateable<UserAggregateRoot>()
  130 + .SetColumns(x => new UserAggregateRoot
  131 + {
  132 + State = false,
  133 + LastModificationTime = now,
  134 + LastModifierId = modifierId
  135 + })
  136 + .Where(x => !x.IsDeleted && x.State && userIds.Contains(x.Id))
  137 + .ExecuteCommandAsync();
  138 + }
  139 +
  140 + private static async Task<List<Guid>> ResolveUserIdsBoundToLocationIdsAsync(
  141 + ISqlSugarClient db,
  142 + IReadOnlyList<string> locationIdStrings)
  143 + {
  144 + var normalizedKeys = new HashSet<string>(
  145 + locationIdStrings
  146 + .Select(id => TeamMemberListScopeHelper.NormalizeScopeKey(id))
  147 + .Where(x => !string.IsNullOrEmpty(x)),
  148 + StringComparer.OrdinalIgnoreCase);
  149 +
  150 + if (normalizedKeys.Count == 0)
  151 + {
  152 + return new List<Guid>();
  153 + }
  154 +
  155 + var bindings = await db.Queryable<UserLocationDbEntity>()
  156 + .Where(x => !x.IsDeleted)
  157 + .Select(x => new { x.UserId, x.LocationId })
  158 + .ToListAsync();
  159 +
  160 + var userIdStrings = bindings
  161 + .Where(x => normalizedKeys.Contains(TeamMemberListScopeHelper.NormalizeScopeKey(x.LocationId)))
  162 + .Select(x => x.UserId)
  163 + .Where(x => !string.IsNullOrWhiteSpace(x))
  164 + .Distinct(StringComparer.OrdinalIgnoreCase)
  165 + .ToList();
  166 +
  167 + var result = new List<Guid>();
  168 + foreach (var uid in userIdStrings)
  169 + {
  170 + if (Guid.TryParse(uid.Trim(), out var guid))
  171 + {
  172 + result.Add(guid);
  173 + }
  174 + }
  175 +
  176 + return result;
  177 + }
  178 +
  179 + private static List<Guid> ParseLocationGuids(IReadOnlyList<string> locationIdStrings)
  180 + {
  181 + var result = new List<Guid>();
  182 + foreach (var id in locationIdStrings)
  183 + {
  184 + if (Guid.TryParse(id?.Trim(), out var guid))
  185 + {
  186 + result.Add(guid);
  187 + }
  188 + }
  189 +
  190 + return result;
  191 + }
  192 +
  193 + private static async Task TryDeleteTeamMemberRegionByGroupIdAsync(ISqlSugarClient db, string groupId)
  194 + {
  195 + if (!await TeamMemberRegionScopeHelper.HasTableAsync(db))
  196 + {
  197 + return;
  198 + }
  199 +
  200 + try
  201 + {
  202 + await db.Deleteable<FlTeamMemberRegionDbEntity>()
  203 + .Where(x => x.GroupId == groupId)
  204 + .ExecuteCommandAsync();
  205 + }
  206 + catch
  207 + {
  208 + // 表探测通过但删除失败时静默跳过,与 TeamMemberRegionScopeHelper 一致
  209 + }
  210 + }
  211 +}
... ...
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/AllScopeBindingHelper.cs
... ... @@ -428,9 +428,7 @@ public static class AllScopeBindingHelper
428 428 return (partnerIds, regionIds, locs);
429 429 }
430 430  
431   - /// <summary>
432   - /// 标签/产品分类等:解析 Region + Location 落库(对齐 Label:Region=ALL 时可保留具体门店快照)。
433   - /// </summary>
  431 + /// <summary>标签/产品分类等 Region + Location 落库结果。</summary>
434 432 public sealed class LabelEntityRegionLocationSaveResult
435 433 {
436 434 public string AvailabilityType { get; init; } = ScopeSpecified;
... ... @@ -440,6 +438,10 @@ public static class AllScopeBindingHelper
440 438 public List<string> LocationIds { get; init; } = new();
441 439 }
442 440  
  441 + /// <summary>
  442 + /// 标签/产品分类等:解析 Region + Location 落库(对齐 Label:Region=ALL 时可保留具体门店快照)。
  443 + /// <paramref name="locationIdsRaw"/> 含 <c>ALL</c> 且已传具体 Region 时,为范围内 ALL(Scoped ALL),禁止升公司级 ALL。
  444 + /// </summary>
443 445 public static async Task<LabelEntityRegionLocationSaveResult> ResolveLabelEntityRegionLocationForSaveAsync(
444 446 ISqlSugarClient db,
445 447 string? declaredAvailabilityType,
... ... @@ -459,9 +461,14 @@ public static class AllScopeBindingHelper
459 461  
460 462 // 仅显式 ALL 哨兵视为 Region=ALL。
461 463 // 禁止「公司下仅 1 个 Region + 勾选该 Region」自动升 ALL(否则编辑回显/再提交会丢 SPECIFIED)。
462   - // 无具体门店且未声明 SPECIFIED 时,才把「勾选当前全部 Region」归档为 ALL。
  464 + // locationIds=["ALL"] + 具体 RegionIds 为 Scoped ALL:禁止「勾选当前全部 Region」启发式升 Region=ALL。
463 465 var regionHasAll = regionHasAllSentinel;
464   - if (!regionHasAll && regionIds.Count > 0 && explicitLocationIds.Count == 0 && !declaredSpecified)
  466 + var isScopedAllWithConcreteRegions = locationHasAll && regionIds.Count > 0 && !regionHasAllSentinel;
  467 + if (!regionHasAll
  468 + && regionIds.Count > 0
  469 + && explicitLocationIds.Count == 0
  470 + && !declaredSpecified
  471 + && !isScopedAllWithConcreteRegions)
465 472 {
466 473 var allRegions = await ResolveAllRegionIdsAsync(
467 474 db,
... ... @@ -469,9 +476,14 @@ public static class AllScopeBindingHelper
469 476 regionHasAll = allRegions.Count > 0 && IsFullIdSelection(regionIds, allRegions);
470 477 }
471 478  
472   - // 仅 locationIds 含 ALL 哨兵才按「全部门店」展开;有具体 Guid 时一律按 SPECIFIED 快照落库
  479 + // locationIds=["ALL"]:相对已传 RegionIds 为范围内 ALL;有具体 Region 时禁止升公司级 ALL
473 480 if (locationHasAll)
474 481 {
  482 + if (isScopedAllWithConcreteRegions)
  483 + {
  484 + regionHasAll = false;
  485 + }
  486 +
475 487 if (regionHasAll)
476 488 {
477 489 var partnerScoped = await TryResolvePartnerScopedAllRegionAllLocationAsync(
... ...
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/DashboardScopeHelper.cs
... ... @@ -267,6 +267,30 @@ public static class DashboardScopeHelper
267 267 }
268 268  
269 269 /// <summary>
  270 + /// 统计范围内启用标签模板数(<c>fl_label_template</c>,未删除且 <c>State=true</c>),
  271 + /// 范围与 Label Templates 列表无额外 partnerId/groupId/locationId 筛选时一致。
  272 + /// </summary>
  273 + public static async Task<int> CountScopedActiveTemplatesAsync(
  274 + ISqlSugarClient db,
  275 + List<string>? scopedLocationIds,
  276 + DateTime? createdBefore)
  277 + {
  278 + var query = db.Queryable<FlLabelTemplateDbEntity>()
  279 + .Where(x => !x.IsDeleted && x.State);
  280 +
  281 + query = await LabelTemplateScopeHelper.ApplyTemplateScopeFilterAsync(
  282 + db, query, scopedLocationIds, null, null, null);
  283 +
  284 + if (createdBefore.HasValue)
  285 + {
  286 + query = query.Where(x => x.CreationTime < createdBefore.Value);
  287 + }
  288 +
  289 + query = LabelTemplateQueryHelper.ProjectListColumns(query);
  290 + return await query.CountAsync();
  291 + }
  292 +
  293 + /// <summary>
270 294 /// 为打印任务查询附加门店范围(<c>scopeLocationIds == null</c> 不限制)。
271 295 /// </summary>
272 296 public static ISugarQueryable<FlLabelPrintTaskDbEntity> ApplyPrintTaskLocationScope(
... ...
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/LabelRegionScopeHelper.cs
... ... @@ -51,6 +51,8 @@ public static class LabelRegionScopeHelper
51 51 /// <summary>
52 52 /// 解析新增/编辑入参中的 Region / Location 范围。
53 53 /// 前端 Select All 常传 SPECIFIED + 当前全量 Id:覆盖全集时归档为 ALL(或不写门店快照),后续新增 Region/Location 动态适用。
  54 + /// <paramref name="locationIds"/> 含 <c>ALL</c> 且已传具体 <paramref name="regionIds"/> 时,表示<strong>范围内 ALL</strong>(Scoped ALL):
  55 + /// 落 <c>AppliedRegionType=SPECIFIED</c> + <c>fl_label_region</c>,不写 <c>fl_label_location</c>,禁止升公司级 <c>ALL</c>。
54 56 /// </summary>
55 57 public static async Task<LabelRegionScopeSaveResult> ResolveScopeForSaveAsync(
56 58 ISqlSugarClient db,
... ... @@ -71,7 +73,19 @@ public static class LabelRegionScopeHelper
71 73 var hasScopeArrays = regionIds is not null || groupIds is not null || locationIds is not null;
72 74 var partnerContext = LocationScopeBindingHelper.NormalizeIds(partnerIdsForContext);
73 75  
74   - // locationIds / regionIds 含 ALL 哨兵:不归档为 Guid 校验,按全选处理(Company 由 fl_label.PartnerId 落库)
  76 + // locationIds=["ALL"] + 具体 RegionIds → Scoped ALL(SPECIFIED + Region 快照,无门店快照)
  77 + if (locationHasAll && mergedRegionIds.Count > 0 && !regionHasAll)
  78 + {
  79 + await ValidateRegionIdsExistAsync(db, mergedRegionIds);
  80 + return new LabelRegionScopeSaveResult
  81 + {
  82 + AppliedRegionType = AppliedRegionSpecified,
  83 + RegionIds = mergedRegionIds,
  84 + LocationIds = new List<string>()
  85 + };
  86 + }
  87 +
  88 + // Region=ALL + Location=ALL(或无具体 Region)→ 公司级/全局 ALL(Partner 由 fl_label.PartnerId 落库)
75 89 if (locationHasAll || (regionHasAll && explicitLocationIds.Count == 0))
76 90 {
77 91 return new LabelRegionScopeSaveResult
... ... @@ -487,7 +501,7 @@ public static class LabelRegionScopeHelper
487 501 null,
488 502 regionIds,
489 503 locationIds,
490   - ScopeAllEchoHelper.ForLabelRegionScope(appliedRegionType, locationIds));
  504 + ScopeAllEchoHelper.ForLabelRegionScope(appliedRegionType, locationIds, regionIds));
491 505  
492 506 return new LabelRegionScopeDisplay
493 507 {
... ... @@ -500,10 +514,14 @@ public static class LabelRegionScopeHelper
500 514 public static async Task<LabelLocationScopeDisplay> BuildLocationDisplayAsync(
501 515 ISqlSugarClient db,
502 516 string? appliedRegionType,
503   - IReadOnlyList<string> locationIds)
  517 + IReadOnlyList<string> locationIds,
  518 + string? labelId = null,
  519 + IReadOnlyList<string>? regionIds = null)
504 520 {
  521 + var persistedLocations = LocationScopeBindingHelper.NormalizeIds(locationIds);
  522 +
505 523 if (string.Equals(appliedRegionType, AppliedRegionAll, StringComparison.OrdinalIgnoreCase)
506   - && locationIds.Count == 0)
  524 + && persistedLocations.Count == 0)
507 525 {
508 526 return new LabelLocationScopeDisplay
509 527 {
... ... @@ -512,7 +530,25 @@ public static class LabelRegionScopeHelper
512 530 };
513 531 }
514 532  
515   - if (locationIds.Count == 0)
  533 + var concreteRegions = LocationScopeBindingHelper.FilterConcreteScopeIds(regionIds);
  534 + if (concreteRegions.Count == 0 && !string.IsNullOrWhiteSpace(labelId))
  535 + {
  536 + concreteRegions = await GetRegionIdsForLabelAsync(db, labelId);
  537 + }
  538 +
  539 + // Scoped ALL:SPECIFIED + 有 Region 快照 + 无门店快照 → 范围内 Location 回显 ALL
  540 + if (AllScopeBindingHelper.IsDeclaredSpecified(appliedRegionType)
  541 + && concreteRegions.Count > 0
  542 + && persistedLocations.Count == 0)
  543 + {
  544 + return new LabelLocationScopeDisplay
  545 + {
  546 + Location = AllLocationsDisplay,
  547 + LocationIds = new List<string> { AllScopeBindingHelper.ScopeAll }
  548 + };
  549 + }
  550 +
  551 + if (persistedLocations.Count == 0)
516 552 {
517 553 return new LabelLocationScopeDisplay
518 554 {
... ... @@ -521,7 +557,7 @@ public static class LabelRegionScopeHelper
521 557 };
522 558 }
523 559  
524   - var guidList = locationIds.Where(x => Guid.TryParse(x, out _)).Select(Guid.Parse).ToList();
  560 + var guidList = persistedLocations.Where(x => Guid.TryParse(x, out _)).Select(Guid.Parse).ToList();
525 561 var names = new List<string>();
526 562 if (guidList.Count > 0)
527 563 {
... ... @@ -539,9 +575,9 @@ public static class LabelRegionScopeHelper
539 575 var collapsed = await ScopeAllEchoHelper.CollapseScopeIdsToAllSentinelAsync(
540 576 db,
541 577 null,
542   - null,
543   - locationIds,
544   - ScopeAllEchoHelper.ForLabelRegionScope(appliedRegionType, locationIds));
  578 + concreteRegions,
  579 + persistedLocations,
  580 + ScopeAllEchoHelper.ForLabelRegionScope(appliedRegionType, persistedLocations, concreteRegions));
545 581  
546 582 return new LabelLocationScopeDisplay
547 583 {
... ...
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/ScopeAllEchoHelper.cs
... ... @@ -88,6 +88,10 @@ public static class ScopeAllEchoHelper
88 88 && LocationScopeBindingHelper.FilterConcreteScopeIds(regionIds).Count == 0
89 89 && LocationScopeBindingHelper.FilterConcreteScopeIds(locationIds).Count == 0,
90 90 IsLocationAll = AllScopeBindingHelper.IsDeclaredAll(availabilityType)
  91 + || (AllScopeBindingHelper.IsDeclaredSpecified(appliedRegionType)
  92 + && LocationScopeBindingHelper.FilterConcreteScopeIds(regionIds).Count > 0
  93 + && LocationScopeBindingHelper.FilterConcreteScopeIds(locationIds).Count == 0
  94 + && !AllScopeBindingHelper.IsDeclaredAll(appliedRegionType))
91 95 };
92 96  
93 97 /// <summary>兼容旧调用:无 Region 类型时用 AvailabilityType 同时驱动 Region/Location。</summary>
... ... @@ -96,16 +100,25 @@ public static class ScopeAllEchoHelper
96 100 string? availabilityType) =>
97 101 ForLabelEntityScope(appliedPartnerType, availabilityType, availabilityType);
98 102  
99   - /// <summary>Label:AppliedRegionType=ALL 且未落门店快照时 Region/Location 均为 ALL。</summary>
  103 + /// <summary>
  104 + /// Label:AppliedRegionType=ALL 且未落门店快照时 Region/Location 均为 ALL;
  105 + /// Scoped ALL(SPECIFIED + 有 Region 快照 + 无门店快照)时 Location 回显 <c>["ALL"]</c>(范围内 ALL)。
  106 + /// </summary>
100 107 public static ScopeAllEchoOptions ForLabelRegionScope(
101 108 string? appliedRegionType,
102   - IReadOnlyList<string> locationIds)
  109 + IReadOnlyList<string> locationIds,
  110 + IReadOnlyList<string>? regionIds = null)
103 111 {
  112 + var persistedLocations = LocationScopeBindingHelper.NormalizeIds(locationIds);
  113 + var concreteRegions = LocationScopeBindingHelper.FilterConcreteScopeIds(regionIds);
104 114 var isRegionAll = AllScopeBindingHelper.IsDeclaredAll(appliedRegionType);
  115 + var isScopedLocationAll = AllScopeBindingHelper.IsDeclaredSpecified(appliedRegionType)
  116 + && concreteRegions.Count > 0
  117 + && persistedLocations.Count == 0;
105 118 return new ScopeAllEchoOptions
106 119 {
107 120 IsRegionAll = isRegionAll,
108   - IsLocationAll = isRegionAll && LocationScopeBindingHelper.NormalizeIds(locationIds).Count == 0
  121 + IsLocationAll = (isRegionAll && persistedLocations.Count == 0) || isScopedLocationAll
109 122 };
110 123 }
111 124  
... ...
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/DashboardAppService.cs
... ... @@ -54,12 +54,10 @@ public class DashboardAppService : ApplicationService, IDashboardAppService
54 54 db.Queryable<FlLabelPrintTaskDbEntity>(), scopeLocationIds)
55 55 .CountAsync(x => x.CreationTime >= yesterdayStart && x.CreationTime < todayStart);
56 56  
57   - var activeTemplates = await LabelTemplateQueryHelper.ProjectListColumns(
58   - _dbContext.SqlSugarClient.Queryable<FlLabelTemplateDbEntity>())
59   - .CountAsync(x => !x.IsDeleted && x.State);
60   - var activeTemplatesPrevWeek = await LabelTemplateQueryHelper.ProjectListColumns(
61   - _dbContext.SqlSugarClient.Queryable<FlLabelTemplateDbEntity>())
62   - .CountAsync(x => !x.IsDeleted && x.State && x.CreationTime < weekStart);
  57 + var activeTemplates = await DashboardScopeHelper.CountScopedActiveTemplatesAsync(
  58 + db, scopeLocationIds, createdBefore: null);
  59 + var activeTemplatesPrevWeek = await DashboardScopeHelper.CountScopedActiveTemplatesAsync(
  60 + db, scopeLocationIds, createdBefore: weekStart);
63 61  
64 62 var activeUsers = await DashboardScopeHelper.CountScopedRegisteredUsersAsync(
65 63 db, scopeLocationIds, activeOnly: true, createdBefore: null);
... ...
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/GroupAppService.cs
... ... @@ -147,6 +147,7 @@ public class GroupAppService : ApplicationService, IGroupAppService
147 147 throw new UserFriendlyException("Group not found.");
148 148 }
149 149  
  150 + var wasActive = entity.State;
150 151 var oldGroupName = entity.GroupName;
151 152 var oldPartnerIdForCascade = entity.PartnerId;
152 153 var name = input.GroupName?.Trim();
... ... @@ -194,6 +195,17 @@ public class GroupAppService : ApplicationService, IGroupAppService
194 195 entity.LastModifierId = CurrentUser?.Id?.ToString();
195 196  
196 197 await _dbContext.SqlSugarClient.Updateable(entity).ExecuteCommandAsync();
  198 +
  199 + if (AccountStructureCascadeInactiveHelper.IsBecomingInactive(wasActive, entity.State))
  200 + {
  201 + await AccountStructureCascadeInactiveHelper.CascadeGroupInactiveAsync(
  202 + _dbContext.SqlSugarClient,
  203 + groupId,
  204 + Clock.Now,
  205 + CurrentUser?.Id,
  206 + CurrentUser?.Id?.ToString());
  207 + }
  208 +
197 209 return await GetAsync(id);
198 210 }
199 211  
... ...
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/LabelAppService.cs
... ... @@ -223,7 +223,7 @@ public class LabelAppService : ApplicationService, ILabelAppService
223 223 regionScopeMap[lid] = await LabelRegionScopeHelper.BuildScopeDisplayAsync(
224 224 db, lid, applied, locIds);
225 225 locationScopeMap[lid] = await LabelRegionScopeHelper.BuildLocationDisplayAsync(
226   - db, applied, locIds);
  226 + db, applied, locIds, lid);
227 227 locationIdsMap[lid] = locationScopeMap[lid].LocationIds;
228 228 labelMap.TryGetValue(lid, out var partnerRow);
229 229 partnerEchoMap[lid] = await BuildLabelPartnerEchoAsync(
... ... @@ -1198,16 +1198,22 @@ public class LabelAppService : ApplicationService, ILabelAppService
1198 1198 partnerIds = !string.IsNullOrWhiteSpace(storedPartnerId)
1199 1199 ? new List<string> { storedPartnerId }
1200 1200 : await LocationScopeBindingHelper.ResolvePartnerIdsFromLocationIdsAsync(db, locationIds);
  1201 + var persistedLocationIds = locationIds;
  1202 + var regionIdsFromDb = !string.IsNullOrWhiteSpace(labelId)
  1203 + ? await LabelRegionScopeHelper.GetRegionIdsForLabelAsync(db, labelId)
  1204 + : new List<string>();
1201 1205 var storedRegionScope = !string.IsNullOrWhiteSpace(labelId)
1202   - ? await LabelRegionScopeHelper.BuildScopeDisplayAsync(db, labelId, appliedRegionType, locationIds)
  1206 + ? await LabelRegionScopeHelper.BuildScopeDisplayAsync(
  1207 + db, labelId, appliedRegionType, persistedLocationIds)
1203 1208 : new LabelRegionScopeHelper.LabelRegionScopeDisplay { RegionIds = new List<string>() };
1204 1209 regionIdsForDto = storedRegionScope.RegionIds;
1205 1210 var collapsed = await ScopeAllEchoHelper.CollapseScopeIdsToAllSentinelAsync(
1206 1211 db,
1207 1212 partnerIds,
1208 1213 regionIdsForDto,
1209   - locationIds,
1210   - ScopeAllEchoHelper.ForLabelRegionScope(appliedRegionType, locationIds));
  1214 + persistedLocationIds,
  1215 + ScopeAllEchoHelper.ForLabelRegionScope(
  1216 + appliedRegionType, persistedLocationIds, regionIdsFromDb));
1211 1217 if (string.IsNullOrWhiteSpace(storedPartnerId))
1212 1218 {
1213 1219 partnerIds = collapsed.PartnerIds;
... ... @@ -1226,7 +1232,7 @@ public class LabelAppService : ApplicationService, ILabelAppService
1226 1232 var locationDisplay = isDynamicAll
1227 1233 ? LabelRegionScopeHelper.AllLocationsDisplay
1228 1234 : (await LabelRegionScopeHelper.BuildLocationDisplayAsync(
1229   - db, appliedRegionType, locationIds)).Location;
  1235 + db, appliedRegionType, locationIds, labelId)).Location;
1230 1236  
1231 1237 var companyIdsEcho = partnerIds.Count == 1
1232 1238 && !AllScopeBindingHelper.IsDeclaredAll(partnerIds[0])
... ...
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/LabelTypeAppService.cs
... ... @@ -61,7 +61,13 @@ public class LabelTypeAppService : ApplicationService, ILabelTypeAppService
61 61 var entities = await query.ToPageListAsync(input.SkipCount, input.MaxResultCount, total);
62 62 var ids = entities.Select(x => x.Id).ToList();
63 63  
64   - var countMap = await BuildTypeLabelStatsMapAsync(ids, scopedLocationIds);
  64 + var countMap = await BuildTypeLabelStatsMapAsync(
  65 + ids,
  66 + scopedLocationIds,
  67 + scopedPartnerIds,
  68 + input.PartnerId,
  69 + input.GroupId,
  70 + input.LocationId);
65 71 var scopeMap = await BuildTypeConfiguredScopeMapAsync(entities);
66 72 var partnerScopeMap = await LabelEntityPartnerScopeHelper.BuildPartnerScopeDisplayMapAsync(
67 73 _dbContext.SqlSugarClient,
... ... @@ -439,9 +445,16 @@ public class LabelTypeAppService : ApplicationService, ILabelTypeAppService
439 445 await _dbContext.SqlSugarClient.Insertable(rows).ExecuteCommandAsync();
440 446 }
441 447  
  448 + /// <summary>
  449 + /// 统计各类型下可见标签数量,范围与 Label 列表一致(Partner + Region/Location 动态命中)。
  450 + /// </summary>
442 451 private async Task<Dictionary<string, TypeLabelStats>> BuildTypeLabelStatsMapAsync(
443 452 List<string> typeIds,
444   - List<string>? scopedLocationIds)
  453 + List<string>? scopedLocationIds,
  454 + List<string>? scopedPartnerIds,
  455 + string? partnerId,
  456 + string? groupId,
  457 + string? locationId)
445 458 {
446 459 var result = new Dictionary<string, TypeLabelStats>(StringComparer.Ordinal);
447 460 if (typeIds.Count == 0)
... ... @@ -449,11 +462,53 @@ public class LabelTypeAppService : ApplicationService, ILabelTypeAppService
449 462 return result;
450 463 }
451 464  
452   - var labelQuery = _dbContext.SqlSugarClient.Queryable<FlLabelDbEntity>()
  465 + var db = _dbContext.SqlSugarClient;
  466 + var regionSchema = await LabelRegionSchemaHelper.GetStatusAsync(db);
  467 + var labelQuery = db.Queryable<FlLabelDbEntity>()
453 468 .Where(x => !x.IsDeleted)
454 469 .Where(x => x.LabelTypeId != null && typeIds.Contains(x.LabelTypeId));
455 470  
456   - labelQuery = ApplyLabelScopeOnLabels(labelQuery, scopedLocationIds);
  471 + labelQuery = LabelRegionScopeHelper.ApplyLabelPartnerListFilter(labelQuery, scopedPartnerIds);
  472 +
  473 + var filterGroupId = groupId?.Trim();
  474 + var applyLocationFilter = LabelEntityListScopeHelper.ShouldApplyLocationAvailabilityFilter(
  475 + partnerId, groupId, locationId);
  476 +
  477 + if (scopedLocationIds is not null && applyLocationFilter)
  478 + {
  479 + if (scopedLocationIds.Count == 0)
  480 + {
  481 + labelQuery = LabelRegionScopeHelper.ApplyLabelAllRegionOnlyFilter(
  482 + db, labelQuery, regionSchema);
  483 + }
  484 + else if (!string.IsNullOrWhiteSpace(filterGroupId))
  485 + {
  486 + labelQuery = LabelRegionScopeHelper.ApplyLabelRegionListFilter(
  487 + db, labelQuery, filterGroupId, scopedLocationIds, regionSchema);
  488 + }
  489 + else
  490 + {
  491 + labelQuery = LabelRegionScopeHelper.ApplyLabelLocationListFilter(
  492 + db, labelQuery, scopedLocationIds, regionSchema);
  493 + }
  494 + }
  495 + else if (!string.IsNullOrWhiteSpace(partnerId) && !applyLocationFilter)
  496 + {
  497 + if (scopedLocationIds is null)
  498 + {
  499 + // 管理员且未展开到门店:不过滤
  500 + }
  501 + else if (scopedLocationIds.Count == 0)
  502 + {
  503 + labelQuery = LabelRegionScopeHelper.ApplyLabelAllRegionOnlyFilter(
  504 + db, labelQuery, regionSchema);
  505 + }
  506 + else
  507 + {
  508 + labelQuery = LabelRegionScopeHelper.ApplyLabelLocationListFilter(
  509 + db, labelQuery, scopedLocationIds, regionSchema);
  510 + }
  511 + }
457 512  
458 513 var rows = await labelQuery
459 514 .Select(x => new { x.LabelTypeId, x.CreationTime, x.LastModificationTime })
... ... @@ -596,20 +651,6 @@ public class LabelTypeAppService : ApplicationService, ILabelTypeAppService
596 651 return result;
597 652 }
598 653  
599   - private static ISugarQueryable<FlLabelDbEntity> ApplyLabelScopeOnLabels(
600   - ISugarQueryable<FlLabelDbEntity> labelQuery,
601   - List<string>? scopedLocationIds)
602   - {
603   - if (scopedLocationIds is null)
604   - {
605   - return labelQuery;
606   - }
607   -
608   - return scopedLocationIds.Count == 0
609   - ? labelQuery.Where(_ => false)
610   - : labelQuery.Where(l => scopedLocationIds.Contains(l.LocationId));
611   - }
612   -
613 654 private sealed class TypeScopeData
614 655 {
615 656 public string Region { get; init; } = string.Empty;
... ...
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/LocationAppService.cs
... ... @@ -138,6 +138,7 @@ public class LocationAppService : ApplicationService, ILocationAppService
138 138 }
139 139  
140 140 /// <inheritdoc />
  141 + [UnitOfWork]
141 142 public async Task<LocationGetListOutputDto> UpdateAsync(Guid id, [FromBody] LocationUpdateInputVo input)
142 143 {
143 144 await AccountManagementStructureHelper.EnsureCanMutateRegionAndLocationAsync(CurrentUser, _dbContext);
... ... @@ -215,6 +216,16 @@ public class LocationAppService : ApplicationService, ILocationAppService
215 216  
216 217 await _locationRepository.UpdateAsync(entity);
217 218  
  219 + // inactive 时始终解绑 Team Member(幂等):避免已 inactive 再保存时跳过,或历史残留绑定清不掉
  220 + if (!entity.State)
  221 + {
  222 + await AccountStructureCascadeInactiveHelper.CascadeLocationInactiveAsync(
  223 + db,
  224 + id,
  225 + Clock.Now,
  226 + CurrentUser?.Id?.ToString());
  227 + }
  228 +
218 229 var saved = await _locationRepository.GetSingleAsync(x => x.Id == id && x.IsDeleted == false);
219 230 return await ToListDtoAsync(saved ?? entity);
220 231 }
... ...
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/PartnerAppService.cs
... ... @@ -116,6 +116,7 @@ public class PartnerAppService : ApplicationService, IPartnerAppService
116 116 throw new UserFriendlyException("Partner not found.");
117 117 }
118 118  
  119 + var wasActive = entity.State;
119 120 var oldName = entity.PartnerName;
120 121 var name = input.PartnerName?.Trim();
121 122 if (string.IsNullOrWhiteSpace(name))
... ... @@ -156,6 +157,16 @@ public class PartnerAppService : ApplicationService, IPartnerAppService
156 157 entity.LastModifierId = CurrentUser?.Id?.ToString();
157 158  
158 159 await _dbContext.SqlSugarClient.Updateable(entity).ExecuteCommandAsync();
  160 +
  161 + if (AccountStructureCascadeInactiveHelper.IsBecomingInactive(wasActive, entity.State))
  162 + {
  163 + await AccountStructureCascadeInactiveHelper.CascadePartnerInactiveAsync(
  164 + _dbContext.SqlSugarClient,
  165 + partnerId,
  166 + Clock.Now,
  167 + CurrentUser?.Id);
  168 + }
  169 +
159 170 return await GetAsync(id);
160 171 }
161 172  
... ...
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/ProductAppService.cs
... ... @@ -1177,7 +1177,12 @@ public class ProductAppService : ApplicationService, IProductAppService
1177 1177  
1178 1178 var regionHasAll = regionHasAllSentinel;
1179 1179 var declaredSpecified = AllScopeBindingHelper.IsDeclaredSpecified(input.AvailabilityType);
1180   - if (!regionHasAll && groupIds.Count > 0 && explicitLocationIds.Count == 0 && !declaredSpecified)
  1180 + var isScopedAllWithConcreteRegions = locationHasAll && groupIds.Count > 0 && !regionHasAllSentinel;
  1181 + if (!regionHasAll
  1182 + && groupIds.Count > 0
  1183 + && explicitLocationIds.Count == 0
  1184 + && !declaredSpecified
  1185 + && !isScopedAllWithConcreteRegions)
1181 1186 {
1182 1187 var allRegions = await AllScopeBindingHelper.ResolveAllRegionIdsAsync(
1183 1188 _dbContext.SqlSugarClient, partnerContext);
... ... @@ -1197,6 +1202,11 @@ public class ProductAppService : ApplicationService, IProductAppService
1197 1202  
1198 1203 if (locationHasAll)
1199 1204 {
  1205 + if (isScopedAllWithConcreteRegions)
  1206 + {
  1207 + regionHasAll = false;
  1208 + }
  1209 +
1200 1210 if (regionHasAll)
1201 1211 {
1202 1212 return new ProductScopeSaveResult
... ... @@ -1208,6 +1218,7 @@ public class ProductAppService : ApplicationService, IProductAppService
1208 1218 };
1209 1219 }
1210 1220  
  1221 + // Scoped ALL:部分 Region + Location ALL → SPECIFIED,不写门店快照(新区店靠 Region 动态匹配需 fl_product_region;此处展开区内门店快照)
1211 1222 var expandRegions = groupIds.Count > 0 ? groupIds : null;
1212 1223 var expanded = await LocationScopeBindingHelper.ExpandScopedAllLocationsForSaveAsync(
1213 1224 _dbContext.SqlSugarClient,
... ...
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/UsAppLabelingAppService.cs
... ... @@ -333,7 +333,7 @@ public class UsAppLabelingAppService : ApplicationService, IUsAppLabelingAppServ
333 333 /// ```
334 334 /// </remarks>
335 335 /// <param name="input">预览入参</param>
336   - /// <returns>顶部字段 + 预览模板结构</returns>
  336 + /// <returns>顶部字段 + 预览模板结构(含 <c>nutritionByElementId</c> 营养成分 JSON)</returns>
337 337 /// <response code="200">成功</response>
338 338 /// <response code="400">参数错误/数据不存在</response>
339 339 /// <response code="500">服务器错误</response>
... ... @@ -485,11 +485,25 @@ public class UsAppLabelingAppService : ApplicationService, IUsAppLabelingAppServ
485 485 }
486 486 }
487 487  
  488 + var nutritionByElementId = ExtractNutritionByElementId(
  489 + template.Elements,
  490 + templateProductDefaultValues);
  491 +
488 492 if (templateProductDefaultValues is { Count: > 0 })
489 493 {
490 494 ApplyTemplateProductDefaultValuesToPreviewElements(template.Elements, templateProductDefaultValues);
491 495 }
492 496  
  497 + if (nutritionByElementId.Count > 0)
  498 + {
  499 + ApplyNutritionFactsJsonToPreviewElements(template.Elements, nutritionByElementId);
  500 + foreach (var (elementId, fields) in nutritionByElementId)
  501 + {
  502 + templateProductDefaultValues ??= new Dictionary<string, object?>();
  503 + templateProductDefaultValues[elementId] = JsonSerializer.Serialize(fields);
  504 + }
  505 + }
  506 +
493 507 return new UsAppLabelPreviewDto
494 508 {
495 509 LabelId = nextDailyLabelId,
... ... @@ -505,7 +519,8 @@ public class UsAppLabelingAppService : ApplicationService, IUsAppLabelingAppServ
505 519 LabelLastEdited = labelRow.LastModificationTime ?? labelRow.CreationTime,
506 520 PreviewImageBase64Png = null,
507 521 Template = template,
508   - TemplateProductDefaultValues = templateProductDefaultValues
  522 + TemplateProductDefaultValues = templateProductDefaultValues,
  523 + NutritionByElementId = nutritionByElementId
509 524 };
510 525 }
511 526  
... ... @@ -1258,6 +1273,10 @@ public class UsAppLabelingAppService : ApplicationService, IUsAppLabelingAppServ
1258 1273  
1259 1274 switch (type)
1260 1275 {
  1276 + case "NUTRITION":
  1277 + case "NUTRITIONFACTS":
  1278 + ApplyNutritionManualToConfig(cfg, ParseNutritionManualObject(stored));
  1279 + break;
1261 1280 case "DATE":
1262 1281 case "TIME":
1263 1282 case "DURATION":
... ... @@ -1307,6 +1326,297 @@ public class UsAppLabelingAppService : ApplicationService, IUsAppLabelingAppServ
1307 1326 }
1308 1327 }
1309 1328  
  1329 + private const string NutritionCompositeSep = "###nut###";
  1330 +
  1331 + private static bool IsNutritionPreviewElement(LabelTemplateElementDto el)
  1332 + {
  1333 + var type = (el.ElementType ?? string.Empty).Trim().ToUpperInvariant();
  1334 + if (type is "NUTRITION" or "NUTRITIONFACTS")
  1335 + {
  1336 + return true;
  1337 + }
  1338 +
  1339 + var typeAdd = (el.TypeAdd ?? string.Empty).Trim().ToUpperInvariant();
  1340 + var name = (el.ElementName ?? string.Empty).Trim().ToUpperInvariant();
  1341 + return typeAdd.Contains("NUTRITION", StringComparison.Ordinal)
  1342 + || name.Contains("NUTRITION", StringComparison.Ordinal);
  1343 + }
  1344 +
  1345 + /// <summary>
  1346 + /// 从标签/产品默认值中提取 Nutrition Facts JSON(elementId → 字段)。
  1347 + /// </summary>
  1348 + private static Dictionary<string, Dictionary<string, string>> ExtractNutritionByElementId(
  1349 + IList<LabelTemplateElementDto>? elements,
  1350 + Dictionary<string, object?>? defaults)
  1351 + {
  1352 + var result = new Dictionary<string, Dictionary<string, string>>(StringComparer.Ordinal);
  1353 + if (elements is null || elements.Count == 0 || defaults is not { Count: > 0 })
  1354 + {
  1355 + return result;
  1356 + }
  1357 +
  1358 + foreach (var el in elements)
  1359 + {
  1360 + if (!IsNutritionPreviewElement(el) || string.IsNullOrWhiteSpace(el.Id))
  1361 + {
  1362 + continue;
  1363 + }
  1364 +
  1365 + var manual = ResolveNutritionManualForElement(el, defaults);
  1366 + if (manual.Count == 0)
  1367 + {
  1368 + continue;
  1369 + }
  1370 +
  1371 + result[el.Id.Trim()] = manual;
  1372 + }
  1373 +
  1374 + return result;
  1375 + }
  1376 +
  1377 + private static Dictionary<string, string> ResolveNutritionManualForElement(
  1378 + LabelTemplateElementDto el,
  1379 + Dictionary<string, object?> defaults)
  1380 + {
  1381 + var stored = ResolveTemplateProductDefaultValueForElement(el, defaults);
  1382 + var fromDirect = ParseNutritionManualObject(stored);
  1383 + if (fromDirect.Count > 0)
  1384 + {
  1385 + return fromDirect;
  1386 + }
  1387 +
  1388 + var id = el.Id?.Trim() ?? string.Empty;
  1389 + if (string.IsNullOrWhiteSpace(id))
  1390 + {
  1391 + return new Dictionary<string, string>(StringComparer.Ordinal);
  1392 + }
  1393 +
  1394 + var prefix = id + NutritionCompositeSep;
  1395 + var composite = new Dictionary<string, string>(StringComparer.Ordinal);
  1396 + foreach (var kv in defaults)
  1397 + {
  1398 + if (kv.Key.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
  1399 + {
  1400 + composite[kv.Key[prefix.Length..]] = TemplateProductDefaultValueToStoredString(kv.Value) ?? string.Empty;
  1401 + }
  1402 + }
  1403 +
  1404 + return composite;
  1405 + }
  1406 +
  1407 + private static Dictionary<string, string> ParseNutritionManualObject(string? raw)
  1408 + {
  1409 + var result = new Dictionary<string, string>(StringComparer.Ordinal);
  1410 + if (string.IsNullOrWhiteSpace(raw))
  1411 + {
  1412 + return result;
  1413 + }
  1414 +
  1415 + var text = raw.Trim();
  1416 + if (!text.StartsWith('{'))
  1417 + {
  1418 + return result;
  1419 + }
  1420 +
  1421 + try
  1422 + {
  1423 + using var doc = JsonDocument.Parse(text);
  1424 + if (doc.RootElement.ValueKind != JsonValueKind.Object)
  1425 + {
  1426 + return result;
  1427 + }
  1428 +
  1429 + foreach (var prop in doc.RootElement.EnumerateObject())
  1430 + {
  1431 + var key = prop.Name.Trim();
  1432 + if (string.IsNullOrWhiteSpace(key))
  1433 + {
  1434 + continue;
  1435 + }
  1436 +
  1437 + result[key] = prop.Value.ValueKind switch
  1438 + {
  1439 + JsonValueKind.String => prop.Value.GetString() ?? string.Empty,
  1440 + JsonValueKind.Null => string.Empty,
  1441 + JsonValueKind.True => "true",
  1442 + JsonValueKind.False => "false",
  1443 + JsonValueKind.Number => prop.Value.GetRawText(),
  1444 + _ => prop.Value.GetRawText()
  1445 + };
  1446 + }
  1447 + }
  1448 + catch
  1449 + {
  1450 + return result;
  1451 + }
  1452 +
  1453 + return result;
  1454 + }
  1455 +
  1456 + private static void ApplyNutritionFactsJsonToPreviewElements(
  1457 + IList<LabelTemplateElementDto>? elements,
  1458 + Dictionary<string, Dictionary<string, string>> nutritionByElementId)
  1459 + {
  1460 + if (elements is null || elements.Count == 0 || nutritionByElementId.Count == 0)
  1461 + {
  1462 + return;
  1463 + }
  1464 +
  1465 + foreach (var el in elements)
  1466 + {
  1467 + if (!IsNutritionPreviewElement(el) || string.IsNullOrWhiteSpace(el.Id))
  1468 + {
  1469 + continue;
  1470 + }
  1471 +
  1472 + if (!nutritionByElementId.TryGetValue(el.Id.Trim(), out var manual) || manual.Count == 0)
  1473 + {
  1474 + continue;
  1475 + }
  1476 +
  1477 + var cfg = ParsePreviewElementConfig(el.ConfigJson);
  1478 + ApplyNutritionManualToConfig(cfg, manual);
  1479 + el.ConfigJson = cfg;
  1480 + }
  1481 + }
  1482 +
  1483 + private static void ApplyNutritionManualToConfig(
  1484 + Dictionary<string, object?> cfg,
  1485 + Dictionary<string, string> manual)
  1486 + {
  1487 + if (manual.Count == 0)
  1488 + {
  1489 + return;
  1490 + }
  1491 +
  1492 + cfg["nutritionFactsJson"] = JsonSerializer.Serialize(manual);
  1493 + foreach (var kv in manual)
  1494 + {
  1495 + var key = kv.Key?.Trim();
  1496 + if (string.IsNullOrWhiteSpace(key))
  1497 + {
  1498 + continue;
  1499 + }
  1500 +
  1501 + cfg[key] = kv.Value ?? string.Empty;
  1502 + }
  1503 +
  1504 + if (TryPickNutritionField(manual, out var calories, "calories"))
  1505 + {
  1506 + cfg["calories"] = calories;
  1507 + cfg["Calories"] = calories;
  1508 + }
  1509 +
  1510 + if (TryPickNutritionField(manual, out var servings, "servingsPerContainer", "servings"))
  1511 + {
  1512 + cfg["servingsPerContainer"] = servings;
  1513 + cfg["servings"] = servings;
  1514 + }
  1515 +
  1516 + if (TryPickNutritionField(manual, out var servingSize, "servingSize", "serveSize"))
  1517 + {
  1518 + cfg["servingSize"] = servingSize;
  1519 + cfg["serveSize"] = servingSize;
  1520 + }
  1521 +
  1522 + if (TryPickNutritionField(manual, out var fat, "fat", "totalFat"))
  1523 + {
  1524 + cfg["fat"] = fat;
  1525 + cfg["totalFat"] = fat;
  1526 + }
  1527 +
  1528 + if (TryPickNutritionField(manual, out var carbs, "carbs", "totalCarbo", "totalCarbohydrate"))
  1529 + {
  1530 + cfg["carbs"] = carbs;
  1531 + }
  1532 +
  1533 + if (TryPickNutritionField(manual, out var sugars, "totalSugar", "sugars"))
  1534 + {
  1535 + cfg["totalSugar"] = sugars;
  1536 + }
  1537 +
  1538 + if (cfg.TryGetValue("fixedNutrients", out var fixedRaw) && fixedRaw is not null)
  1539 + {
  1540 + ApplyNutritionManualToFixedNutrients(cfg, manual);
  1541 + }
  1542 + }
  1543 +
  1544 + private static bool TryPickNutritionField(
  1545 + Dictionary<string, string> manual,
  1546 + out string value,
  1547 + params string[] keys)
  1548 + {
  1549 + foreach (var key in keys)
  1550 + {
  1551 + foreach (var kv in manual)
  1552 + {
  1553 + if (string.Equals(kv.Key, key, StringComparison.OrdinalIgnoreCase)
  1554 + && !string.IsNullOrWhiteSpace(kv.Value))
  1555 + {
  1556 + value = kv.Value;
  1557 + return true;
  1558 + }
  1559 + }
  1560 + }
  1561 +
  1562 + value = string.Empty;
  1563 + return false;
  1564 + }
  1565 +
  1566 + private static void ApplyNutritionManualToFixedNutrients(
  1567 + Dictionary<string, object?> cfg,
  1568 + Dictionary<string, string> manual)
  1569 + {
  1570 + try
  1571 + {
  1572 + var json = JsonSerializer.Serialize(cfg["fixedNutrients"]);
  1573 + var rows = JsonSerializer.Deserialize<List<Dictionary<string, object?>>>(json);
  1574 + if (rows is null || rows.Count == 0)
  1575 + {
  1576 + return;
  1577 + }
  1578 +
  1579 + foreach (var row in rows)
  1580 + {
  1581 + if (!row.TryGetValue("key", out var keyObj))
  1582 + {
  1583 + continue;
  1584 + }
  1585 +
  1586 + var key = Convert.ToString(keyObj, CultureInfo.InvariantCulture)?.Trim();
  1587 + if (string.IsNullOrWhiteSpace(key))
  1588 + {
  1589 + continue;
  1590 + }
  1591 +
  1592 + if (TryPickNutritionField(manual, out var amount, key, AliasForNutritionKey(key)))
  1593 + {
  1594 + row["value"] = amount;
  1595 + }
  1596 +
  1597 + if (TryPickNutritionField(manual, out var pct, $"{key}Percent"))
  1598 + {
  1599 + row["dailyValuePercent"] = pct;
  1600 + }
  1601 + }
  1602 +
  1603 + cfg["fixedNutrients"] = rows;
  1604 + }
  1605 + catch
  1606 + {
  1607 + // keep original fixedNutrients when merge fails
  1608 + }
  1609 + }
  1610 +
  1611 + private static string AliasForNutritionKey(string key) => key switch
  1612 + {
  1613 + "fat" => "totalFat",
  1614 + "totalFat" => "fat",
  1615 + "carbs" => "totalCarbo",
  1616 + "totalSugar" => "sugars",
  1617 + _ => key
  1618 + };
  1619 +
1310 1620 private static string? ResolveTemplateProductDefaultValueForElement(
1311 1621 LabelTemplateElementDto el,
1312 1622 Dictionary<string, object?> defaults)
... ...
美国版/Food Labeling Management Code/Yi.Abp.Net8/src/Yi.Abp.Web/appsettings.json
... ... @@ -20,14 +20,13 @@
20 20 },
21 21 //应用启动:SelfUrl 供 Program.cs UseUrls 绑定;用 0.0.0.0 避免写成固定局域网 IP 在本机无该网卡时启动失败(WinError 10049)
22 22 "App": {
23   - "SelfUrl": "http://192.168.31.89:19003",
  23 + "SelfUrl": "http://192.168.31.88:19003",
24 24 "CorsOrigins": "http://localhost:19003;http://localhost:18000;http://localhost:5666;http://localhost:5174;http://localhost:5173;http://localhost:3000"
25 25 },
26 26 //配置
27 27 "Settings": {
28 28 "Test": "hello"
29 29 },
30   -
31 30 //数据库类型列表
32 31 "DbList": [ "Sqlite", "Mysql", "Sqlserver", "Oracle", "PostgreSQL" ],
33 32  
... ...