Commit 2a0e4d1da16e175b34660710c65867c37a0d68df

Authored by 李曜臣
1 parent 5d2dea03

2026-07-09优化

Showing 23 changed files with 1533 additions and 38 deletions
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/Dtos/Label/LabelBatchCreateInputVo.cs 0 → 100644
  1 +namespace FoodLabeling.Application.Contracts.Dtos.Label;
  2 +
  3 +/// <summary>
  4 +/// 标签批量导入入参(同一模板多行)
  5 +/// </summary>
  6 +public class LabelBatchCreateInputVo
  7 +{
  8 + /// <summary>模板编码(所有行共用)</summary>
  9 + public string TemplateCode { get; set; } = string.Empty;
  10 +
  11 + /// <summary>导入行列表</summary>
  12 + public List<LabelBatchCreateItemInputVo> Items { get; set; } = new();
  13 +
  14 + /// <summary>
  15 + /// 是否将各行模板数据合并写入 <c>fl_label_template_product_default</c>(与 Web 端 Bulk Add 行为一致)
  16 + /// </summary>
  17 + public bool SaveTemplateProductDefaults { get; set; } = true;
  18 +}
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/Dtos/Label/LabelBatchCreateItemInputVo.cs 0 → 100644
  1 +namespace FoodLabeling.Application.Contracts.Dtos.Label;
  2 +
  3 +/// <summary>
  4 +/// 批量导入单行:标签基本字段 + 模板数据字段
  5 +/// </summary>
  6 +public class LabelBatchCreateItemInputVo
  7 +{
  8 + public string? LabelCode { get; set; }
  9 +
  10 + public string LabelName { get; set; } = string.Empty;
  11 +
  12 + public string? PartnerId { get; set; }
  13 +
  14 + public List<string>? PartnerIds { get; set; }
  15 +
  16 + public string? AppliedRegionType { get; set; }
  17 +
  18 + public List<string>? RegionIds { get; set; }
  19 +
  20 + public List<string>? GroupIds { get; set; }
  21 +
  22 + public List<string>? LocationIds { get; set; }
  23 +
  24 + public string? LocationId { get; set; }
  25 +
  26 + public string LabelCategoryId { get; set; } = string.Empty;
  27 +
  28 + public string? LabelTypeId { get; set; }
  29 +
  30 + public List<string> ProductIds { get; set; } = new();
  31 +
  32 + /// <summary>标签级模板数据(落库 <c>fl_label.LabelInfoJson</c>);通常批量导入走模板 ProductDefaults</summary>
  33 + public object? LabelInfoJson { get; set; }
  34 +
  35 + public bool State { get; set; } = true;
  36 +
  37 + /// <summary>
  38 + /// 已组装的模板默认值(elementId → 值)。若传入则优先使用,不再从下方结构化字段推导。
  39 + /// </summary>
  40 + public Dictionary<string, object?>? TemplateDefaultValues { get; set; }
  41 +
  42 + /// <summary>模板文本类录入(elementId → 文本)</summary>
  43 + public Dictionary<string, string>? TemplateDataValues { get; set; }
  44 +
  45 + /// <summary>模板日期/时间/时长录入(elementId → 单位+数值)</summary>
  46 + public Dictionary<string, LabelBatchDateOffsetInputVo>? TemplateDateOffsets { get; set; }
  47 +
  48 + /// <summary>营养成分手动录入(nutritionElementId → 子字段键值)</summary>
  49 + public Dictionary<string, Dictionary<string, string>>? NutritionByElementId { get; set; }
  50 +}
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/Dtos/Label/LabelBatchCreateResultDto.cs 0 → 100644
  1 +namespace FoodLabeling.Application.Contracts.Dtos.Label;
  2 +
  3 +/// <summary>
  4 +/// 标签批量导入结果
  5 +/// </summary>
  6 +public class LabelBatchCreateResultDto
  7 +{
  8 + public int SuccessCount { get; set; }
  9 +
  10 + public int FailCount { get; set; }
  11 +
  12 + public List<LabelBatchCreateErrorDto> Errors { get; set; } = new();
  13 +
  14 + public List<LabelBatchCreateSuccessItemDto> SuccessItems { get; set; } = new();
  15 +}
  16 +
  17 +public class LabelBatchCreateErrorDto
  18 +{
  19 + public int RowNumber { get; set; }
  20 +
  21 + public string? LabelName { get; set; }
  22 +
  23 + public string Message { get; set; } = string.Empty;
  24 +}
  25 +
  26 +public class LabelBatchCreateSuccessItemDto
  27 +{
  28 + public int RowNumber { get; set; }
  29 +
  30 + public string LabelCode { get; set; } = string.Empty;
  31 +
  32 + public string LabelName { get; set; } = string.Empty;
  33 +}
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/Dtos/Label/LabelBatchDateOffsetInputVo.cs 0 → 100644
  1 +namespace FoodLabeling.Application.Contracts.Dtos.Label;
  2 +
  3 +/// <summary>
  4 +/// 批量导入行:模板日期/时间/时长偏移录入(单位 + 数值)
  5 +/// </summary>
  6 +public class LabelBatchDateOffsetInputVo
  7 +{
  8 + /// <summary>偏移单位,如 Days、Hours</summary>
  9 + public string Unit { get; set; } = "Days";
  10 +
  11 + /// <summary>偏移数值</summary>
  12 + public string Value { get; set; } = string.Empty;
  13 +}
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/Dtos/Product/ProductCreateInputVo.cs
@@ -30,6 +30,11 @@ public class ProductCreateInputVo @@ -30,6 +30,11 @@ public class ProductCreateInputVo
30 public bool State { get; set; } = true; 30 public bool State { get; set; } = true;
31 31
32 /// <summary> 32 /// <summary>
  33 + /// 适用门店:ALL / SPECIFIED(ALL 时动态包含后续新增门店,不写快照)
  34 + /// </summary>
  35 + public string? AvailabilityType { get; set; }
  36 +
  37 + /// <summary>
33 /// 适用 Company(<c>fl_partner.Id</c>,UI 称 Company);展开该公司下全部门店后与 Region/门店合并写入 <c>fl_location_product</c> 38 /// 适用 Company(<c>fl_partner.Id</c>,UI 称 Company);展开该公司下全部门店后与 Region/门店合并写入 <c>fl_location_product</c>
34 /// </summary> 39 /// </summary>
35 public string? PartnerId { get; set; } 40 public string? PartnerId { get; set; }
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/Dtos/Product/ProductGetListOutputDto.cs
@@ -24,6 +24,9 @@ public class ProductGetListOutputDto @@ -24,6 +24,9 @@ public class ProductGetListOutputDto
24 24
25 public bool State { get; set; } 25 public bool State { get; set; }
26 26
  27 + /// <summary>适用门店:ALL / SPECIFIED</summary>
  28 + public string AvailabilityType { get; set; } = "SPECIFIED";
  29 +
27 /// <summary> 30 /// <summary>
28 /// 该产品关联的标签数量(fl_label_product + fl_label) 31 /// 该产品关联的标签数量(fl_label_product + fl_label)
29 /// </summary> 32 /// </summary>
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/Dtos/Product/ProductGetOutputDto.cs
@@ -26,6 +26,9 @@ public class ProductGetOutputDto @@ -26,6 +26,9 @@ public class ProductGetOutputDto
26 26
27 public bool State { get; set; } 27 public bool State { get; set; }
28 28
  29 + /// <summary>适用门店:ALL / SPECIFIED</summary>
  30 + public string AvailabilityType { get; set; } = "SPECIFIED";
  31 +
29 /// <summary>适用 Company Id(<c>fl_partner.Id</c>,由关联门店反推;多公司时取第一个)</summary> 32 /// <summary>适用 Company Id(<c>fl_partner.Id</c>,由关联门店反推;多公司时取第一个)</summary>
30 public string? PartnerId { get; set; } 33 public string? PartnerId { get; set; }
31 34
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/IServices/ILabelAppService.cs
@@ -26,6 +26,11 @@ public interface ILabelAppService : IApplicationService @@ -26,6 +26,11 @@ public interface ILabelAppService : IApplicationService
26 Task<LabelGetOutputDto> CreateAsync(LabelCreateInputVo input); 26 Task<LabelGetOutputDto> CreateAsync(LabelCreateInputVo input);
27 27
28 /// <summary> 28 /// <summary>
  29 + /// 批量导入标签(同一模板多行)。每行含标签基本字段与模板数据字段;可选合并写入模板 ProductDefaults。
  30 + /// </summary>
  31 + Task<LabelBatchCreateResultDto> BatchCreateAsync(LabelBatchCreateInputVo input);
  32 +
  33 + /// <summary>
29 /// 编辑标签(id=LabelCode)。适用 Region / 门店字段同 <see cref="CreateAsync"/>。 34 /// 编辑标签(id=LabelCode)。适用 Region / 门店字段同 <see cref="CreateAsync"/>。
30 /// </summary> 35 /// </summary>
31 Task<LabelGetOutputDto> UpdateAsync(string id, LabelUpdateInputVo input); 36 Task<LabelGetOutputDto> UpdateAsync(string id, LabelUpdateInputVo input);
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/AllScopeBindingHelper.cs 0 → 100644
  1 +using FoodLabeling.Application.Services.DbModels;
  2 +using SqlSugar;
  3 +
  4 +namespace FoodLabeling.Application.Helpers;
  5 +
  6 +/// <summary>
  7 +/// 「适用全部 Region/Location/Company」:保存为 ALL(不写关联快照),查询时动态包含后续新增的 Region/Location。
  8 +/// </summary>
  9 +public static class AllScopeBindingHelper
  10 +{
  11 + public const string ScopeAll = "ALL";
  12 + public const string ScopeSpecified = "SPECIFIED";
  13 +
  14 + public const string AllRegionsDisplay = "All Regions";
  15 + public const string AllLocationsDisplay = "All Locations";
  16 + public const string AllCompaniesDisplay = "All Companies";
  17 +
  18 + /// <summary>选中 Id 是否覆盖当前上下文中全部可选项(用于将「全选」规范为 ALL)。</summary>
  19 + public static bool IsFullIdSelection(IReadOnlyList<string> selected, IReadOnlyList<string> universe)
  20 + {
  21 + if (universe.Count == 0)
  22 + {
  23 + return selected.Count == 0;
  24 + }
  25 +
  26 + if (selected.Count != universe.Count)
  27 + {
  28 + return false;
  29 + }
  30 +
  31 + var set = new HashSet<string>(universe, StringComparer.Ordinal);
  32 + return selected.All(id => set.Contains(id));
  33 + }
  34 +
  35 + /// <summary>解析维度类型:显式 ALL、空数组 ALL、或 Id 列表全选时视为 ALL。</summary>
  36 + public static string ResolveDimensionType(
  37 + string? declaredType,
  38 + IReadOnlyList<string> ids,
  39 + bool hasArrayInPayload,
  40 + bool isFullSelection)
  41 + {
  42 + if (isFullSelection || (ids.Count == 0 && IsDeclaredAll(declaredType)))
  43 + {
  44 + return ScopeAll;
  45 + }
  46 +
  47 + if (ids.Count > 0)
  48 + {
  49 + return ScopeSpecified;
  50 + }
  51 +
  52 + if (hasArrayInPayload && IsDeclaredAll(declaredType))
  53 + {
  54 + return ScopeAll;
  55 + }
  56 +
  57 + var normalized = (declaredType ?? ScopeAll).Trim().ToUpperInvariant();
  58 + return normalized == ScopeSpecified ? ScopeSpecified : ScopeAll;
  59 + }
  60 +
  61 + public static bool IsDeclaredAll(string? type) =>
  62 + string.Equals((type ?? ScopeAll).Trim(), ScopeAll, StringComparison.OrdinalIgnoreCase);
  63 +
  64 + /// <summary>全部 Company(<c>fl_partner.Id</c>)。</summary>
  65 + public static async Task<List<string>> ResolveAllPartnerIdsAsync(ISqlSugarClient db)
  66 + {
  67 + var rows = await db.Queryable<FlPartnerDbEntity>()
  68 + .Where(x => !x.IsDeleted)
  69 + .Select(x => x.Id)
  70 + .ToListAsync();
  71 + return LocationScopeBindingHelper.NormalizeIds(rows);
  72 + }
  73 +
  74 + /// <summary>全部 Region;可按 Company 限定。</summary>
  75 + public static async Task<List<string>> ResolveAllRegionIdsAsync(
  76 + ISqlSugarClient db,
  77 + IReadOnlyList<string>? partnerIds)
  78 + {
  79 + var query = db.Queryable<FlGroupDbEntity>().Where(x => !x.IsDeleted);
  80 + var pids = LocationScopeBindingHelper.NormalizeIds(partnerIds);
  81 + if (pids.Count > 0)
  82 + {
  83 + query = query.Where(x => pids.Contains(x.PartnerId));
  84 + }
  85 +
  86 + var rows = await query.Select(x => x.Id).ToListAsync();
  87 + return LocationScopeBindingHelper.NormalizeIds(rows);
  88 + }
  89 +
  90 + /// <summary>全部门店;可按 Company / Region 限定。</summary>
  91 + public static async Task<List<string>> ResolveAllLocationIdsAsync(
  92 + ISqlSugarClient db,
  93 + IReadOnlyList<string>? partnerIds,
  94 + IReadOnlyList<string>? regionIds)
  95 + {
  96 + var merged = await LocationScopeBindingHelper.MergeToLocationIdsAsync(
  97 + db,
  98 + partnerIds,
  99 + regionIds,
  100 + null);
  101 + return LocationScopeBindingHelper.NormalizeIds(merged);
  102 + }
  103 +
  104 + /// <summary>Company 维度是否应存为 ALL(含「勾选了全部 Company」)。</summary>
  105 + public static async Task<(string Type, List<string> Ids)> NormalizePartnerScopeAsync(
  106 + ISqlSugarClient db,
  107 + string? declaredType,
  108 + IReadOnlyList<string>? partnerIds,
  109 + IReadOnlyList<string>? companyIds,
  110 + bool hasArrayInPayload)
  111 + {
  112 + var ids = LabelEntityPartnerScopeHelper.NormalizePartnerIds(partnerIds, companyIds);
  113 + var allPartners = await ResolveAllPartnerIdsAsync(db);
  114 + var isFull = ids.Count > 0 && IsFullIdSelection(ids, allPartners);
  115 + var type = ResolveDimensionType(declaredType, ids, hasArrayInPayload, isFull);
  116 + return (type, type == ScopeSpecified ? ids : new List<string>());
  117 + }
  118 +
  119 + /// <summary>Region 维度是否应存为 ALL。</summary>
  120 + public static async Task<(string Type, List<string> Ids)> NormalizeRegionScopeAsync(
  121 + ISqlSugarClient db,
  122 + string? declaredType,
  123 + IReadOnlyList<string> regionIds,
  124 + bool hasArrayInPayload,
  125 + IReadOnlyList<string>? partnerIdsForContext)
  126 + {
  127 + var ids = LocationScopeBindingHelper.NormalizeIds(regionIds);
  128 + var allRegions = await ResolveAllRegionIdsAsync(db, partnerIdsForContext);
  129 + var isFull = ids.Count > 0 && IsFullIdSelection(ids, allRegions);
  130 + var type = ResolveDimensionType(declaredType, ids, hasArrayInPayload, isFull);
  131 + return (type, type == ScopeSpecified ? ids : new List<string>());
  132 + }
  133 +
  134 + /// <summary>Location 维度是否应存为 ALL。</summary>
  135 + public static async Task<(string Type, List<string> Ids)> NormalizeLocationScopeAsync(
  136 + ISqlSugarClient db,
  137 + string? declaredType,
  138 + IReadOnlyList<string> locationIds,
  139 + bool hasArrayInPayload,
  140 + IReadOnlyList<string>? partnerIdsForContext,
  141 + IReadOnlyList<string>? regionIdsForContext)
  142 + {
  143 + var ids = LocationScopeBindingHelper.NormalizeIds(locationIds);
  144 + var allLocations = await ResolveAllLocationIdsAsync(db, partnerIdsForContext, regionIdsForContext);
  145 + var isFull = ids.Count > 0 && IsFullIdSelection(ids, allLocations);
  146 + var type = ResolveDimensionType(declaredType, ids, hasArrayInPayload, isFull);
  147 + return (type, type == ScopeSpecified ? ids : new List<string>());
  148 + }
  149 +
  150 + /// <summary>
  151 + /// 标签类型/分类/多选项/产品分类:Region+Location 合并后是否应视为 ALL。
  152 + /// </summary>
  153 + public static async Task<bool> ShouldTreatMergedLocationScopeAsAllAsync(
  154 + ISqlSugarClient db,
  155 + string? declaredAvailabilityType,
  156 + IReadOnlyList<string>? regionIds,
  157 + IReadOnlyList<string>? locationIds,
  158 + bool hasScopeArrays,
  159 + IReadOnlyList<string>? partnerIdsForContext)
  160 + {
  161 + if (IsDeclaredAll(declaredAvailabilityType)
  162 + && LocationScopeBindingHelper.NormalizeIds(regionIds).Count == 0
  163 + && LocationScopeBindingHelper.NormalizeIds(locationIds).Count == 0)
  164 + {
  165 + return true;
  166 + }
  167 +
  168 + if (hasScopeArrays
  169 + && LocationScopeBindingHelper.NormalizeIds(regionIds).Count == 0
  170 + && LocationScopeBindingHelper.NormalizeIds(locationIds).Count == 0
  171 + && IsDeclaredAll(declaredAvailabilityType))
  172 + {
  173 + return true;
  174 + }
  175 +
  176 + var merged = await LocationScopeBindingHelper.MergeToLocationIdsAsync(
  177 + db,
  178 + (IReadOnlyList<string>?)null,
  179 + regionIds,
  180 + locationIds);
  181 + if (merged.Count == 0)
  182 + {
  183 + return false;
  184 + }
  185 +
  186 + var allLocations = await ResolveAllLocationIdsAsync(db, partnerIdsForContext, null);
  187 + return IsFullIdSelection(merged, allLocations);
  188 + }
  189 +
  190 + /// <summary>产品门店范围是否应存为 ALL(不写 <c>fl_location_product</c> 快照)。</summary>
  191 + public static async Task<bool> ShouldTreatProductLocationScopeAsAllAsync(
  192 + ISqlSugarClient db,
  193 + string? declaredAvailabilityType,
  194 + string? partnerId,
  195 + IReadOnlyList<string>? groupIds,
  196 + IReadOnlyList<string>? locationIds,
  197 + bool hasScopePayload)
  198 + {
  199 + if (IsDeclaredAll(declaredAvailabilityType)
  200 + && string.IsNullOrWhiteSpace(partnerId)
  201 + && LocationScopeBindingHelper.NormalizeIds(groupIds).Count == 0
  202 + && LocationScopeBindingHelper.NormalizeIds(locationIds).Count == 0)
  203 + {
  204 + return true;
  205 + }
  206 +
  207 + if (!hasScopePayload)
  208 + {
  209 + return false;
  210 + }
  211 +
  212 + var partnerIds = string.IsNullOrWhiteSpace(partnerId)
  213 + ? null
  214 + : new List<string> { partnerId.Trim() };
  215 + var merged = await LocationScopeBindingHelper.MergeToLocationIdsAsync(
  216 + db,
  217 + partnerId,
  218 + groupIds,
  219 + locationIds);
  220 + if (merged.Count == 0)
  221 + {
  222 + return false;
  223 + }
  224 +
  225 + var allLocations = await ResolveAllLocationIdsAsync(db, partnerIds, null);
  226 + return IsFullIdSelection(merged, allLocations);
  227 + }
  228 +}
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/LabelBatchTemplateDefaultsHelper.cs 0 → 100644
  1 +using System.Globalization;
  2 +using System.Text.Json;
  3 +using FoodLabeling.Application.Contracts.Dtos.Label;
  4 +using FoodLabeling.Application.Contracts.Dtos.LabelTemplate;
  5 +using FoodLabeling.Application.Services.DbModels;
  6 +using SqlSugar;
  7 +using Volo.Abp;
  8 +using Volo.Abp.Guids;
  9 +
  10 +namespace FoodLabeling.Application.Helpers;
  11 +
  12 +/// <summary>
  13 +/// 标签批量导入:模板 ProductDefaults 合并与默认值组装
  14 +/// </summary>
  15 +public static class LabelBatchTemplateDefaultsHelper
  16 +{
  17 + private static readonly HashSet<string> DataEntryTypeAddWhitelist = new(StringComparer.OrdinalIgnoreCase)
  18 + {
  19 + "label_label name",
  20 + "label_text",
  21 + "label_qr code",
  22 + "label_barcode",
  23 + "label_price",
  24 + "label_duration date",
  25 + "label_duration time",
  26 + "label_duration",
  27 + "label_image",
  28 + "label_label type",
  29 + "label_how-to",
  30 + "label_expiration alert"
  31 + };
  32 +
  33 + public static async Task<List<LabelTemplateElementDto>> LoadTemplateElementsAsync(
  34 + ISqlSugarClient db,
  35 + string templateDbId)
  36 + {
  37 + var rows = await db.Queryable<FlLabelTemplateElementDbEntity>()
  38 + .Where(x => x.TemplateId == templateDbId)
  39 + .OrderBy(x => x.OrderNum * 1000000 + x.ZIndex)
  40 + .ToListAsync();
  41 +
  42 + return rows.Select(e =>
  43 + {
  44 + object? cfg = null;
  45 + if (!string.IsNullOrWhiteSpace(e.ConfigJson))
  46 + {
  47 + try
  48 + {
  49 + cfg = JsonSerializer.Deserialize<object>(e.ConfigJson);
  50 + }
  51 + catch
  52 + {
  53 + // ignore
  54 + }
  55 + }
  56 +
  57 + return new LabelTemplateElementDto
  58 + {
  59 + Id = e.ElementKey,
  60 + ElementType = e.ElementType,
  61 + TypeAdd = e.TypeAdd,
  62 + ElementName = e.ElementName,
  63 + OrderNum = e.OrderNum,
  64 + ValueSourceType = e.ValueSourceType,
  65 + InputKey = e.InputKey,
  66 + ConfigJson = cfg
  67 + };
  68 + }).ToList();
  69 + }
  70 +
  71 + public static Dictionary<string, object?> CollectDefaultValuesForItem(
  72 + IReadOnlyList<LabelTemplateElementDto> elements,
  73 + LabelBatchCreateItemInputVo item,
  74 + string? productCodeValue,
  75 + string? labelTypeName)
  76 + {
  77 + if (item.TemplateDefaultValues is { Count: > 0 })
  78 + {
  79 + return item.TemplateDefaultValues.ToDictionary(
  80 + x => x.Key,
  81 + x => x.Value,
  82 + StringComparer.OrdinalIgnoreCase);
  83 + }
  84 +
  85 + var textValues = item.TemplateDataValues ?? new Dictionary<string, string>();
  86 + var dateOffsets = item.TemplateDateOffsets ?? new Dictionary<string, LabelBatchDateOffsetInputVo>();
  87 + var nutritionByElementId = item.NutritionByElementId ?? new Dictionary<string, Dictionary<string, string>>();
  88 + var outDict = new Dictionary<string, object?>(StringComparer.OrdinalIgnoreCase);
  89 +
  90 + foreach (var el in elements)
  91 + {
  92 + if (IsDataEntryTableColumnElement(el))
  93 + {
  94 + var id = el.Id;
  95 + if (IsDateTimeDataEntryField(el))
  96 + {
  97 + var pair = dateOffsets.TryGetValue(id, out var offset)
  98 + ? offset
  99 + : new LabelBatchDateOffsetInputVo();
  100 + var unit = string.IsNullOrWhiteSpace(pair.Unit) ? "Days" : pair.Unit.Trim();
  101 + var norm = NormalizeOffsetInput(pair.Value);
  102 + outDict[id] = norm.Kind switch
  103 + {
  104 + OffsetInputKind.Invalid => "",
  105 + OffsetInputKind.Zero => SerializePrintInputOffset(unit, "0"),
  106 + _ => SerializePrintInputOffset(unit, norm.StoreValue ?? "")
  107 + };
  108 + }
  109 + else
  110 + {
  111 + outDict[id] = textValues.TryGetValue(id, out var tv) ? tv : "";
  112 + }
  113 + }
  114 +
  115 + if (IsNutritionElement(el)
  116 + && nutritionByElementId.TryGetValue(el.Id, out var manual)
  117 + && manual.Count > 0)
  118 + {
  119 + var json = JsonSerializer.Serialize(manual);
  120 + if (json != "{}")
  121 + {
  122 + outDict[el.Id] = json;
  123 + }
  124 + }
  125 + }
  126 +
  127 + var codeValue = (productCodeValue ?? "").Trim();
  128 + if (!string.IsNullOrWhiteSpace(codeValue))
  129 + {
  130 + foreach (var el in elements)
  131 + {
  132 + if (IsTemplateSectionBarcodeOrQrElement(el))
  133 + {
  134 + outDict[el.Id] = codeValue;
  135 + }
  136 + }
  137 + }
  138 +
  139 + var labelName = (item.LabelName ?? "").Trim();
  140 + if (!string.IsNullOrWhiteSpace(labelName))
  141 + {
  142 + foreach (var el in elements)
  143 + {
  144 + if (IsTemplateLabelNameElement(el))
  145 + {
  146 + outDict[el.Id] = labelName;
  147 + }
  148 + }
  149 + }
  150 +
  151 + var typeName = (labelTypeName ?? "").Trim();
  152 + if (!string.IsNullOrWhiteSpace(typeName))
  153 + {
  154 + foreach (var el in elements)
  155 + {
  156 + if (IsTemplateLabelTypeElement(el))
  157 + {
  158 + outDict[el.Id] = typeName;
  159 + }
  160 + }
  161 + }
  162 +
  163 + return outDict;
  164 + }
  165 +
  166 + public static bool HasTemplateDataInput(LabelBatchCreateItemInputVo item) =>
  167 + item.TemplateDefaultValues is { Count: > 0 }
  168 + || item.TemplateDataValues is { Count: > 0 }
  169 + || item.TemplateDateOffsets is { Count: > 0 }
  170 + || item.NutritionByElementId is { Count: > 0 };
  171 +
  172 + public static async Task MergeAndSaveTemplateProductDefaultsAsync(
  173 + ISqlSugarClient db,
  174 + IGuidGenerator guidGenerator,
  175 + string templateDbId,
  176 + IReadOnlyList<LabelTemplateProductDefaultDto> existingDefaults,
  177 + IReadOnlyList<(string ProductId, string LabelTypeId, Dictionary<string, object?> DefaultValues)> newRows)
  178 + {
  179 + var map = new Dictionary<string, LabelTemplateProductDefaultDto>(StringComparer.OrdinalIgnoreCase);
  180 + foreach (var row in existingDefaults)
  181 + {
  182 + var productId = row.ProductId?.Trim();
  183 + var labelTypeId = row.LabelTypeId?.Trim();
  184 + if (string.IsNullOrWhiteSpace(productId) || string.IsNullOrWhiteSpace(labelTypeId))
  185 + {
  186 + continue;
  187 + }
  188 +
  189 + map[$"{productId}::{labelTypeId}"] = row;
  190 + }
  191 +
  192 + foreach (var (productId, labelTypeId, defaultValues) in newRows)
  193 + {
  194 + var pid = productId.Trim();
  195 + var ltid = labelTypeId.Trim();
  196 + if (string.IsNullOrWhiteSpace(pid) || string.IsNullOrWhiteSpace(ltid) || defaultValues.Count == 0)
  197 + {
  198 + continue;
  199 + }
  200 +
  201 + map[$"{pid}::{ltid}"] = new LabelTemplateProductDefaultDto
  202 + {
  203 + ProductId = pid,
  204 + LabelTypeId = ltid,
  205 + DefaultValues = defaultValues,
  206 + OrderNum = map.Count + 1
  207 + };
  208 + }
  209 +
  210 + var merged = map.Values
  211 + .Select((x, idx) =>
  212 + {
  213 + x.OrderNum = idx + 1;
  214 + return x;
  215 + })
  216 + .ToList();
  217 +
  218 + var duplicateCheckSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
  219 + foreach (var row in merged)
  220 + {
  221 + var key = $"{row.ProductId}::{row.LabelTypeId}";
  222 + if (!duplicateCheckSet.Add(key))
  223 + {
  224 + throw new UserFriendlyException(
  225 + $"模板默认值绑定重复:产品[{row.ProductId}]与标签类型[{row.LabelTypeId}]只能存在一条");
  226 + }
  227 + }
  228 +
  229 + await db.Deleteable<FlLabelTemplateProductDefaultDbEntity>()
  230 + .Where(x => x.TemplateId == templateDbId)
  231 + .ExecuteCommandAsync();
  232 +
  233 + if (merged.Count == 0)
  234 + {
  235 + return;
  236 + }
  237 +
  238 + var rows = merged.Select(x => new FlLabelTemplateProductDefaultDbEntity
  239 + {
  240 + Id = guidGenerator.Create().ToString(),
  241 + TemplateId = templateDbId,
  242 + ProductId = x.ProductId,
  243 + LabelTypeId = x.LabelTypeId,
  244 + DefaultValuesJson = x.DefaultValues is null ? null : JsonSerializer.Serialize(x.DefaultValues),
  245 + OrderNum = x.OrderNum
  246 + }).ToList();
  247 +
  248 + await db.Insertable(rows).ExecuteCommandAsync();
  249 + }
  250 +
  251 + private enum OffsetInputKind
  252 + {
  253 + Invalid,
  254 + Zero,
  255 + Amount
  256 + }
  257 +
  258 + private sealed class OffsetInputNormalizeResult
  259 + {
  260 + public OffsetInputKind Kind { get; init; }
  261 +
  262 + public string? StoreValue { get; init; }
  263 + }
  264 +
  265 + private static OffsetInputNormalizeResult NormalizeOffsetInput(string? raw)
  266 + {
  267 + var t = (raw ?? "").Trim();
  268 + if (t.Length == 0)
  269 + {
  270 + return new OffsetInputNormalizeResult { Kind = OffsetInputKind.Zero };
  271 + }
  272 +
  273 + if (!decimal.TryParse(t, NumberStyles.Number, CultureInfo.InvariantCulture, out var n)
  274 + && !decimal.TryParse(t, NumberStyles.Number, CultureInfo.CurrentCulture, out n))
  275 + {
  276 + return new OffsetInputNormalizeResult { Kind = OffsetInputKind.Invalid };
  277 + }
  278 +
  279 + if (n == 0)
  280 + {
  281 + return new OffsetInputNormalizeResult { Kind = OffsetInputKind.Zero };
  282 + }
  283 +
  284 + return new OffsetInputNormalizeResult { Kind = OffsetInputKind.Amount, StoreValue = t };
  285 + }
  286 +
  287 + private static string SerializePrintInputOffset(string unit, string value) =>
  288 + JsonSerializer.Serialize(new { unit, value });
  289 +
  290 + private static string CanonicalElementType(string? elementType) =>
  291 + (elementType ?? "").Trim().ToUpperInvariant();
  292 +
  293 + private static string NormalizeTypeAdd(string? typeAdd) =>
  294 + (typeAdd ?? "").Trim().ToLowerInvariant().Replace(" ", " ", StringComparison.Ordinal);
  295 +
  296 + private static bool IsTemplateSectionPersistedType(LabelTemplateElementDto el) =>
  297 + NormalizeTypeAdd(el.TypeAdd).StartsWith("template_", StringComparison.Ordinal);
  298 +
  299 + private static bool IsDataEntryTableColumnElement(LabelTemplateElementDto el)
  300 + {
  301 + var typeAdd = NormalizeTypeAdd(el.TypeAdd);
  302 + if (typeAdd.StartsWith("template_", StringComparison.Ordinal))
  303 + {
  304 + return false;
  305 + }
  306 +
  307 + if (CanonicalElementType(el.ElementType) == "BLANK")
  308 + {
  309 + return false;
  310 + }
  311 +
  312 + if (!DataEntryTypeAddWhitelist.Contains(typeAdd))
  313 + {
  314 + return false;
  315 + }
  316 +
  317 + var vst = (el.ValueSourceType ?? "FIXED").Trim().ToUpperInvariant();
  318 + return vst is "FIXED" or "PRINT_INPUT";
  319 + }
  320 +
  321 + private static bool IsDateTimeDataEntryField(LabelTemplateElementDto el)
  322 + {
  323 + var type = CanonicalElementType(el.ElementType);
  324 + if (type is "TIME" or "DURATION")
  325 + {
  326 + return true;
  327 + }
  328 +
  329 + if (type != "DATE")
  330 + {
  331 + return false;
  332 + }
  333 +
  334 + var cfg = ParseConfigDict(el.ConfigJson);
  335 + var inputType = GetConfigString(cfg, "inputType", "InputType").ToLowerInvariant();
  336 + if (inputType is "datetime" or "date")
  337 + {
  338 + return true;
  339 + }
  340 +
  341 + var typeAdd = NormalizeTypeAdd(el.TypeAdd);
  342 + if (typeAdd is "label_duration date" || typeAdd.Contains("duration date", StringComparison.Ordinal))
  343 + {
  344 + return true;
  345 + }
  346 +
  347 + var nameHint = $"{el.ElementName} {el.InputKey}".ToLowerInvariant();
  348 + return nameHint.Contains("durationdate", StringComparison.Ordinal)
  349 + || nameHint.Contains("duration_date", StringComparison.Ordinal)
  350 + || nameHint.Contains("duration date", StringComparison.Ordinal);
  351 + }
  352 +
  353 + private static bool IsNutritionElement(LabelTemplateElementDto el) =>
  354 + CanonicalElementType(el.ElementType) == "NUTRITION";
  355 +
  356 + private static bool IsTemplateSectionBarcodeOrQrElement(LabelTemplateElementDto el)
  357 + {
  358 + if (!IsTemplateSectionPersistedType(el))
  359 + {
  360 + return false;
  361 + }
  362 +
  363 + var t = CanonicalElementType(el.ElementType);
  364 + return t is "BARCODE" or "QRCODE";
  365 + }
  366 +
  367 + private static bool IsTemplateLabelNameElement(LabelTemplateElementDto el) =>
  368 + !IsTemplateSectionPersistedType(el) && NormalizeTypeAdd(el.TypeAdd) == "label_label name";
  369 +
  370 + private static bool IsTemplateLabelTypeElement(LabelTemplateElementDto el) =>
  371 + !IsTemplateSectionPersistedType(el) && NormalizeTypeAdd(el.TypeAdd) == "label_label type";
  372 +
  373 + private static Dictionary<string, object?> ParseConfigDict(object? configJson)
  374 + {
  375 + if (configJson is null)
  376 + {
  377 + return new Dictionary<string, object?>(StringComparer.OrdinalIgnoreCase);
  378 + }
  379 +
  380 + if (configJson is Dictionary<string, object?> dict)
  381 + {
  382 + return dict;
  383 + }
  384 +
  385 + if (configJson is JsonElement je && je.ValueKind == JsonValueKind.Object)
  386 + {
  387 + var outDict = new Dictionary<string, object?>(StringComparer.OrdinalIgnoreCase);
  388 + foreach (var prop in je.EnumerateObject())
  389 + {
  390 + outDict[prop.Name] = prop.Value;
  391 + }
  392 +
  393 + return outDict;
  394 + }
  395 +
  396 + try
  397 + {
  398 + return JsonSerializer.Deserialize<Dictionary<string, object?>>(JsonSerializer.Serialize(configJson))
  399 + ?? new Dictionary<string, object?>(StringComparer.OrdinalIgnoreCase);
  400 + }
  401 + catch
  402 + {
  403 + return new Dictionary<string, object?>(StringComparer.OrdinalIgnoreCase);
  404 + }
  405 + }
  406 +
  407 + private static string GetConfigString(IReadOnlyDictionary<string, object?> cfg, params string[] keys)
  408 + {
  409 + foreach (var key in keys)
  410 + {
  411 + if (!cfg.TryGetValue(key, out var val) || val is null)
  412 + {
  413 + continue;
  414 + }
  415 +
  416 + if (val is JsonElement je)
  417 + {
  418 + return je.ValueKind == JsonValueKind.String ? je.GetString() ?? "" : je.ToString();
  419 + }
  420 +
  421 + return val.ToString() ?? "";
  422 + }
  423 +
  424 + return "";
  425 + }
  426 +}
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/LabelEntityPartnerScopeHelper.cs
@@ -112,10 +112,13 @@ public static class LabelEntityPartnerScopeHelper @@ -112,10 +112,13 @@ public static class LabelEntityPartnerScopeHelper
112 IReadOnlyList<string>? companyIds) 112 IReadOnlyList<string>? companyIds)
113 { 113 {
114 var normalizedPartnerIds = NormalizePartnerIds(partnerIds, companyIds); 114 var normalizedPartnerIds = NormalizePartnerIds(partnerIds, companyIds);
115 - var partnerType = ResolveAppliedPartnerType( 115 + var (partnerType, partnerIdsForSave) = await AllScopeBindingHelper.NormalizePartnerScopeAsync(
  116 + db,
116 appliedPartnerType, 117 appliedPartnerType,
117 - normalizedPartnerIds, 118 + partnerIds,
  119 + companyIds,
118 partnerIds is not null || companyIds is not null); 120 partnerIds is not null || companyIds is not null);
  121 + normalizedPartnerIds = partnerIdsForSave;
119 122
120 ValidatePartnerType(partnerType); 123 ValidatePartnerType(partnerType);
121 124
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/LabelTemplateScopeHelper.cs
@@ -67,18 +67,34 @@ public static class LabelTemplateScopeHelper @@ -67,18 +67,34 @@ public static class LabelTemplateScopeHelper
67 var regionIds = NormalizeRegionIds(input); 67 var regionIds = NormalizeRegionIds(input);
68 var locationIds = MergeExplicitLocationIds(input); 68 var locationIds = MergeExplicitLocationIds(input);
69 69
70 - var partnerType = ResolveDimensionType( 70 + var (partnerType, partnerIdsForSave) = await AllScopeBindingHelper.NormalizePartnerScopeAsync(
  71 + db,
71 input.AppliedPartnerType, 72 input.AppliedPartnerType,
72 partnerIds, 73 partnerIds,
  74 + null,
73 input.PartnerIds is not null || input.CompanyIds is not null); 75 input.PartnerIds is not null || input.CompanyIds is not null);
74 - var regionType = ResolveDimensionType( 76 + partnerIds = partnerIdsForSave;
  77 +
  78 + var partnerContext = string.Equals(partnerType, ScopeSpecified, StringComparison.OrdinalIgnoreCase)
  79 + ? partnerIds
  80 + : null;
  81 +
  82 + var (regionType, regionIdsForSave) = await AllScopeBindingHelper.NormalizeRegionScopeAsync(
  83 + db,
75 input.AppliedRegionType, 84 input.AppliedRegionType,
76 regionIds, 85 regionIds,
77 - input.RegionIds is not null || input.GroupIds is not null);  
78 - var locationType = ResolveDimensionType( 86 + input.RegionIds is not null || input.GroupIds is not null,
  87 + partnerContext);
  88 + regionIds = regionIdsForSave;
  89 +
  90 + var (locationType, locationIdsForSave) = await AllScopeBindingHelper.NormalizeLocationScopeAsync(
  91 + db,
79 input.AppliedLocationType, 92 input.AppliedLocationType,
80 locationIds, 93 locationIds,
81 - input.LocationIds is not null || input.AppliedLocationIds is not null); 94 + input.LocationIds is not null || input.AppliedLocationIds is not null,
  95 + partnerContext,
  96 + string.Equals(regionType, ScopeSpecified, StringComparison.OrdinalIgnoreCase) ? regionIds : null);
  97 + locationIds = locationIdsForSave;
82 98
83 ValidateDimensionType("Company", partnerType); 99 ValidateDimensionType("Company", partnerType);
84 ValidateDimensionType("Region", regionType); 100 ValidateDimensionType("Region", regionType);
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/ProductScopeSchemaHelper.cs 0 → 100644
  1 +using SqlSugar;
  2 +
  3 +namespace FoodLabeling.Application.Helpers;
  4 +
  5 +/// <summary>
  6 +/// 探测 <c>fl_product.AvailabilityType</c> 列是否已迁移。
  7 +/// </summary>
  8 +public static class ProductScopeSchemaHelper
  9 +{
  10 + private static bool? _hasAvailabilityTypeColumn;
  11 +
  12 + public static async Task<bool> HasAvailabilityTypeColumnAsync(ISqlSugarClient db)
  13 + {
  14 + if (_hasAvailabilityTypeColumn is not null)
  15 + {
  16 + return _hasAvailabilityTypeColumn.Value;
  17 + }
  18 +
  19 + try
  20 + {
  21 + var count = await db.Ado.GetIntAsync(
  22 + """
  23 + SELECT COUNT(*)
  24 + FROM information_schema.COLUMNS
  25 + WHERE TABLE_SCHEMA = DATABASE()
  26 + AND TABLE_NAME = 'fl_product'
  27 + AND COLUMN_NAME = 'AvailabilityType'
  28 + """);
  29 + _hasAvailabilityTypeColumn = count > 0;
  30 + }
  31 + catch
  32 + {
  33 + _hasAvailabilityTypeColumn = false;
  34 + }
  35 +
  36 + return _hasAvailabilityTypeColumn.Value;
  37 + }
  38 +
  39 + public static void ResetCacheForTests() => _hasAvailabilityTypeColumn = null;
  40 +}
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/DbModels/FlProductDbEntity.cs
@@ -31,4 +31,9 @@ public class FlProductDbEntity @@ -31,4 +31,9 @@ public class FlProductDbEntity
31 public string? CategoryPhotoUrl { get; set; } 31 public string? CategoryPhotoUrl { get; set; }
32 32
33 public bool State { get; set; } 33 public bool State { get; set; }
  34 +
  35 + /// <summary>
  36 + /// 适用门店:ALL / SPECIFIED(ALL 时动态包含后续新增门店)
  37 + /// </summary>
  38 + public string AvailabilityType { get; set; } = "SPECIFIED";
34 } 39 }
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/LabelAppService.cs
@@ -460,6 +460,201 @@ public class LabelAppService : ApplicationService, ILabelAppService @@ -460,6 +460,201 @@ public class LabelAppService : ApplicationService, ILabelAppService
460 return await GetAsync(labelCode); 460 return await GetAsync(labelCode);
461 } 461 }
462 462
  463 + /// <summary>
  464 + /// 批量导入标签(同一模板多行)
  465 + /// </summary>
  466 + /// <remarks>
  467 + /// 用于 Web 端 Bulk Add Labels:一次提交多行标签基本字段(门店、分类、类型、产品等)与模板数据字段(文本、日期偏移、条码等)。
  468 + ///
  469 + /// 示例请求:
  470 + /// ```json
  471 + /// {
  472 + /// "templateCode": "TPL_NUTRITION_3X6",
  473 + /// "saveTemplateProductDefaults": true,
  474 + /// "items": [
  475 + /// {
  476 + /// "labelName": "Chicken Salad",
  477 + /// "labelCategoryId": "cat-id",
  478 + /// "labelTypeId": "type-id",
  479 + /// "locationIds": ["location-id"],
  480 + /// "productIds": ["product-id"],
  481 + /// "appliedRegionType": "SPECIFIED",
  482 + /// "regionIds": ["group-id"],
  483 + /// "templateDataValues": { "el-text": "Fresh" },
  484 + /// "templateDateOffsets": { "el-duration": { "unit": "Days", "value": "3" } }
  485 + /// }
  486 + /// ]
  487 + /// }
  488 + /// ```
  489 + ///
  490 + /// 参数说明:
  491 + /// - templateCode: 所有行共用的模板编码
  492 + /// - items: 导入行;字段与单条创建基本一致,另支持 templateDefaultValues / templateDataValues / templateDateOffsets / nutritionByElementId
  493 + /// - saveTemplateProductDefaults: 是否将各行模板数据合并写入 fl_label_template_product_default
  494 + /// </remarks>
  495 + /// <param name="input">批量导入入参</param>
  496 + /// <returns>成功/失败统计与行级错误</returns>
  497 + /// <response code="200">导入完成(可能部分成功)</response>
  498 + /// <response code="400">入参非法或模板不存在</response>
  499 + /// <response code="500">服务器错误</response>
  500 + [UnitOfWork]
  501 + public async Task<LabelBatchCreateResultDto> BatchCreateAsync(LabelBatchCreateInputVo input)
  502 + {
  503 + if (input?.Items is null || input.Items.Count == 0)
  504 + {
  505 + throw new UserFriendlyException("批量导入行不能为空");
  506 + }
  507 +
  508 + const int maxRows = 500;
  509 + if (input.Items.Count > maxRows)
  510 + {
  511 + throw new UserFriendlyException($"单次最多导入 {maxRows} 行");
  512 + }
  513 +
  514 + var templateCode = input.TemplateCode?.Trim();
  515 + if (string.IsNullOrWhiteSpace(templateCode))
  516 + {
  517 + throw new UserFriendlyException("模板编码不能为空");
  518 + }
  519 +
  520 + var db = _dbContext.SqlSugarClient;
  521 + var template = await LabelTemplateQueryHelper.QueryProjected(db)
  522 + .FirstAsync(x => !x.IsDeleted && x.TemplateCode == templateCode);
  523 + if (template is null)
  524 + {
  525 + throw new UserFriendlyException("模板不存在");
  526 + }
  527 +
  528 + var templateElements = await LabelBatchTemplateDefaultsHelper.LoadTemplateElementsAsync(db, template.Id);
  529 + var existingDefaults = await db.Queryable<FlLabelTemplateProductDefaultDbEntity>()
  530 + .Where(x => x.TemplateId == template.Id)
  531 + .OrderBy(x => x.OrderNum)
  532 + .ToListAsync();
  533 + var existingDefaultDtos = existingDefaults.Select(x =>
  534 + {
  535 + object? defaults = null;
  536 + if (!string.IsNullOrWhiteSpace(x.DefaultValuesJson))
  537 + {
  538 + defaults = JsonSerializer.Deserialize<object>(x.DefaultValuesJson);
  539 + }
  540 +
  541 + return new LabelTemplateProductDefaultDto
  542 + {
  543 + ProductId = x.ProductId,
  544 + LabelTypeId = x.LabelTypeId,
  545 + DefaultValues = defaults,
  546 + OrderNum = x.OrderNum
  547 + };
  548 + }).ToList();
  549 +
  550 + var result = new LabelBatchCreateResultDto();
  551 + var templateDefaultRows = new List<(string ProductId, string LabelTypeId, Dictionary<string, object?> DefaultValues)>();
  552 +
  553 + for (var i = 0; i < input.Items.Count; i++)
  554 + {
  555 + var rowNumber = i + 1;
  556 + var item = input.Items[i];
  557 + try
  558 + {
  559 + var createInput = MapBatchItemToCreateInput(item, templateCode);
  560 + var created = await CreateAsync(createInput);
  561 + result.SuccessCount++;
  562 + result.SuccessItems.Add(new LabelBatchCreateSuccessItemDto
  563 + {
  564 + RowNumber = rowNumber,
  565 + LabelCode = created.Id,
  566 + LabelName = created.LabelName
  567 + });
  568 +
  569 + if (!input.SaveTemplateProductDefaults || !LabelBatchTemplateDefaultsHelper.HasTemplateDataInput(item))
  570 + {
  571 + continue;
  572 + }
  573 +
  574 + var productId = item.ProductIds?.FirstOrDefault(x => !string.IsNullOrWhiteSpace(x))?.Trim();
  575 + var labelTypeId = NormalizeOptionalLabelTypeId(item.LabelTypeId);
  576 + if (string.IsNullOrWhiteSpace(productId) || string.IsNullOrWhiteSpace(labelTypeId))
  577 + {
  578 + continue;
  579 + }
  580 +
  581 + var product = await db.Queryable<FlProductDbEntity>()
  582 + .FirstAsync(x => !x.IsDeleted && x.Id == productId);
  583 + var labelType = await db.Queryable<FlLabelTypeDbEntity>()
  584 + .FirstAsync(x => !x.IsDeleted && x.Id == labelTypeId);
  585 + var codeValue = string.IsNullOrWhiteSpace(product?.CodeValue)
  586 + ? product?.ProductCode
  587 + : product!.CodeValue;
  588 + var defaultValues = LabelBatchTemplateDefaultsHelper.CollectDefaultValuesForItem(
  589 + templateElements,
  590 + item,
  591 + codeValue,
  592 + labelType?.TypeName);
  593 + if (defaultValues.Count > 0)
  594 + {
  595 + templateDefaultRows.Add((productId, labelTypeId, defaultValues));
  596 + }
  597 + }
  598 + catch (UserFriendlyException ex)
  599 + {
  600 + result.FailCount++;
  601 + result.Errors.Add(new LabelBatchCreateErrorDto
  602 + {
  603 + RowNumber = rowNumber,
  604 + LabelName = item.LabelName,
  605 + Message = ex.Message
  606 + });
  607 + }
  608 + }
  609 +
  610 + if (input.SaveTemplateProductDefaults && templateDefaultRows.Count > 0)
  611 + {
  612 + try
  613 + {
  614 + await LabelBatchTemplateDefaultsHelper.MergeAndSaveTemplateProductDefaultsAsync(
  615 + db,
  616 + _guidGenerator,
  617 + template.Id,
  618 + existingDefaultDtos,
  619 + templateDefaultRows);
  620 + }
  621 + catch (UserFriendlyException ex)
  622 + {
  623 + result.Errors.Add(new LabelBatchCreateErrorDto
  624 + {
  625 + RowNumber = 0,
  626 + Message = $"标签已创建,但模板默认值保存失败:{ex.Message}"
  627 + });
  628 + }
  629 + }
  630 +
  631 + return result;
  632 + }
  633 +
  634 + private static LabelCreateInputVo MapBatchItemToCreateInput(
  635 + LabelBatchCreateItemInputVo item,
  636 + string templateCode)
  637 + {
  638 + return new LabelCreateInputVo
  639 + {
  640 + LabelCode = item.LabelCode,
  641 + LabelName = item.LabelName,
  642 + TemplateCode = templateCode,
  643 + PartnerId = item.PartnerId,
  644 + PartnerIds = item.PartnerIds,
  645 + AppliedRegionType = item.AppliedRegionType,
  646 + RegionIds = item.RegionIds,
  647 + GroupIds = item.GroupIds,
  648 + LocationIds = item.LocationIds,
  649 + LocationId = item.LocationId,
  650 + LabelCategoryId = item.LabelCategoryId,
  651 + LabelTypeId = item.LabelTypeId,
  652 + ProductIds = item.ProductIds ?? new List<string>(),
  653 + LabelInfoJson = item.LabelInfoJson,
  654 + State = item.State
  655 + };
  656 + }
  657 +
463 [UnitOfWork] 658 [UnitOfWork]
464 public async Task<LabelGetOutputDto> UpdateAsync(string id, LabelUpdateInputVo input) 659 public async Task<LabelGetOutputDto> UpdateAsync(string id, LabelUpdateInputVo input)
465 { 660 {
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/LabelCategoryAppService.cs
@@ -290,14 +290,32 @@ public class LabelCategoryAppService : ApplicationService, ILabelCategoryAppServ @@ -290,14 +290,32 @@ public class LabelCategoryAppService : ApplicationService, ILabelCategoryAppServ
290 290
291 var regionIds = NormalizeRegionIds(input); 291 var regionIds = NormalizeRegionIds(input);
292 var explicitLocationIds = LocationScopeBindingHelper.NormalizeIds(input.LocationIds); 292 var explicitLocationIds = LocationScopeBindingHelper.NormalizeIds(input.LocationIds);
293 - var availabilityType = (input.AvailabilityType ?? "ALL").Trim().ToUpperInvariant();  
294 -  
295 var hasScopeArrays = input.RegionIds is not null || input.GroupIds is not null || input.LocationIds is not null; 293 var hasScopeArrays = input.RegionIds is not null || input.GroupIds is not null || input.LocationIds is not null;
  294 +
  295 + var partnerContext = string.Equals(
  296 + partnerScope.AppliedPartnerType,
  297 + LabelEntityPartnerScopeHelper.ScopeSpecified,
  298 + StringComparison.OrdinalIgnoreCase)
  299 + ? partnerScope.PartnerIds
  300 + : null;
  301 +
  302 + if (await AllScopeBindingHelper.ShouldTreatMergedLocationScopeAsAllAsync(
  303 + _dbContext.SqlSugarClient,
  304 + input.AvailabilityType,
  305 + regionIds,
  306 + explicitLocationIds,
  307 + hasScopeArrays,
  308 + partnerContext))
  309 + {
  310 + return (partnerScope, "ALL", new List<string>());
  311 + }
  312 +
  313 + var availabilityType = (input.AvailabilityType ?? "ALL").Trim().ToUpperInvariant();
296 if (regionIds.Count > 0 || explicitLocationIds.Count > 0) 314 if (regionIds.Count > 0 || explicitLocationIds.Count > 0)
297 { 315 {
298 availabilityType = "SPECIFIED"; 316 availabilityType = "SPECIFIED";
299 } 317 }
300 - else if (hasScopeArrays && string.Equals(availabilityType, "ALL", StringComparison.OrdinalIgnoreCase)) 318 + else if (hasScopeArrays && AllScopeBindingHelper.IsDeclaredAll(availabilityType))
301 { 319 {
302 availabilityType = "ALL"; 320 availabilityType = "ALL";
303 } 321 }
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/LabelMultipleOptionAppService.cs
@@ -237,14 +237,32 @@ public class LabelMultipleOptionAppService : ApplicationService, ILabelMultipleO @@ -237,14 +237,32 @@ public class LabelMultipleOptionAppService : ApplicationService, ILabelMultipleO
237 237
238 var regionIds = NormalizeRegionIds(input); 238 var regionIds = NormalizeRegionIds(input);
239 var explicitLocationIds = LocationScopeBindingHelper.NormalizeIds(input.LocationIds); 239 var explicitLocationIds = LocationScopeBindingHelper.NormalizeIds(input.LocationIds);
240 - var availabilityType = (input.AvailabilityType ?? "ALL").Trim().ToUpperInvariant();  
241 -  
242 var hasScopeArrays = input.RegionIds is not null || input.GroupIds is not null || input.LocationIds is not null; 240 var hasScopeArrays = input.RegionIds is not null || input.GroupIds is not null || input.LocationIds is not null;
  241 +
  242 + var partnerContext = string.Equals(
  243 + partnerScope.AppliedPartnerType,
  244 + LabelEntityPartnerScopeHelper.ScopeSpecified,
  245 + StringComparison.OrdinalIgnoreCase)
  246 + ? partnerScope.PartnerIds
  247 + : null;
  248 +
  249 + if (await AllScopeBindingHelper.ShouldTreatMergedLocationScopeAsAllAsync(
  250 + _dbContext.SqlSugarClient,
  251 + input.AvailabilityType,
  252 + regionIds,
  253 + explicitLocationIds,
  254 + hasScopeArrays,
  255 + partnerContext))
  256 + {
  257 + return (partnerScope, "ALL", new List<string>());
  258 + }
  259 +
  260 + var availabilityType = (input.AvailabilityType ?? "ALL").Trim().ToUpperInvariant();
243 if (regionIds.Count > 0 || explicitLocationIds.Count > 0) 261 if (regionIds.Count > 0 || explicitLocationIds.Count > 0)
244 { 262 {
245 availabilityType = "SPECIFIED"; 263 availabilityType = "SPECIFIED";
246 } 264 }
247 - else if (hasScopeArrays && string.Equals(availabilityType, "ALL", StringComparison.OrdinalIgnoreCase)) 265 + else if (hasScopeArrays && AllScopeBindingHelper.IsDeclaredAll(availabilityType))
248 { 266 {
249 availabilityType = "ALL"; 267 availabilityType = "ALL";
250 } 268 }
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/LabelTypeAppService.cs
@@ -252,14 +252,32 @@ public class LabelTypeAppService : ApplicationService, ILabelTypeAppService @@ -252,14 +252,32 @@ public class LabelTypeAppService : ApplicationService, ILabelTypeAppService
252 252
253 var regionIds = NormalizeRegionIds(input); 253 var regionIds = NormalizeRegionIds(input);
254 var explicitLocationIds = LocationScopeBindingHelper.NormalizeIds(input.LocationIds); 254 var explicitLocationIds = LocationScopeBindingHelper.NormalizeIds(input.LocationIds);
255 - var availabilityType = (input.AvailabilityType ?? "ALL").Trim().ToUpperInvariant();  
256 -  
257 var hasScopeArrays = input.RegionIds is not null || input.GroupIds is not null || input.LocationIds is not null; 255 var hasScopeArrays = input.RegionIds is not null || input.GroupIds is not null || input.LocationIds is not null;
  256 +
  257 + var partnerContext = string.Equals(
  258 + partnerScope.AppliedPartnerType,
  259 + LabelEntityPartnerScopeHelper.ScopeSpecified,
  260 + StringComparison.OrdinalIgnoreCase)
  261 + ? partnerScope.PartnerIds
  262 + : null;
  263 +
  264 + if (await AllScopeBindingHelper.ShouldTreatMergedLocationScopeAsAllAsync(
  265 + _dbContext.SqlSugarClient,
  266 + input.AvailabilityType,
  267 + regionIds,
  268 + explicitLocationIds,
  269 + hasScopeArrays,
  270 + partnerContext))
  271 + {
  272 + return (partnerScope, "ALL", new List<string>());
  273 + }
  274 +
  275 + var availabilityType = (input.AvailabilityType ?? "ALL").Trim().ToUpperInvariant();
258 if (regionIds.Count > 0 || explicitLocationIds.Count > 0) 276 if (regionIds.Count > 0 || explicitLocationIds.Count > 0)
259 { 277 {
260 availabilityType = "SPECIFIED"; 278 availabilityType = "SPECIFIED";
261 } 279 }
262 - else if (hasScopeArrays && string.Equals(availabilityType, "ALL", StringComparison.OrdinalIgnoreCase)) 280 + else if (hasScopeArrays && AllScopeBindingHelper.IsDeclaredAll(availabilityType))
263 { 281 {
264 availabilityType = "ALL"; 282 availabilityType = "ALL";
265 } 283 }
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/ProductAppService.cs
@@ -97,6 +97,10 @@ public class ProductAppService : ApplicationService, IProductAppService @@ -97,6 +97,10 @@ public class ProductAppService : ApplicationService, IProductAppService
97 97
98 locationIdsByProduct.TryGetValue(x.Id, out var locationIds); 98 locationIdsByProduct.TryGetValue(x.Id, out var locationIds);
99 locationNameByProduct.TryGetValue(x.Id, out var locationName); 99 locationNameByProduct.TryGetValue(x.Id, out var locationName);
  100 + var isAllLocations = string.Equals(
  101 + x.AvailabilityType,
  102 + AllScopeBindingHelper.ScopeAll,
  103 + StringComparison.OrdinalIgnoreCase);
100 104
101 return new ProductGetListOutputDto 105 return new ProductGetListOutputDto
102 { 106 {
@@ -111,9 +115,12 @@ public class ProductAppService : ApplicationService, IProductAppService @@ -111,9 +115,12 @@ public class ProductAppService : ApplicationService, IProductAppService
111 ButtonAppearance = x.ButtonAppearance, 115 ButtonAppearance = x.ButtonAppearance,
112 CategoryPhotoUrl = x.CategoryPhotoUrl, 116 CategoryPhotoUrl = x.CategoryPhotoUrl,
113 State = x.State, 117 State = x.State,
  118 + AvailabilityType = x.AvailabilityType,
114 NoOfLabels = countMap.TryGetValue(x.Id, out var count) ? count : 0, 119 NoOfLabels = countMap.TryGetValue(x.Id, out var count) ? count : 0,
115 - LocationIds = locationIds ?? new List<string>(),  
116 - LocationName = string.IsNullOrWhiteSpace(locationName) ? "无" : locationName! 120 + LocationIds = isAllLocations ? new List<string>() : (locationIds ?? new List<string>()),
  121 + LocationName = isAllLocations
  122 + ? AllScopeBindingHelper.AllLocationsDisplay
  123 + : (string.IsNullOrWhiteSpace(locationName) ? "无" : locationName!)
117 }; 124 };
118 }).ToList(); 125 }).ToList();
119 126
@@ -152,10 +159,18 @@ public class ProductAppService : ApplicationService, IProductAppService @@ -152,10 +159,18 @@ public class ProductAppService : ApplicationService, IProductAppService
152 .Where(x => x.ProductId == productId) 159 .Where(x => x.ProductId == productId)
153 .Select(x => x.LocationId) 160 .Select(x => x.LocationId)
154 .ToListAsync()); 161 .ToListAsync());
155 - var partnerIds = await LocationScopeBindingHelper.ResolvePartnerIdsFromLocationIdsAsync(  
156 - _dbContext.SqlSugarClient, locationIds);  
157 - var groupIds = await LocationScopeBindingHelper.ResolveGroupIdsFromLocationIdsAsync(  
158 - _dbContext.SqlSugarClient, locationIds); 162 + var isAllLocations = string.Equals(
  163 + entity.AvailabilityType,
  164 + AllScopeBindingHelper.ScopeAll,
  165 + StringComparison.OrdinalIgnoreCase);
  166 + var partnerIds = isAllLocations
  167 + ? new List<string>()
  168 + : await LocationScopeBindingHelper.ResolvePartnerIdsFromLocationIdsAsync(
  169 + _dbContext.SqlSugarClient, locationIds);
  170 + var groupIds = isAllLocations
  171 + ? new List<string>()
  172 + : await LocationScopeBindingHelper.ResolveGroupIdsFromLocationIdsAsync(
  173 + _dbContext.SqlSugarClient, locationIds);
159 174
160 return new ProductGetOutputDto 175 return new ProductGetOutputDto
161 { 176 {
@@ -170,10 +185,11 @@ public class ProductAppService : ApplicationService, IProductAppService @@ -170,10 +185,11 @@ public class ProductAppService : ApplicationService, IProductAppService
170 ButtonAppearance = entity.ButtonAppearance, 185 ButtonAppearance = entity.ButtonAppearance,
171 CategoryPhotoUrl = entity.CategoryPhotoUrl, 186 CategoryPhotoUrl = entity.CategoryPhotoUrl,
172 State = entity.State, 187 State = entity.State,
  188 + AvailabilityType = entity.AvailabilityType,
173 PartnerId = partnerIds.Count > 0 ? partnerIds[0] : null, 189 PartnerId = partnerIds.Count > 0 ? partnerIds[0] : null,
174 PartnerIds = partnerIds, 190 PartnerIds = partnerIds,
175 GroupIds = groupIds, 191 GroupIds = groupIds,
176 - LocationIds = locationIds 192 + LocationIds = isAllLocations ? new List<string>() : locationIds
177 }; 193 };
178 } 194 }
179 195
@@ -213,12 +229,14 @@ public class ProductAppService : ApplicationService, IProductAppService @@ -213,12 +229,14 @@ public class ProductAppService : ApplicationService, IProductAppService
213 }; 229 };
214 ApplyProductAppearanceToEntity(entity, input); 230 ApplyProductAppearanceToEntity(entity, input);
215 231
  232 + var (availabilityType, locationIds) = await ResolveProductScopeForSaveAsync(input);
  233 + entity.AvailabilityType = availabilityType;
  234 +
216 await _dbContext.SqlSugarClient.Insertable(entity).ExecuteCommandAsync(); 235 await _dbContext.SqlSugarClient.Insertable(entity).ExecuteCommandAsync();
217 236
218 - if (HasProductScopeBinding(input)) 237 + if (ShouldPersistProductScope(input))
219 { 238 {
220 - var locIds = await ResolveProductLocationIdsForSaveAsync(input);  
221 - await ReplaceProductLocationLinksAsync(entity.Id, locIds); 239 + await ReplaceProductLocationLinksAsync(entity.Id, locationIds);
222 } 240 }
223 241
224 return await GetAsync(Guid.Parse(entity.Id)); 242 return await GetAsync(Guid.Parse(entity.Id));
@@ -270,12 +288,14 @@ public class ProductAppService : ApplicationService, IProductAppService @@ -270,12 +288,14 @@ public class ProductAppService : ApplicationService, IProductAppService
270 entity.State = input.State; 288 entity.State = input.State;
271 ApplyProductAppearanceToEntity(entity, input); 289 ApplyProductAppearanceToEntity(entity, input);
272 290
  291 + var (availabilityType, locationIds) = await ResolveProductScopeForSaveAsync(input);
  292 + entity.AvailabilityType = availabilityType;
  293 +
273 await _dbContext.SqlSugarClient.Updateable(entity).ExecuteCommandAsync(); 294 await _dbContext.SqlSugarClient.Updateable(entity).ExecuteCommandAsync();
274 295
275 - if (HasProductScopeBinding(input)) 296 + if (ShouldPersistProductScope(input))
276 { 297 {
277 - var locIds = await ResolveProductLocationIdsForSaveAsync(input);  
278 - await ReplaceProductLocationLinksAsync(productId, locIds); 298 + await ReplaceProductLocationLinksAsync(productId, locationIds);
279 } 299 }
280 300
281 return await GetAsync(id); 301 return await GetAsync(id);
@@ -517,10 +537,23 @@ public class ProductAppService : ApplicationService, IProductAppService @@ -517,10 +537,23 @@ public class ProductAppService : ApplicationService, IProductAppService
517 } 537 }
518 else 538 else
519 { 539 {
520 - query = query.Where(p =>  
521 - SqlFunc.Subqueryable<FlLocationProductDbEntity>()  
522 - .Where(lp => lp.ProductId == p.Id && locationIds.Contains(lp.LocationId))  
523 - .Any()); 540 + var hasAvailabilityColumn = await ProductScopeSchemaHelper.HasAvailabilityTypeColumnAsync(
  541 + _dbContext.SqlSugarClient);
  542 + if (hasAvailabilityColumn)
  543 + {
  544 + query = query.Where(p =>
  545 + p.AvailabilityType == AllScopeBindingHelper.ScopeAll
  546 + || SqlFunc.Subqueryable<FlLocationProductDbEntity>()
  547 + .Where(lp => lp.ProductId == p.Id && locationIds.Contains(lp.LocationId))
  548 + .Any());
  549 + }
  550 + else
  551 + {
  552 + query = query.Where(p =>
  553 + SqlFunc.Subqueryable<FlLocationProductDbEntity>()
  554 + .Where(lp => lp.ProductId == p.Id && locationIds.Contains(lp.LocationId))
  555 + .Any());
  556 + }
524 } 557 }
525 } 558 }
526 559
@@ -834,6 +867,40 @@ public class ProductAppService : ApplicationService, IProductAppService @@ -834,6 +867,40 @@ public class ProductAppService : ApplicationService, IProductAppService
834 input.GroupIds is not null || 867 input.GroupIds is not null ||
835 input.LocationIds is not null; 868 input.LocationIds is not null;
836 869
  870 + private static bool ShouldPersistProductScope(ProductCreateInputVo input) =>
  871 + HasProductScopeBinding(input) || !string.IsNullOrWhiteSpace(input.AvailabilityType);
  872 +
  873 + /// <summary>
  874 + /// 解析产品门店范围:ALL 时不写 <c>fl_location_product</c> 快照,后续新增门店自动可见。
  875 + /// </summary>
  876 + private async Task<(string AvailabilityType, List<string> LocationIds)> ResolveProductScopeForSaveAsync(
  877 + ProductCreateInputVo input)
  878 + {
  879 + if (!ShouldPersistProductScope(input))
  880 + {
  881 + return (AllScopeBindingHelper.ScopeSpecified, new List<string>());
  882 + }
  883 +
  884 + if (await AllScopeBindingHelper.ShouldTreatProductLocationScopeAsAllAsync(
  885 + _dbContext.SqlSugarClient,
  886 + input.AvailabilityType,
  887 + input.PartnerId,
  888 + input.GroupIds,
  889 + input.LocationIds,
  890 + HasProductScopeBinding(input)))
  891 + {
  892 + return (AllScopeBindingHelper.ScopeAll, new List<string>());
  893 + }
  894 +
  895 + if (!HasProductScopeBinding(input))
  896 + {
  897 + return (AllScopeBindingHelper.ScopeSpecified, new List<string>());
  898 + }
  899 +
  900 + var locIds = await ResolveProductLocationIdsForSaveAsync(input);
  901 + return (AllScopeBindingHelper.ScopeSpecified, locIds);
  902 + }
  903 +
837 /// <summary> 904 /// <summary>
838 /// 合并 Company(partnerId)、Region(groupIds)、门店(locationIds)并校验存在性。 905 /// 合并 Company(partnerId)、Region(groupIds)、门店(locationIds)并校验存在性。
839 /// </summary> 906 /// </summary>
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/ProductCategoryAppService.cs
@@ -272,16 +272,26 @@ public class ProductCategoryAppService : ApplicationService, IProductCategoryApp @@ -272,16 +272,26 @@ public class ProductCategoryAppService : ApplicationService, IProductCategoryApp
272 { 272 {
273 var regionIds = NormalizeRegionIds(input); 273 var regionIds = NormalizeRegionIds(input);
274 var explicitLocationIds = LocationScopeBindingHelper.NormalizeIds(input.LocationIds); 274 var explicitLocationIds = LocationScopeBindingHelper.NormalizeIds(input.LocationIds);
275 - var availabilityType = (input.AvailabilityType ?? "ALL").Trim().ToUpperInvariant();  
276 -  
277 var hasScopeArrays = input.RegionIds is not null || input.GroupIds is not null || input.LocationIds is not null; 275 var hasScopeArrays = input.RegionIds is not null || input.GroupIds is not null || input.LocationIds is not null;
  276 +
  277 + if (await AllScopeBindingHelper.ShouldTreatMergedLocationScopeAsAllAsync(
  278 + _dbContext.SqlSugarClient,
  279 + input.AvailabilityType,
  280 + regionIds,
  281 + explicitLocationIds,
  282 + hasScopeArrays,
  283 + null))
  284 + {
  285 + return ("ALL", new List<string>());
  286 + }
  287 +
  288 + var availabilityType = (input.AvailabilityType ?? "ALL").Trim().ToUpperInvariant();
278 if (regionIds.Count > 0 || explicitLocationIds.Count > 0) 289 if (regionIds.Count > 0 || explicitLocationIds.Count > 0)
279 { 290 {
280 availabilityType = "SPECIFIED"; 291 availabilityType = "SPECIFIED";
281 } 292 }
282 - else if (hasScopeArrays && string.Equals(availabilityType, "ALL", StringComparison.OrdinalIgnoreCase)) 293 + else if (hasScopeArrays && AllScopeBindingHelper.IsDeclaredAll(availabilityType))
283 { 294 {
284 - // 显式传了空数组 [] 表示清空指定范围,仍视为 SPECIFIED(0 门店)或改回 ALL  
285 availabilityType = "ALL"; 295 availabilityType = "ALL";
286 } 296 }
287 297
@@ -343,8 +353,9 @@ public class ProductCategoryAppService : ApplicationService, IProductCategoryApp @@ -343,8 +353,9 @@ public class ProductCategoryAppService : ApplicationService, IProductCategoryApp
343 return query.Where(_ => false); 353 return query.Where(_ => false);
344 } 354 }
345 355
346 - // 非平台管理员:仅返回绑定门店与可见范围有交集的分类(不再因 AvailabilityType=ALL 暴露其它公司数据) 356 + // 非平台管理员:绑定门店与可见范围有交集,或 AvailabilityType=ALL(动态包含后续新增门店)
347 return query.Where(c => 357 return query.Where(c =>
  358 + c.AvailabilityType == "ALL" ||
348 SqlFunc.Subqueryable<FlProductCategoryLocationDbEntity>() 359 SqlFunc.Subqueryable<FlProductCategoryLocationDbEntity>()
349 .Where(cl => cl.CategoryId == c.Id && scopedLocationIds.Contains(cl.LocationId)) 360 .Where(cl => cl.CategoryId == c.Id && scopedLocationIds.Contains(cl.LocationId))
350 .Any()); 361 .Any());
@@ -372,6 +383,11 @@ public class ProductCategoryAppService : ApplicationService, IProductCategoryApp @@ -372,6 +383,11 @@ public class ProductCategoryAppService : ApplicationService, IProductCategoryApp
372 throw new UserFriendlyException("无权访问该类别"); 383 throw new UserFriendlyException("无权访问该类别");
373 } 384 }
374 385
  386 + if (string.Equals(entity.AvailabilityType, "ALL", StringComparison.OrdinalIgnoreCase))
  387 + {
  388 + return;
  389 + }
  390 +
375 var visible = await _dbContext.SqlSugarClient.Queryable<FlProductCategoryLocationDbEntity>() 391 var visible = await _dbContext.SqlSugarClient.Queryable<FlProductCategoryLocationDbEntity>()
376 .AnyAsync(cl => cl.CategoryId == entity.Id && scopedLocationIds.Contains(cl.LocationId)); 392 .AnyAsync(cl => cl.CategoryId == entity.Id && scopedLocationIds.Contains(cl.LocationId));
377 if (!visible) 393 if (!visible)
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/UsAppLabelingAppService.cs
@@ -78,6 +78,18 @@ public class UsAppLabelingAppService : ApplicationService, IUsAppLabelingAppServ @@ -78,6 +78,18 @@ public class UsAppLabelingAppService : ApplicationService, IUsAppLabelingAppServ
78 .Select(x => x.ProductId) 78 .Select(x => x.ProductId)
79 .ToListAsync(); 79 .ToListAsync();
80 80
  81 + if (await ProductScopeSchemaHelper.HasAvailabilityTypeColumnAsync(_dbContext.SqlSugarClient))
  82 + {
  83 + var allScopeProductIds = await _dbContext.SqlSugarClient.Queryable<FlProductDbEntity>()
  84 + .Where(x => !x.IsDeleted && x.State && x.AvailabilityType == AllScopeBindingHelper.ScopeAll)
  85 + .Select(x => x.Id)
  86 + .ToListAsync();
  87 + productIds = productIds
  88 + .Concat(allScopeProductIds)
  89 + .Distinct(StringComparer.Ordinal)
  90 + .ToList();
  91 + }
  92 +
81 if (productIds.Count == 0) 93 if (productIds.Count == 0)
82 { 94 {
83 return new List<UsAppLabelCategoryTreeNodeDto>(); 95 return new List<UsAppLabelCategoryTreeNodeDto>();
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/scripts/fl_product_availability.sql 0 → 100644
  1 +-- 产品适用门店:ALL / SPECIFIED(ALL 时动态包含后续新增门店,不写 fl_location_product 快照)
  2 +-- 可重复执行
  3 +
  4 +SET @db := DATABASE();
  5 +
  6 +SET @col_product_availability := (
  7 + SELECT COUNT(*) FROM information_schema.COLUMNS
  8 + WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 'fl_product' AND COLUMN_NAME = 'AvailabilityType'
  9 +);
  10 +SET @ddl_product_availability := IF(
  11 + @col_product_availability = 0,
  12 + 'ALTER TABLE `fl_product` ADD COLUMN `AvailabilityType` varchar(20) NOT NULL DEFAULT ''SPECIFIED'' COMMENT ''适用门店:ALL/SPECIFIED'' AFTER `State`',
  13 + 'SELECT 1'
  14 +);
  15 +PREPARE stmt_product_availability FROM @ddl_product_availability;
  16 +EXECUTE stmt_product_availability;
  17 +DEALLOCATE PREPARE stmt_product_availability;
项目相关文档/2026-07-09代码修改.md 0 → 100644
  1 +# 2026-07-09 代码修改
  2 +
  3 +本文档说明 **2026-07-09** 对美国版标签(Label)模块的接口补充:**标签列表**与**批量导入**(Bulk Add Labels)。
  4 +
  5 +---
  6 +
  7 +## 一、背景与目标
  8 +
  9 +| 项目 | 说明 |
  10 +|------|------|
  11 +| 业务场景 | Web 管理端 **Bulk Add Labels** 页面:同一模板下多行录入标签基本字段 + 模板数据字段后一次性保存 |
  12 +| 原行为 | 前端 `LabelsList.tsx` 对每行循环调用 `POST /api/app/label` 单条创建,模板数据再单独 `updateLabelTemplate` |
  13 +| 新行为 | 新增 `POST /api/app/label/batch-create`,一次提交多行;可选合并写入 `fl_label_template_product_default` |
  14 +| 列表接口 | `GET /api/app/label?SkipCount=1&MaxResultCount=10` 为标签分页列表(按标签维度分页,非 label-product 笛卡尔行) |
  15 +
  16 +---
  17 +
  18 +## 二、标签列表
  19 +
  20 +### 基本信息
  21 +
  22 +| 项目 | 内容 |
  23 +|------|------|
  24 +| 方法 | `GET` |
  25 +| 路径 | `/api/app/label` |
  26 +| 鉴权 | Bearer Token |
  27 +| 示例 | `/api/app/label?SkipCount=1&MaxResultCount=10` |
  28 +
  29 +### 分页参数
  30 +
  31 +| 参数 | 类型 | 说明 |
  32 +|------|------|------|
  33 +| `SkipCount` | `int` | 页码,**从 1 起**(非 0) |
  34 +| `MaxResultCount` | `int` | 每页条数 |
  35 +
  36 +### 筛选参数(Query)
  37 +
  38 +| 参数 | 说明 |
  39 +|------|------|
  40 +| `PartnerId` | 按 Company(`fl_partner.Id`)下门店集合筛选 |
  41 +| `GroupId` | 按 Region(`fl_group.Id`)筛选:命中 `fl_label_region`、`fl_label_location` 或 `AppliedRegionType=ALL` |
  42 +| `LocationId` | 按门店(`location.Id`)筛选;传则优先于 `GroupId` |
  43 +| `ProductId` | 按产品筛选(一个产品可对应多个标签) |
  44 +| `Keyword` | 关键词 |
  45 +| `LabelCategoryId` | 标签分类 |
  46 +| `LabelTypeId` | 标签类型(可选) |
  47 +| `TemplateCode` | 模板编码 |
  48 +| `State` | 启用状态 |
  49 +
  50 +### 出参结构
  51 +
  52 +```json
  53 +{
  54 + "pageIndex": 1,
  55 + "pageSize": 10,
  56 + "totalCount": 100,
  57 + "totalPages": 10,
  58 + "items": [
  59 + {
  60 + "id": "LBL_xxx",
  61 + "labelName": "Turkey Breast",
  62 + "locationName": "Store A, Store B",
  63 + "locationIds": ["loc-id-1", "loc-id-2"],
  64 + "region": "Region A",
  65 + "regionIds": ["group-id-1"],
  66 + "groupIds": ["group-id-1"],
  67 + "appliedRegionType": "SPECIFIED",
  68 + "labelCategoryName": "Prep",
  69 + "productCategoryName": "Meat",
  70 + "products": "Turkey Breast",
  71 + "templateName": "3\"x6\" Nutrition Details",
  72 + "templateCode": "tpl_229mx5_mr05n3cq",
  73 + "labelTypeName": "Use By",
  74 + "state": true,
  75 + "lastEdited": "2026-07-09T10:00:00",
  76 + "hasError": false
  77 + }
  78 + ]
  79 +}
  80 +```
  81 +
  82 +### 列表 curl 示例
  83 +
  84 +```bash
  85 +# 登录(管理端)
  86 +curl -X POST "http://192.168.31.88:19001/api/app/account/login" \
  87 + -H "Content-Type: application/json" \
  88 + -d '{"userName":"sandi@123.com","password":"123456"}'
  89 +
  90 +# 标签列表第一页(10 条)
  91 +curl -G "http://192.168.31.88:19001/api/app/label" \
  92 + -H "Authorization: Bearer {token}" \
  93 + --data-urlencode "SkipCount=1" \
  94 + --data-urlencode "MaxResultCount=10"
  95 +```
  96 +
  97 +---
  98 +
  99 +## 三、标签批量导入
  100 +
  101 +### 基本信息
  102 +
  103 +| 项目 | 内容 |
  104 +|------|------|
  105 +| 方法 | `POST` |
  106 +| 路径 | `/api/app/label/batch-create` |
  107 +| 鉴权 | Bearer Token |
  108 +| 对应页面 | Web 端 **Bulk Add Labels**(`LabelsList.tsx` → `LabelBulkAddPage`) |
  109 +| 单次上限 | 500 行 |
  110 +
  111 +### Body 顶层字段
  112 +
  113 +| 字段 | 类型 | 必填 | 说明 |
  114 +|------|------|------|------|
  115 +| `templateCode` | `string` | 是 | 所有行共用的模板编码 |
  116 +| `items` | `array` | 是 | 导入行列表 |
  117 +| `saveTemplateProductDefaults` | `bool` | 否 | 是否合并写入模板 ProductDefaults,默认 `true` |
  118 +
  119 +### `items[]` 每行字段
  120 +
  121 +#### 标签基本字段(与单条 `POST /api/app/label` 一致)
  122 +
  123 +| 字段 | 类型 | 必填 | 说明 |
  124 +|------|------|------|------|
  125 +| `labelName` | `string` | 是 | 标签名称 |
  126 +| `labelCategoryId` | `string` | 是 | 标签分类 Id |
  127 +| `labelTypeId` | `string` | 建议 | 标签类型 Id |
  128 +| `productIds` | `string[]` | 是 | 至少 1 个产品 |
  129 +| `locationIds` | `string[]` | 建议 | 适用门店(主字段) |
  130 +| `locationId` | `string` | 否 | 兼容单门店,与 `locationIds` 合并 |
  131 +| `appliedRegionType` | `string` | 否 | `ALL` / `SPECIFIED` |
  132 +| `regionIds` / `groupIds` | `string[]` | 条件 | `SPECIFIED` 时传 Region |
  133 +| `partnerId` / `partnerIds` | `string` / `string[]` | 否 | Company 范围 |
  134 +| `labelCode` | `string` | 否 | 不传则自动生成 `LBL_{guid}` |
  135 +| `labelInfoJson` | `object` | 否 | 标签级模板 JSON(通常走 ProductDefaults) |
  136 +| `state` | `bool` | 否 | 默认 `true` |
  137 +
  138 +#### 模板数据字段(对应 Bulk Add 表格列)
  139 +
  140 +| 字段 | 类型 | 说明 |
  141 +|------|------|------|
  142 +| `templateDefaultValues` | `object` | 已组装的 elementId → 值;**优先使用**,不再从下方字段推导 |
  143 +| `templateDataValues` | `object` | 文本类录入(如 Text、Barcode 手填值) |
  144 +| `templateDateOffsets` | `object` | 日期/时间/时长:`{ "el-id": { "unit": "Days", "value": "3" } }` |
  145 +| `nutritionByElementId` | `object` | 营养成分:`{ "el-nutrition": { "calories": "120" } }` |
  146 +
  147 +**模板数据落库规则**
  148 +
  149 +- `saveTemplateProductDefaults=true` 时:按 `productId + labelTypeId` 合并写入 `fl_label_template_product_default`(与前端 `saveTemplateDefaultsAfterLabels` 一致)
  150 +- 日期偏移存为 JSON 字符串:`{"unit":"Days","value":"3"}`
  151 +- Template 面板条码/二维码自动填充产品 `codeValue`;Label Name / Label Type 自动绑定行内 `labelName`、类型名
  152 +
  153 +### 请求示例
  154 +
  155 +```json
  156 +{
  157 + "templateCode": "tpl_229mx5_mr05n3cq",
  158 + "saveTemplateProductDefaults": true,
  159 + "items": [
  160 + {
  161 + "labelName": "Chicken Salad",
  162 + "labelCategoryId": "3a2228ca-42fa-5273-1105-3d8252ffdd99",
  163 + "labelTypeId": "3a2228e5-33c5-278e-a09f-47fd6e2ddbc7",
  164 + "locationIds": ["3a222878-b4c1-d27b-d437-93da14886350"],
  165 + "productIds": ["3a2228a8-6a51-6cc4-fee2-b77769766b33"],
  166 + "appliedRegionType": "SPECIFIED",
  167 + "regionIds": [],
  168 + "templateDataValues": {
  169 + "el-1782794752668-0gixa9y": "Fresh batch text",
  170 + "el-1782794771519-4360c0p": "123456789"
  171 + },
  172 + "templateDateOffsets": {
  173 + "el-1782794481721-sdf7mvy": { "unit": "Days", "value": "3" }
  174 + },
  175 + "state": true
  176 + },
  177 + {
  178 + "labelName": "Turkey Wrap",
  179 + "labelCategoryId": "3a2228ca-42fa-5273-1105-3d8252ffdd99",
  180 + "labelTypeId": "3a2228e6-3ed0-b056-a08b-ea8b1eea46a0",
  181 + "locationIds": ["3a222878-b4c1-d27b-d437-93da14886350"],
  182 + "productIds": ["3a2228a8-6a51-6cc4-fee2-b77769766b33"],
  183 + "templateDataValues": {
  184 + "el-1782794752668-0gixa9y": "Ready to serve"
  185 + },
  186 + "templateDateOffsets": {
  187 + "el-1782794481721-sdf7mvy": { "unit": "Days", "value": "5" }
  188 + }
  189 + }
  190 + ]
  191 +}
  192 +```
  193 +
  194 +### 响应示例
  195 +
  196 +```json
  197 +{
  198 + "successCount": 2,
  199 + "failCount": 0,
  200 + "successItems": [
  201 + { "rowNumber": 1, "labelCode": "LBL_abc...", "labelName": "Chicken Salad" },
  202 + { "rowNumber": 2, "labelCode": "LBL_def...", "labelName": "Turkey Wrap" }
  203 + ],
  204 + "errors": []
  205 +}
  206 +```
  207 +
  208 +**部分成功示例**(第 2 行校验失败、第 1 行仍创建):
  209 +
  210 +```json
  211 +{
  212 + "successCount": 1,
  213 + "failCount": 1,
  214 + "successItems": [
  215 + { "rowNumber": 1, "labelCode": "LBL_abc...", "labelName": "Chicken Salad" }
  216 + ],
  217 + "errors": [
  218 + { "rowNumber": 2, "labelName": "", "message": "标签名称不能为空" }
  219 + ]
  220 +}
  221 +```
  222 +
  223 +### 批量导入 curl 示例
  224 +
  225 +```bash
  226 +curl -X POST "http://192.168.31.88:19001/api/app/label/batch-create" \
  227 + -H "Authorization: Bearer {token}" \
  228 + -H "Content-Type: application/json" \
  229 + -d '{
  230 + "templateCode": "tpl_229mx5_mr05n3cq",
  231 + "saveTemplateProductDefaults": true,
  232 + "items": [
  233 + {
  234 + "labelName": "Batch Test",
  235 + "labelCategoryId": "3a2228ca-42fa-5273-1105-3d8252ffdd99",
  236 + "labelTypeId": "3a2228e5-33c5-278e-a09f-47fd6e2ddbc7",
  237 + "locationIds": ["3a222878-b4c1-d27b-d437-93da14886350"],
  238 + "productIds": ["3a2228a8-6a51-6cc4-fee2-b77769766b33"],
  239 + "templateDataValues": { "el-1782794752668-0gixa9y": "Fresh" },
  240 + "templateDateOffsets": { "el-1782794481721-sdf7mvy": { "unit": "Days", "value": "3" } }
  241 + }
  242 + ]
  243 + }'
  244 +```
  245 +
  246 +---
  247 +
  248 +## 四、与单条创建对比
  249 +
  250 +| 能力 | `POST /api/app/label` | `POST /api/app/label/batch-create` |
  251 +|------|----------------------|-----------------------------------|
  252 +| 行数 | 1 条 | 最多 500 条 |
  253 +| 模板编码 | 每 Body 自带 | 顶层 `templateCode` 共用 |
  254 +| 模板数据 | 仅 `labelInfoJson` | 支持结构化模板字段 + ProductDefaults 合并 |
  255 +| 失败处理 | 整请求失败 | 行级错误收集,支持部分成功 |
  256 +| 返回值 | 标签详情 DTO | `successCount` / `failCount` / `errors` / `successItems` |
  257 +
  258 +---
  259 +
  260 +## 五、代码改动摘要
  261 +
  262 +| 文件 | 改动 |
  263 +|------|------|
  264 +| `ILabelAppService.cs` | 新增 `BatchCreateAsync` |
  265 +| `LabelAppService.cs` | 实现批量导入;逐行复用 `CreateAsync`;可选合并模板 ProductDefaults |
  266 +| `LabelBatchCreateInputVo.cs` | 批量入参 DTO |
  267 +| `LabelBatchCreateItemInputVo.cs` | 单行(基本字段 + 模板数据字段) |
  268 +| `LabelBatchDateOffsetInputVo.cs` | 日期偏移单位+数值 |
  269 +| `LabelBatchCreateResultDto.cs` | 批量结果 DTO |
  270 +| `LabelBatchTemplateDefaultsHelper.cs` | 组装/合并模板 ProductDefaults |
  271 +
  272 +---
  273 +
  274 +## 六、部署与联调注意
  275 +
  276 +1. `dotnet build` 编译 `FoodLabeling.Application` 与 `Yi.Abp.Web` 后**重启 API 进程**(未重启时 `batch-create` 会返回 405)
  277 +2. 管理端登录:`POST /api/app/account/login`(非 `/api/oauth/Login`)
  278 +3. 本地 Base URL 以 `appsettings.json` 中 `App:SelfUrl` 为准(当前示例为 `http://192.168.31.88:19001`)
  279 +4. 前端 `LabelsList.tsx` 的 `submit()` 仍循环调单条 `createLabel`;对接批量接口时需改为调用 `batch-create`
  280 +
  281 +---
  282 +
  283 +## 七、相关文档
  284 +
  285 +- 标签多门店 `locationIds`:`项目相关文档/6-23代码优化.md`
  286 +- 模板三维 scope:`项目相关文档/6-4代码优化.md`