diff --git a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/Dtos/Label/LabelBatchCreateInputVo.cs b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/Dtos/Label/LabelBatchCreateInputVo.cs new file mode 100644 index 0000000..c3e2333 --- /dev/null +++ b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/Dtos/Label/LabelBatchCreateInputVo.cs @@ -0,0 +1,18 @@ +namespace FoodLabeling.Application.Contracts.Dtos.Label; + +/// +/// 标签批量导入入参(同一模板多行) +/// +public class LabelBatchCreateInputVo +{ + /// 模板编码(所有行共用) + public string TemplateCode { get; set; } = string.Empty; + + /// 导入行列表 + public List Items { get; set; } = new(); + + /// + /// 是否将各行模板数据合并写入 fl_label_template_product_default(与 Web 端 Bulk Add 行为一致) + /// + public bool SaveTemplateProductDefaults { get; set; } = true; +} diff --git a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/Dtos/Label/LabelBatchCreateItemInputVo.cs b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/Dtos/Label/LabelBatchCreateItemInputVo.cs new file mode 100644 index 0000000..00df67d --- /dev/null +++ b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/Dtos/Label/LabelBatchCreateItemInputVo.cs @@ -0,0 +1,50 @@ +namespace FoodLabeling.Application.Contracts.Dtos.Label; + +/// +/// 批量导入单行:标签基本字段 + 模板数据字段 +/// +public class LabelBatchCreateItemInputVo +{ + public string? LabelCode { get; set; } + + public string LabelName { get; set; } = string.Empty; + + public string? PartnerId { get; set; } + + public List? PartnerIds { get; set; } + + public string? AppliedRegionType { get; set; } + + public List? RegionIds { get; set; } + + public List? GroupIds { get; set; } + + public List? LocationIds { get; set; } + + public string? LocationId { get; set; } + + public string LabelCategoryId { get; set; } = string.Empty; + + public string? LabelTypeId { get; set; } + + public List ProductIds { get; set; } = new(); + + /// 标签级模板数据(落库 fl_label.LabelInfoJson);通常批量导入走模板 ProductDefaults + public object? LabelInfoJson { get; set; } + + public bool State { get; set; } = true; + + /// + /// 已组装的模板默认值(elementId → 值)。若传入则优先使用,不再从下方结构化字段推导。 + /// + public Dictionary? TemplateDefaultValues { get; set; } + + /// 模板文本类录入(elementId → 文本) + public Dictionary? TemplateDataValues { get; set; } + + /// 模板日期/时间/时长录入(elementId → 单位+数值) + public Dictionary? TemplateDateOffsets { get; set; } + + /// 营养成分手动录入(nutritionElementId → 子字段键值) + public Dictionary>? NutritionByElementId { get; set; } +} diff --git a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/Dtos/Label/LabelBatchCreateResultDto.cs b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/Dtos/Label/LabelBatchCreateResultDto.cs new file mode 100644 index 0000000..a92f894 --- /dev/null +++ b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/Dtos/Label/LabelBatchCreateResultDto.cs @@ -0,0 +1,33 @@ +namespace FoodLabeling.Application.Contracts.Dtos.Label; + +/// +/// 标签批量导入结果 +/// +public class LabelBatchCreateResultDto +{ + public int SuccessCount { get; set; } + + public int FailCount { get; set; } + + public List Errors { get; set; } = new(); + + public List SuccessItems { get; set; } = new(); +} + +public class LabelBatchCreateErrorDto +{ + public int RowNumber { get; set; } + + public string? LabelName { get; set; } + + public string Message { get; set; } = string.Empty; +} + +public class LabelBatchCreateSuccessItemDto +{ + public int RowNumber { get; set; } + + public string LabelCode { get; set; } = string.Empty; + + public string LabelName { get; set; } = string.Empty; +} diff --git a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/Dtos/Label/LabelBatchDateOffsetInputVo.cs b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/Dtos/Label/LabelBatchDateOffsetInputVo.cs new file mode 100644 index 0000000..339bad0 --- /dev/null +++ b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/Dtos/Label/LabelBatchDateOffsetInputVo.cs @@ -0,0 +1,13 @@ +namespace FoodLabeling.Application.Contracts.Dtos.Label; + +/// +/// 批量导入行:模板日期/时间/时长偏移录入(单位 + 数值) +/// +public class LabelBatchDateOffsetInputVo +{ + /// 偏移单位,如 Days、Hours + public string Unit { get; set; } = "Days"; + + /// 偏移数值 + public string Value { get; set; } = string.Empty; +} diff --git a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/Dtos/Product/ProductCreateInputVo.cs b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/Dtos/Product/ProductCreateInputVo.cs index 623f4cb..5f849e5 100644 --- a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/Dtos/Product/ProductCreateInputVo.cs +++ b/美国版/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 public bool State { get; set; } = true; /// + /// 适用门店:ALL / SPECIFIED(ALL 时动态包含后续新增门店,不写快照) + /// + public string? AvailabilityType { get; set; } + + /// /// 适用 Company(fl_partner.Id,UI 称 Company);展开该公司下全部门店后与 Region/门店合并写入 fl_location_product /// public string? PartnerId { get; set; } diff --git a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/Dtos/Product/ProductGetListOutputDto.cs b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/Dtos/Product/ProductGetListOutputDto.cs index 8f75e0e..2d01648 100644 --- a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/Dtos/Product/ProductGetListOutputDto.cs +++ b/美国版/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 public bool State { get; set; } + /// 适用门店:ALL / SPECIFIED + public string AvailabilityType { get; set; } = "SPECIFIED"; + /// /// 该产品关联的标签数量(fl_label_product + fl_label) /// diff --git a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/Dtos/Product/ProductGetOutputDto.cs b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/Dtos/Product/ProductGetOutputDto.cs index 2d36fb4..a5da767 100644 --- a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/Dtos/Product/ProductGetOutputDto.cs +++ b/美国版/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 public bool State { get; set; } + /// 适用门店:ALL / SPECIFIED + public string AvailabilityType { get; set; } = "SPECIFIED"; + /// 适用 Company Id(fl_partner.Id,由关联门店反推;多公司时取第一个) public string? PartnerId { get; set; } diff --git a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/IServices/ILabelAppService.cs b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/IServices/ILabelAppService.cs index a7870cf..7506e37 100644 --- a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/IServices/ILabelAppService.cs +++ b/美国版/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 Task CreateAsync(LabelCreateInputVo input); /// + /// 批量导入标签(同一模板多行)。每行含标签基本字段与模板数据字段;可选合并写入模板 ProductDefaults。 + /// + Task BatchCreateAsync(LabelBatchCreateInputVo input); + + /// /// 编辑标签(id=LabelCode)。适用 Region / 门店字段同 。 /// Task UpdateAsync(string id, LabelUpdateInputVo input); diff --git a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/AllScopeBindingHelper.cs b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/AllScopeBindingHelper.cs new file mode 100644 index 0000000..2f0df3d --- /dev/null +++ b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/AllScopeBindingHelper.cs @@ -0,0 +1,228 @@ +using FoodLabeling.Application.Services.DbModels; +using SqlSugar; + +namespace FoodLabeling.Application.Helpers; + +/// +/// 「适用全部 Region/Location/Company」:保存为 ALL(不写关联快照),查询时动态包含后续新增的 Region/Location。 +/// +public static class AllScopeBindingHelper +{ + public const string ScopeAll = "ALL"; + public const string ScopeSpecified = "SPECIFIED"; + + public const string AllRegionsDisplay = "All Regions"; + public const string AllLocationsDisplay = "All Locations"; + public const string AllCompaniesDisplay = "All Companies"; + + /// 选中 Id 是否覆盖当前上下文中全部可选项(用于将「全选」规范为 ALL)。 + public static bool IsFullIdSelection(IReadOnlyList selected, IReadOnlyList universe) + { + if (universe.Count == 0) + { + return selected.Count == 0; + } + + if (selected.Count != universe.Count) + { + return false; + } + + var set = new HashSet(universe, StringComparer.Ordinal); + return selected.All(id => set.Contains(id)); + } + + /// 解析维度类型:显式 ALL、空数组 ALL、或 Id 列表全选时视为 ALL。 + public static string ResolveDimensionType( + string? declaredType, + IReadOnlyList ids, + bool hasArrayInPayload, + bool isFullSelection) + { + if (isFullSelection || (ids.Count == 0 && IsDeclaredAll(declaredType))) + { + return ScopeAll; + } + + if (ids.Count > 0) + { + return ScopeSpecified; + } + + if (hasArrayInPayload && IsDeclaredAll(declaredType)) + { + return ScopeAll; + } + + var normalized = (declaredType ?? ScopeAll).Trim().ToUpperInvariant(); + return normalized == ScopeSpecified ? ScopeSpecified : ScopeAll; + } + + public static bool IsDeclaredAll(string? type) => + string.Equals((type ?? ScopeAll).Trim(), ScopeAll, StringComparison.OrdinalIgnoreCase); + + /// 全部 Company(fl_partner.Id)。 + public static async Task> ResolveAllPartnerIdsAsync(ISqlSugarClient db) + { + var rows = await db.Queryable() + .Where(x => !x.IsDeleted) + .Select(x => x.Id) + .ToListAsync(); + return LocationScopeBindingHelper.NormalizeIds(rows); + } + + /// 全部 Region;可按 Company 限定。 + public static async Task> ResolveAllRegionIdsAsync( + ISqlSugarClient db, + IReadOnlyList? partnerIds) + { + var query = db.Queryable().Where(x => !x.IsDeleted); + var pids = LocationScopeBindingHelper.NormalizeIds(partnerIds); + if (pids.Count > 0) + { + query = query.Where(x => pids.Contains(x.PartnerId)); + } + + var rows = await query.Select(x => x.Id).ToListAsync(); + return LocationScopeBindingHelper.NormalizeIds(rows); + } + + /// 全部门店;可按 Company / Region 限定。 + public static async Task> ResolveAllLocationIdsAsync( + ISqlSugarClient db, + IReadOnlyList? partnerIds, + IReadOnlyList? regionIds) + { + var merged = await LocationScopeBindingHelper.MergeToLocationIdsAsync( + db, + partnerIds, + regionIds, + null); + return LocationScopeBindingHelper.NormalizeIds(merged); + } + + /// Company 维度是否应存为 ALL(含「勾选了全部 Company」)。 + public static async Task<(string Type, List Ids)> NormalizePartnerScopeAsync( + ISqlSugarClient db, + string? declaredType, + IReadOnlyList? partnerIds, + IReadOnlyList? companyIds, + bool hasArrayInPayload) + { + var ids = LabelEntityPartnerScopeHelper.NormalizePartnerIds(partnerIds, companyIds); + var allPartners = await ResolveAllPartnerIdsAsync(db); + var isFull = ids.Count > 0 && IsFullIdSelection(ids, allPartners); + var type = ResolveDimensionType(declaredType, ids, hasArrayInPayload, isFull); + return (type, type == ScopeSpecified ? ids : new List()); + } + + /// Region 维度是否应存为 ALL。 + public static async Task<(string Type, List Ids)> NormalizeRegionScopeAsync( + ISqlSugarClient db, + string? declaredType, + IReadOnlyList regionIds, + bool hasArrayInPayload, + IReadOnlyList? partnerIdsForContext) + { + var ids = LocationScopeBindingHelper.NormalizeIds(regionIds); + var allRegions = await ResolveAllRegionIdsAsync(db, partnerIdsForContext); + var isFull = ids.Count > 0 && IsFullIdSelection(ids, allRegions); + var type = ResolveDimensionType(declaredType, ids, hasArrayInPayload, isFull); + return (type, type == ScopeSpecified ? ids : new List()); + } + + /// Location 维度是否应存为 ALL。 + public static async Task<(string Type, List Ids)> NormalizeLocationScopeAsync( + ISqlSugarClient db, + string? declaredType, + IReadOnlyList locationIds, + bool hasArrayInPayload, + IReadOnlyList? partnerIdsForContext, + IReadOnlyList? regionIdsForContext) + { + var ids = LocationScopeBindingHelper.NormalizeIds(locationIds); + var allLocations = await ResolveAllLocationIdsAsync(db, partnerIdsForContext, regionIdsForContext); + var isFull = ids.Count > 0 && IsFullIdSelection(ids, allLocations); + var type = ResolveDimensionType(declaredType, ids, hasArrayInPayload, isFull); + return (type, type == ScopeSpecified ? ids : new List()); + } + + /// + /// 标签类型/分类/多选项/产品分类:Region+Location 合并后是否应视为 ALL。 + /// + public static async Task ShouldTreatMergedLocationScopeAsAllAsync( + ISqlSugarClient db, + string? declaredAvailabilityType, + IReadOnlyList? regionIds, + IReadOnlyList? locationIds, + bool hasScopeArrays, + IReadOnlyList? partnerIdsForContext) + { + if (IsDeclaredAll(declaredAvailabilityType) + && LocationScopeBindingHelper.NormalizeIds(regionIds).Count == 0 + && LocationScopeBindingHelper.NormalizeIds(locationIds).Count == 0) + { + return true; + } + + if (hasScopeArrays + && LocationScopeBindingHelper.NormalizeIds(regionIds).Count == 0 + && LocationScopeBindingHelper.NormalizeIds(locationIds).Count == 0 + && IsDeclaredAll(declaredAvailabilityType)) + { + return true; + } + + var merged = await LocationScopeBindingHelper.MergeToLocationIdsAsync( + db, + (IReadOnlyList?)null, + regionIds, + locationIds); + if (merged.Count == 0) + { + return false; + } + + var allLocations = await ResolveAllLocationIdsAsync(db, partnerIdsForContext, null); + return IsFullIdSelection(merged, allLocations); + } + + /// 产品门店范围是否应存为 ALL(不写 fl_location_product 快照)。 + public static async Task ShouldTreatProductLocationScopeAsAllAsync( + ISqlSugarClient db, + string? declaredAvailabilityType, + string? partnerId, + IReadOnlyList? groupIds, + IReadOnlyList? locationIds, + bool hasScopePayload) + { + if (IsDeclaredAll(declaredAvailabilityType) + && string.IsNullOrWhiteSpace(partnerId) + && LocationScopeBindingHelper.NormalizeIds(groupIds).Count == 0 + && LocationScopeBindingHelper.NormalizeIds(locationIds).Count == 0) + { + return true; + } + + if (!hasScopePayload) + { + return false; + } + + var partnerIds = string.IsNullOrWhiteSpace(partnerId) + ? null + : new List { partnerId.Trim() }; + var merged = await LocationScopeBindingHelper.MergeToLocationIdsAsync( + db, + partnerId, + groupIds, + locationIds); + if (merged.Count == 0) + { + return false; + } + + var allLocations = await ResolveAllLocationIdsAsync(db, partnerIds, null); + return IsFullIdSelection(merged, allLocations); + } +} diff --git a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/LabelBatchTemplateDefaultsHelper.cs b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/LabelBatchTemplateDefaultsHelper.cs new file mode 100644 index 0000000..56b5ebb --- /dev/null +++ b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/LabelBatchTemplateDefaultsHelper.cs @@ -0,0 +1,426 @@ +using System.Globalization; +using System.Text.Json; +using FoodLabeling.Application.Contracts.Dtos.Label; +using FoodLabeling.Application.Contracts.Dtos.LabelTemplate; +using FoodLabeling.Application.Services.DbModels; +using SqlSugar; +using Volo.Abp; +using Volo.Abp.Guids; + +namespace FoodLabeling.Application.Helpers; + +/// +/// 标签批量导入:模板 ProductDefaults 合并与默认值组装 +/// +public static class LabelBatchTemplateDefaultsHelper +{ + private static readonly HashSet DataEntryTypeAddWhitelist = new(StringComparer.OrdinalIgnoreCase) + { + "label_label name", + "label_text", + "label_qr code", + "label_barcode", + "label_price", + "label_duration date", + "label_duration time", + "label_duration", + "label_image", + "label_label type", + "label_how-to", + "label_expiration alert" + }; + + public static async Task> LoadTemplateElementsAsync( + ISqlSugarClient db, + string templateDbId) + { + var rows = await db.Queryable() + .Where(x => x.TemplateId == templateDbId) + .OrderBy(x => x.OrderNum * 1000000 + x.ZIndex) + .ToListAsync(); + + return rows.Select(e => + { + object? cfg = null; + if (!string.IsNullOrWhiteSpace(e.ConfigJson)) + { + try + { + cfg = JsonSerializer.Deserialize(e.ConfigJson); + } + catch + { + // ignore + } + } + + return new LabelTemplateElementDto + { + Id = e.ElementKey, + ElementType = e.ElementType, + TypeAdd = e.TypeAdd, + ElementName = e.ElementName, + OrderNum = e.OrderNum, + ValueSourceType = e.ValueSourceType, + InputKey = e.InputKey, + ConfigJson = cfg + }; + }).ToList(); + } + + public static Dictionary CollectDefaultValuesForItem( + IReadOnlyList elements, + LabelBatchCreateItemInputVo item, + string? productCodeValue, + string? labelTypeName) + { + if (item.TemplateDefaultValues is { Count: > 0 }) + { + return item.TemplateDefaultValues.ToDictionary( + x => x.Key, + x => x.Value, + StringComparer.OrdinalIgnoreCase); + } + + var textValues = item.TemplateDataValues ?? new Dictionary(); + var dateOffsets = item.TemplateDateOffsets ?? new Dictionary(); + var nutritionByElementId = item.NutritionByElementId ?? new Dictionary>(); + var outDict = new Dictionary(StringComparer.OrdinalIgnoreCase); + + foreach (var el in elements) + { + if (IsDataEntryTableColumnElement(el)) + { + var id = el.Id; + if (IsDateTimeDataEntryField(el)) + { + var pair = dateOffsets.TryGetValue(id, out var offset) + ? offset + : new LabelBatchDateOffsetInputVo(); + var unit = string.IsNullOrWhiteSpace(pair.Unit) ? "Days" : pair.Unit.Trim(); + var norm = NormalizeOffsetInput(pair.Value); + outDict[id] = norm.Kind switch + { + OffsetInputKind.Invalid => "", + OffsetInputKind.Zero => SerializePrintInputOffset(unit, "0"), + _ => SerializePrintInputOffset(unit, norm.StoreValue ?? "") + }; + } + else + { + outDict[id] = textValues.TryGetValue(id, out var tv) ? tv : ""; + } + } + + if (IsNutritionElement(el) + && nutritionByElementId.TryGetValue(el.Id, out var manual) + && manual.Count > 0) + { + var json = JsonSerializer.Serialize(manual); + if (json != "{}") + { + outDict[el.Id] = json; + } + } + } + + var codeValue = (productCodeValue ?? "").Trim(); + if (!string.IsNullOrWhiteSpace(codeValue)) + { + foreach (var el in elements) + { + if (IsTemplateSectionBarcodeOrQrElement(el)) + { + outDict[el.Id] = codeValue; + } + } + } + + var labelName = (item.LabelName ?? "").Trim(); + if (!string.IsNullOrWhiteSpace(labelName)) + { + foreach (var el in elements) + { + if (IsTemplateLabelNameElement(el)) + { + outDict[el.Id] = labelName; + } + } + } + + var typeName = (labelTypeName ?? "").Trim(); + if (!string.IsNullOrWhiteSpace(typeName)) + { + foreach (var el in elements) + { + if (IsTemplateLabelTypeElement(el)) + { + outDict[el.Id] = typeName; + } + } + } + + return outDict; + } + + public static bool HasTemplateDataInput(LabelBatchCreateItemInputVo item) => + item.TemplateDefaultValues is { Count: > 0 } + || item.TemplateDataValues is { Count: > 0 } + || item.TemplateDateOffsets is { Count: > 0 } + || item.NutritionByElementId is { Count: > 0 }; + + public static async Task MergeAndSaveTemplateProductDefaultsAsync( + ISqlSugarClient db, + IGuidGenerator guidGenerator, + string templateDbId, + IReadOnlyList existingDefaults, + IReadOnlyList<(string ProductId, string LabelTypeId, Dictionary DefaultValues)> newRows) + { + var map = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var row in existingDefaults) + { + var productId = row.ProductId?.Trim(); + var labelTypeId = row.LabelTypeId?.Trim(); + if (string.IsNullOrWhiteSpace(productId) || string.IsNullOrWhiteSpace(labelTypeId)) + { + continue; + } + + map[$"{productId}::{labelTypeId}"] = row; + } + + foreach (var (productId, labelTypeId, defaultValues) in newRows) + { + var pid = productId.Trim(); + var ltid = labelTypeId.Trim(); + if (string.IsNullOrWhiteSpace(pid) || string.IsNullOrWhiteSpace(ltid) || defaultValues.Count == 0) + { + continue; + } + + map[$"{pid}::{ltid}"] = new LabelTemplateProductDefaultDto + { + ProductId = pid, + LabelTypeId = ltid, + DefaultValues = defaultValues, + OrderNum = map.Count + 1 + }; + } + + var merged = map.Values + .Select((x, idx) => + { + x.OrderNum = idx + 1; + return x; + }) + .ToList(); + + var duplicateCheckSet = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var row in merged) + { + var key = $"{row.ProductId}::{row.LabelTypeId}"; + if (!duplicateCheckSet.Add(key)) + { + throw new UserFriendlyException( + $"模板默认值绑定重复:产品[{row.ProductId}]与标签类型[{row.LabelTypeId}]只能存在一条"); + } + } + + await db.Deleteable() + .Where(x => x.TemplateId == templateDbId) + .ExecuteCommandAsync(); + + if (merged.Count == 0) + { + return; + } + + var rows = merged.Select(x => new FlLabelTemplateProductDefaultDbEntity + { + Id = guidGenerator.Create().ToString(), + TemplateId = templateDbId, + ProductId = x.ProductId, + LabelTypeId = x.LabelTypeId, + DefaultValuesJson = x.DefaultValues is null ? null : JsonSerializer.Serialize(x.DefaultValues), + OrderNum = x.OrderNum + }).ToList(); + + await db.Insertable(rows).ExecuteCommandAsync(); + } + + private enum OffsetInputKind + { + Invalid, + Zero, + Amount + } + + private sealed class OffsetInputNormalizeResult + { + public OffsetInputKind Kind { get; init; } + + public string? StoreValue { get; init; } + } + + private static OffsetInputNormalizeResult NormalizeOffsetInput(string? raw) + { + var t = (raw ?? "").Trim(); + if (t.Length == 0) + { + return new OffsetInputNormalizeResult { Kind = OffsetInputKind.Zero }; + } + + if (!decimal.TryParse(t, NumberStyles.Number, CultureInfo.InvariantCulture, out var n) + && !decimal.TryParse(t, NumberStyles.Number, CultureInfo.CurrentCulture, out n)) + { + return new OffsetInputNormalizeResult { Kind = OffsetInputKind.Invalid }; + } + + if (n == 0) + { + return new OffsetInputNormalizeResult { Kind = OffsetInputKind.Zero }; + } + + return new OffsetInputNormalizeResult { Kind = OffsetInputKind.Amount, StoreValue = t }; + } + + private static string SerializePrintInputOffset(string unit, string value) => + JsonSerializer.Serialize(new { unit, value }); + + private static string CanonicalElementType(string? elementType) => + (elementType ?? "").Trim().ToUpperInvariant(); + + private static string NormalizeTypeAdd(string? typeAdd) => + (typeAdd ?? "").Trim().ToLowerInvariant().Replace(" ", " ", StringComparison.Ordinal); + + private static bool IsTemplateSectionPersistedType(LabelTemplateElementDto el) => + NormalizeTypeAdd(el.TypeAdd).StartsWith("template_", StringComparison.Ordinal); + + private static bool IsDataEntryTableColumnElement(LabelTemplateElementDto el) + { + var typeAdd = NormalizeTypeAdd(el.TypeAdd); + if (typeAdd.StartsWith("template_", StringComparison.Ordinal)) + { + return false; + } + + if (CanonicalElementType(el.ElementType) == "BLANK") + { + return false; + } + + if (!DataEntryTypeAddWhitelist.Contains(typeAdd)) + { + return false; + } + + var vst = (el.ValueSourceType ?? "FIXED").Trim().ToUpperInvariant(); + return vst is "FIXED" or "PRINT_INPUT"; + } + + private static bool IsDateTimeDataEntryField(LabelTemplateElementDto el) + { + var type = CanonicalElementType(el.ElementType); + if (type is "TIME" or "DURATION") + { + return true; + } + + if (type != "DATE") + { + return false; + } + + var cfg = ParseConfigDict(el.ConfigJson); + var inputType = GetConfigString(cfg, "inputType", "InputType").ToLowerInvariant(); + if (inputType is "datetime" or "date") + { + return true; + } + + var typeAdd = NormalizeTypeAdd(el.TypeAdd); + if (typeAdd is "label_duration date" || typeAdd.Contains("duration date", StringComparison.Ordinal)) + { + return true; + } + + var nameHint = $"{el.ElementName} {el.InputKey}".ToLowerInvariant(); + return nameHint.Contains("durationdate", StringComparison.Ordinal) + || nameHint.Contains("duration_date", StringComparison.Ordinal) + || nameHint.Contains("duration date", StringComparison.Ordinal); + } + + private static bool IsNutritionElement(LabelTemplateElementDto el) => + CanonicalElementType(el.ElementType) == "NUTRITION"; + + private static bool IsTemplateSectionBarcodeOrQrElement(LabelTemplateElementDto el) + { + if (!IsTemplateSectionPersistedType(el)) + { + return false; + } + + var t = CanonicalElementType(el.ElementType); + return t is "BARCODE" or "QRCODE"; + } + + private static bool IsTemplateLabelNameElement(LabelTemplateElementDto el) => + !IsTemplateSectionPersistedType(el) && NormalizeTypeAdd(el.TypeAdd) == "label_label name"; + + private static bool IsTemplateLabelTypeElement(LabelTemplateElementDto el) => + !IsTemplateSectionPersistedType(el) && NormalizeTypeAdd(el.TypeAdd) == "label_label type"; + + private static Dictionary ParseConfigDict(object? configJson) + { + if (configJson is null) + { + return new Dictionary(StringComparer.OrdinalIgnoreCase); + } + + if (configJson is Dictionary dict) + { + return dict; + } + + if (configJson is JsonElement je && je.ValueKind == JsonValueKind.Object) + { + var outDict = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var prop in je.EnumerateObject()) + { + outDict[prop.Name] = prop.Value; + } + + return outDict; + } + + try + { + return JsonSerializer.Deserialize>(JsonSerializer.Serialize(configJson)) + ?? new Dictionary(StringComparer.OrdinalIgnoreCase); + } + catch + { + return new Dictionary(StringComparer.OrdinalIgnoreCase); + } + } + + private static string GetConfigString(IReadOnlyDictionary cfg, params string[] keys) + { + foreach (var key in keys) + { + if (!cfg.TryGetValue(key, out var val) || val is null) + { + continue; + } + + if (val is JsonElement je) + { + return je.ValueKind == JsonValueKind.String ? je.GetString() ?? "" : je.ToString(); + } + + return val.ToString() ?? ""; + } + + return ""; + } +} diff --git a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/LabelEntityPartnerScopeHelper.cs b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/LabelEntityPartnerScopeHelper.cs index 4aa1d5a..6e21224 100644 --- a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/LabelEntityPartnerScopeHelper.cs +++ b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/LabelEntityPartnerScopeHelper.cs @@ -112,10 +112,13 @@ public static class LabelEntityPartnerScopeHelper IReadOnlyList? companyIds) { var normalizedPartnerIds = NormalizePartnerIds(partnerIds, companyIds); - var partnerType = ResolveAppliedPartnerType( + var (partnerType, partnerIdsForSave) = await AllScopeBindingHelper.NormalizePartnerScopeAsync( + db, appliedPartnerType, - normalizedPartnerIds, + partnerIds, + companyIds, partnerIds is not null || companyIds is not null); + normalizedPartnerIds = partnerIdsForSave; ValidatePartnerType(partnerType); diff --git a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/LabelTemplateScopeHelper.cs b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/LabelTemplateScopeHelper.cs index 5c1e81d..6cde130 100644 --- a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/LabelTemplateScopeHelper.cs +++ b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/LabelTemplateScopeHelper.cs @@ -67,18 +67,34 @@ public static class LabelTemplateScopeHelper var regionIds = NormalizeRegionIds(input); var locationIds = MergeExplicitLocationIds(input); - var partnerType = ResolveDimensionType( + var (partnerType, partnerIdsForSave) = await AllScopeBindingHelper.NormalizePartnerScopeAsync( + db, input.AppliedPartnerType, partnerIds, + null, input.PartnerIds is not null || input.CompanyIds is not null); - var regionType = ResolveDimensionType( + partnerIds = partnerIdsForSave; + + var partnerContext = string.Equals(partnerType, ScopeSpecified, StringComparison.OrdinalIgnoreCase) + ? partnerIds + : null; + + var (regionType, regionIdsForSave) = await AllScopeBindingHelper.NormalizeRegionScopeAsync( + db, input.AppliedRegionType, regionIds, - input.RegionIds is not null || input.GroupIds is not null); - var locationType = ResolveDimensionType( + input.RegionIds is not null || input.GroupIds is not null, + partnerContext); + regionIds = regionIdsForSave; + + var (locationType, locationIdsForSave) = await AllScopeBindingHelper.NormalizeLocationScopeAsync( + db, input.AppliedLocationType, locationIds, - input.LocationIds is not null || input.AppliedLocationIds is not null); + input.LocationIds is not null || input.AppliedLocationIds is not null, + partnerContext, + string.Equals(regionType, ScopeSpecified, StringComparison.OrdinalIgnoreCase) ? regionIds : null); + locationIds = locationIdsForSave; ValidateDimensionType("Company", partnerType); ValidateDimensionType("Region", regionType); diff --git a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/ProductScopeSchemaHelper.cs b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/ProductScopeSchemaHelper.cs new file mode 100644 index 0000000..b5df963 --- /dev/null +++ b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/ProductScopeSchemaHelper.cs @@ -0,0 +1,40 @@ +using SqlSugar; + +namespace FoodLabeling.Application.Helpers; + +/// +/// 探测 fl_product.AvailabilityType 列是否已迁移。 +/// +public static class ProductScopeSchemaHelper +{ + private static bool? _hasAvailabilityTypeColumn; + + public static async Task HasAvailabilityTypeColumnAsync(ISqlSugarClient db) + { + if (_hasAvailabilityTypeColumn is not null) + { + return _hasAvailabilityTypeColumn.Value; + } + + try + { + var count = await db.Ado.GetIntAsync( + """ + SELECT COUNT(*) + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = 'fl_product' + AND COLUMN_NAME = 'AvailabilityType' + """); + _hasAvailabilityTypeColumn = count > 0; + } + catch + { + _hasAvailabilityTypeColumn = false; + } + + return _hasAvailabilityTypeColumn.Value; + } + + public static void ResetCacheForTests() => _hasAvailabilityTypeColumn = null; +} diff --git a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/DbModels/FlProductDbEntity.cs b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/DbModels/FlProductDbEntity.cs index 345f18f..7d31ad8 100644 --- a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/DbModels/FlProductDbEntity.cs +++ b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/DbModels/FlProductDbEntity.cs @@ -31,4 +31,9 @@ public class FlProductDbEntity public string? CategoryPhotoUrl { get; set; } public bool State { get; set; } + + /// + /// 适用门店:ALL / SPECIFIED(ALL 时动态包含后续新增门店) + /// + public string AvailabilityType { get; set; } = "SPECIFIED"; } diff --git a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/LabelAppService.cs b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/LabelAppService.cs index 2b7202a..5023bcb 100644 --- a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/LabelAppService.cs +++ b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/LabelAppService.cs @@ -460,6 +460,201 @@ public class LabelAppService : ApplicationService, ILabelAppService return await GetAsync(labelCode); } + /// + /// 批量导入标签(同一模板多行) + /// + /// + /// 用于 Web 端 Bulk Add Labels:一次提交多行标签基本字段(门店、分类、类型、产品等)与模板数据字段(文本、日期偏移、条码等)。 + /// + /// 示例请求: + /// ```json + /// { + /// "templateCode": "TPL_NUTRITION_3X6", + /// "saveTemplateProductDefaults": true, + /// "items": [ + /// { + /// "labelName": "Chicken Salad", + /// "labelCategoryId": "cat-id", + /// "labelTypeId": "type-id", + /// "locationIds": ["location-id"], + /// "productIds": ["product-id"], + /// "appliedRegionType": "SPECIFIED", + /// "regionIds": ["group-id"], + /// "templateDataValues": { "el-text": "Fresh" }, + /// "templateDateOffsets": { "el-duration": { "unit": "Days", "value": "3" } } + /// } + /// ] + /// } + /// ``` + /// + /// 参数说明: + /// - templateCode: 所有行共用的模板编码 + /// - items: 导入行;字段与单条创建基本一致,另支持 templateDefaultValues / templateDataValues / templateDateOffsets / nutritionByElementId + /// - saveTemplateProductDefaults: 是否将各行模板数据合并写入 fl_label_template_product_default + /// + /// 批量导入入参 + /// 成功/失败统计与行级错误 + /// 导入完成(可能部分成功) + /// 入参非法或模板不存在 + /// 服务器错误 + [UnitOfWork] + public async Task BatchCreateAsync(LabelBatchCreateInputVo input) + { + if (input?.Items is null || input.Items.Count == 0) + { + throw new UserFriendlyException("批量导入行不能为空"); + } + + const int maxRows = 500; + if (input.Items.Count > maxRows) + { + throw new UserFriendlyException($"单次最多导入 {maxRows} 行"); + } + + var templateCode = input.TemplateCode?.Trim(); + if (string.IsNullOrWhiteSpace(templateCode)) + { + throw new UserFriendlyException("模板编码不能为空"); + } + + var db = _dbContext.SqlSugarClient; + var template = await LabelTemplateQueryHelper.QueryProjected(db) + .FirstAsync(x => !x.IsDeleted && x.TemplateCode == templateCode); + if (template is null) + { + throw new UserFriendlyException("模板不存在"); + } + + var templateElements = await LabelBatchTemplateDefaultsHelper.LoadTemplateElementsAsync(db, template.Id); + var existingDefaults = await db.Queryable() + .Where(x => x.TemplateId == template.Id) + .OrderBy(x => x.OrderNum) + .ToListAsync(); + var existingDefaultDtos = existingDefaults.Select(x => + { + object? defaults = null; + if (!string.IsNullOrWhiteSpace(x.DefaultValuesJson)) + { + defaults = JsonSerializer.Deserialize(x.DefaultValuesJson); + } + + return new LabelTemplateProductDefaultDto + { + ProductId = x.ProductId, + LabelTypeId = x.LabelTypeId, + DefaultValues = defaults, + OrderNum = x.OrderNum + }; + }).ToList(); + + var result = new LabelBatchCreateResultDto(); + var templateDefaultRows = new List<(string ProductId, string LabelTypeId, Dictionary DefaultValues)>(); + + for (var i = 0; i < input.Items.Count; i++) + { + var rowNumber = i + 1; + var item = input.Items[i]; + try + { + var createInput = MapBatchItemToCreateInput(item, templateCode); + var created = await CreateAsync(createInput); + result.SuccessCount++; + result.SuccessItems.Add(new LabelBatchCreateSuccessItemDto + { + RowNumber = rowNumber, + LabelCode = created.Id, + LabelName = created.LabelName + }); + + if (!input.SaveTemplateProductDefaults || !LabelBatchTemplateDefaultsHelper.HasTemplateDataInput(item)) + { + continue; + } + + var productId = item.ProductIds?.FirstOrDefault(x => !string.IsNullOrWhiteSpace(x))?.Trim(); + var labelTypeId = NormalizeOptionalLabelTypeId(item.LabelTypeId); + if (string.IsNullOrWhiteSpace(productId) || string.IsNullOrWhiteSpace(labelTypeId)) + { + continue; + } + + var product = await db.Queryable() + .FirstAsync(x => !x.IsDeleted && x.Id == productId); + var labelType = await db.Queryable() + .FirstAsync(x => !x.IsDeleted && x.Id == labelTypeId); + var codeValue = string.IsNullOrWhiteSpace(product?.CodeValue) + ? product?.ProductCode + : product!.CodeValue; + var defaultValues = LabelBatchTemplateDefaultsHelper.CollectDefaultValuesForItem( + templateElements, + item, + codeValue, + labelType?.TypeName); + if (defaultValues.Count > 0) + { + templateDefaultRows.Add((productId, labelTypeId, defaultValues)); + } + } + catch (UserFriendlyException ex) + { + result.FailCount++; + result.Errors.Add(new LabelBatchCreateErrorDto + { + RowNumber = rowNumber, + LabelName = item.LabelName, + Message = ex.Message + }); + } + } + + if (input.SaveTemplateProductDefaults && templateDefaultRows.Count > 0) + { + try + { + await LabelBatchTemplateDefaultsHelper.MergeAndSaveTemplateProductDefaultsAsync( + db, + _guidGenerator, + template.Id, + existingDefaultDtos, + templateDefaultRows); + } + catch (UserFriendlyException ex) + { + result.Errors.Add(new LabelBatchCreateErrorDto + { + RowNumber = 0, + Message = $"标签已创建,但模板默认值保存失败:{ex.Message}" + }); + } + } + + return result; + } + + private static LabelCreateInputVo MapBatchItemToCreateInput( + LabelBatchCreateItemInputVo item, + string templateCode) + { + return new LabelCreateInputVo + { + LabelCode = item.LabelCode, + LabelName = item.LabelName, + TemplateCode = templateCode, + PartnerId = item.PartnerId, + PartnerIds = item.PartnerIds, + AppliedRegionType = item.AppliedRegionType, + RegionIds = item.RegionIds, + GroupIds = item.GroupIds, + LocationIds = item.LocationIds, + LocationId = item.LocationId, + LabelCategoryId = item.LabelCategoryId, + LabelTypeId = item.LabelTypeId, + ProductIds = item.ProductIds ?? new List(), + LabelInfoJson = item.LabelInfoJson, + State = item.State + }; + } + [UnitOfWork] public async Task UpdateAsync(string id, LabelUpdateInputVo input) { diff --git a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/LabelCategoryAppService.cs b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/LabelCategoryAppService.cs index 4d6d0e8..1d03d06 100644 --- a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/LabelCategoryAppService.cs +++ b/美国版/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 var regionIds = NormalizeRegionIds(input); var explicitLocationIds = LocationScopeBindingHelper.NormalizeIds(input.LocationIds); - var availabilityType = (input.AvailabilityType ?? "ALL").Trim().ToUpperInvariant(); - var hasScopeArrays = input.RegionIds is not null || input.GroupIds is not null || input.LocationIds is not null; + + var partnerContext = string.Equals( + partnerScope.AppliedPartnerType, + LabelEntityPartnerScopeHelper.ScopeSpecified, + StringComparison.OrdinalIgnoreCase) + ? partnerScope.PartnerIds + : null; + + if (await AllScopeBindingHelper.ShouldTreatMergedLocationScopeAsAllAsync( + _dbContext.SqlSugarClient, + input.AvailabilityType, + regionIds, + explicitLocationIds, + hasScopeArrays, + partnerContext)) + { + return (partnerScope, "ALL", new List()); + } + + var availabilityType = (input.AvailabilityType ?? "ALL").Trim().ToUpperInvariant(); if (regionIds.Count > 0 || explicitLocationIds.Count > 0) { availabilityType = "SPECIFIED"; } - else if (hasScopeArrays && string.Equals(availabilityType, "ALL", StringComparison.OrdinalIgnoreCase)) + else if (hasScopeArrays && AllScopeBindingHelper.IsDeclaredAll(availabilityType)) { availabilityType = "ALL"; } diff --git a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/LabelMultipleOptionAppService.cs b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/LabelMultipleOptionAppService.cs index b68f5d9..2891a9c 100644 --- a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/LabelMultipleOptionAppService.cs +++ b/美国版/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 var regionIds = NormalizeRegionIds(input); var explicitLocationIds = LocationScopeBindingHelper.NormalizeIds(input.LocationIds); - var availabilityType = (input.AvailabilityType ?? "ALL").Trim().ToUpperInvariant(); - var hasScopeArrays = input.RegionIds is not null || input.GroupIds is not null || input.LocationIds is not null; + + var partnerContext = string.Equals( + partnerScope.AppliedPartnerType, + LabelEntityPartnerScopeHelper.ScopeSpecified, + StringComparison.OrdinalIgnoreCase) + ? partnerScope.PartnerIds + : null; + + if (await AllScopeBindingHelper.ShouldTreatMergedLocationScopeAsAllAsync( + _dbContext.SqlSugarClient, + input.AvailabilityType, + regionIds, + explicitLocationIds, + hasScopeArrays, + partnerContext)) + { + return (partnerScope, "ALL", new List()); + } + + var availabilityType = (input.AvailabilityType ?? "ALL").Trim().ToUpperInvariant(); if (regionIds.Count > 0 || explicitLocationIds.Count > 0) { availabilityType = "SPECIFIED"; } - else if (hasScopeArrays && string.Equals(availabilityType, "ALL", StringComparison.OrdinalIgnoreCase)) + else if (hasScopeArrays && AllScopeBindingHelper.IsDeclaredAll(availabilityType)) { availabilityType = "ALL"; } diff --git a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/LabelTypeAppService.cs b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/LabelTypeAppService.cs index 7501f05..c65ebda 100644 --- a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/LabelTypeAppService.cs +++ b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/LabelTypeAppService.cs @@ -252,14 +252,32 @@ public class LabelTypeAppService : ApplicationService, ILabelTypeAppService var regionIds = NormalizeRegionIds(input); var explicitLocationIds = LocationScopeBindingHelper.NormalizeIds(input.LocationIds); - var availabilityType = (input.AvailabilityType ?? "ALL").Trim().ToUpperInvariant(); - var hasScopeArrays = input.RegionIds is not null || input.GroupIds is not null || input.LocationIds is not null; + + var partnerContext = string.Equals( + partnerScope.AppliedPartnerType, + LabelEntityPartnerScopeHelper.ScopeSpecified, + StringComparison.OrdinalIgnoreCase) + ? partnerScope.PartnerIds + : null; + + if (await AllScopeBindingHelper.ShouldTreatMergedLocationScopeAsAllAsync( + _dbContext.SqlSugarClient, + input.AvailabilityType, + regionIds, + explicitLocationIds, + hasScopeArrays, + partnerContext)) + { + return (partnerScope, "ALL", new List()); + } + + var availabilityType = (input.AvailabilityType ?? "ALL").Trim().ToUpperInvariant(); if (regionIds.Count > 0 || explicitLocationIds.Count > 0) { availabilityType = "SPECIFIED"; } - else if (hasScopeArrays && string.Equals(availabilityType, "ALL", StringComparison.OrdinalIgnoreCase)) + else if (hasScopeArrays && AllScopeBindingHelper.IsDeclaredAll(availabilityType)) { availabilityType = "ALL"; } diff --git a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/ProductAppService.cs b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/ProductAppService.cs index 085edd5..e24d56c 100644 --- a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/ProductAppService.cs +++ b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/ProductAppService.cs @@ -97,6 +97,10 @@ public class ProductAppService : ApplicationService, IProductAppService locationIdsByProduct.TryGetValue(x.Id, out var locationIds); locationNameByProduct.TryGetValue(x.Id, out var locationName); + var isAllLocations = string.Equals( + x.AvailabilityType, + AllScopeBindingHelper.ScopeAll, + StringComparison.OrdinalIgnoreCase); return new ProductGetListOutputDto { @@ -111,9 +115,12 @@ public class ProductAppService : ApplicationService, IProductAppService ButtonAppearance = x.ButtonAppearance, CategoryPhotoUrl = x.CategoryPhotoUrl, State = x.State, + AvailabilityType = x.AvailabilityType, NoOfLabels = countMap.TryGetValue(x.Id, out var count) ? count : 0, - LocationIds = locationIds ?? new List(), - LocationName = string.IsNullOrWhiteSpace(locationName) ? "无" : locationName! + LocationIds = isAllLocations ? new List() : (locationIds ?? new List()), + LocationName = isAllLocations + ? AllScopeBindingHelper.AllLocationsDisplay + : (string.IsNullOrWhiteSpace(locationName) ? "无" : locationName!) }; }).ToList(); @@ -152,10 +159,18 @@ public class ProductAppService : ApplicationService, IProductAppService .Where(x => x.ProductId == productId) .Select(x => x.LocationId) .ToListAsync()); - var partnerIds = await LocationScopeBindingHelper.ResolvePartnerIdsFromLocationIdsAsync( - _dbContext.SqlSugarClient, locationIds); - var groupIds = await LocationScopeBindingHelper.ResolveGroupIdsFromLocationIdsAsync( - _dbContext.SqlSugarClient, locationIds); + var isAllLocations = string.Equals( + entity.AvailabilityType, + AllScopeBindingHelper.ScopeAll, + StringComparison.OrdinalIgnoreCase); + var partnerIds = isAllLocations + ? new List() + : await LocationScopeBindingHelper.ResolvePartnerIdsFromLocationIdsAsync( + _dbContext.SqlSugarClient, locationIds); + var groupIds = isAllLocations + ? new List() + : await LocationScopeBindingHelper.ResolveGroupIdsFromLocationIdsAsync( + _dbContext.SqlSugarClient, locationIds); return new ProductGetOutputDto { @@ -170,10 +185,11 @@ public class ProductAppService : ApplicationService, IProductAppService ButtonAppearance = entity.ButtonAppearance, CategoryPhotoUrl = entity.CategoryPhotoUrl, State = entity.State, + AvailabilityType = entity.AvailabilityType, PartnerId = partnerIds.Count > 0 ? partnerIds[0] : null, PartnerIds = partnerIds, GroupIds = groupIds, - LocationIds = locationIds + LocationIds = isAllLocations ? new List() : locationIds }; } @@ -213,12 +229,14 @@ public class ProductAppService : ApplicationService, IProductAppService }; ApplyProductAppearanceToEntity(entity, input); + var (availabilityType, locationIds) = await ResolveProductScopeForSaveAsync(input); + entity.AvailabilityType = availabilityType; + await _dbContext.SqlSugarClient.Insertable(entity).ExecuteCommandAsync(); - if (HasProductScopeBinding(input)) + if (ShouldPersistProductScope(input)) { - var locIds = await ResolveProductLocationIdsForSaveAsync(input); - await ReplaceProductLocationLinksAsync(entity.Id, locIds); + await ReplaceProductLocationLinksAsync(entity.Id, locationIds); } return await GetAsync(Guid.Parse(entity.Id)); @@ -270,12 +288,14 @@ public class ProductAppService : ApplicationService, IProductAppService entity.State = input.State; ApplyProductAppearanceToEntity(entity, input); + var (availabilityType, locationIds) = await ResolveProductScopeForSaveAsync(input); + entity.AvailabilityType = availabilityType; + await _dbContext.SqlSugarClient.Updateable(entity).ExecuteCommandAsync(); - if (HasProductScopeBinding(input)) + if (ShouldPersistProductScope(input)) { - var locIds = await ResolveProductLocationIdsForSaveAsync(input); - await ReplaceProductLocationLinksAsync(productId, locIds); + await ReplaceProductLocationLinksAsync(productId, locationIds); } return await GetAsync(id); @@ -517,10 +537,23 @@ public class ProductAppService : ApplicationService, IProductAppService } else { - query = query.Where(p => - SqlFunc.Subqueryable() - .Where(lp => lp.ProductId == p.Id && locationIds.Contains(lp.LocationId)) - .Any()); + var hasAvailabilityColumn = await ProductScopeSchemaHelper.HasAvailabilityTypeColumnAsync( + _dbContext.SqlSugarClient); + if (hasAvailabilityColumn) + { + query = query.Where(p => + p.AvailabilityType == AllScopeBindingHelper.ScopeAll + || SqlFunc.Subqueryable() + .Where(lp => lp.ProductId == p.Id && locationIds.Contains(lp.LocationId)) + .Any()); + } + else + { + query = query.Where(p => + SqlFunc.Subqueryable() + .Where(lp => lp.ProductId == p.Id && locationIds.Contains(lp.LocationId)) + .Any()); + } } } @@ -834,6 +867,40 @@ public class ProductAppService : ApplicationService, IProductAppService input.GroupIds is not null || input.LocationIds is not null; + private static bool ShouldPersistProductScope(ProductCreateInputVo input) => + HasProductScopeBinding(input) || !string.IsNullOrWhiteSpace(input.AvailabilityType); + + /// + /// 解析产品门店范围:ALL 时不写 fl_location_product 快照,后续新增门店自动可见。 + /// + private async Task<(string AvailabilityType, List LocationIds)> ResolveProductScopeForSaveAsync( + ProductCreateInputVo input) + { + if (!ShouldPersistProductScope(input)) + { + return (AllScopeBindingHelper.ScopeSpecified, new List()); + } + + if (await AllScopeBindingHelper.ShouldTreatProductLocationScopeAsAllAsync( + _dbContext.SqlSugarClient, + input.AvailabilityType, + input.PartnerId, + input.GroupIds, + input.LocationIds, + HasProductScopeBinding(input))) + { + return (AllScopeBindingHelper.ScopeAll, new List()); + } + + if (!HasProductScopeBinding(input)) + { + return (AllScopeBindingHelper.ScopeSpecified, new List()); + } + + var locIds = await ResolveProductLocationIdsForSaveAsync(input); + return (AllScopeBindingHelper.ScopeSpecified, locIds); + } + /// /// 合并 Company(partnerId)、Region(groupIds)、门店(locationIds)并校验存在性。 /// diff --git a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/ProductCategoryAppService.cs b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/ProductCategoryAppService.cs index c39f1d4..f983253 100644 --- a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/ProductCategoryAppService.cs +++ b/美国版/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 { var regionIds = NormalizeRegionIds(input); var explicitLocationIds = LocationScopeBindingHelper.NormalizeIds(input.LocationIds); - var availabilityType = (input.AvailabilityType ?? "ALL").Trim().ToUpperInvariant(); - var hasScopeArrays = input.RegionIds is not null || input.GroupIds is not null || input.LocationIds is not null; + + if (await AllScopeBindingHelper.ShouldTreatMergedLocationScopeAsAllAsync( + _dbContext.SqlSugarClient, + input.AvailabilityType, + regionIds, + explicitLocationIds, + hasScopeArrays, + null)) + { + return ("ALL", new List()); + } + + var availabilityType = (input.AvailabilityType ?? "ALL").Trim().ToUpperInvariant(); if (regionIds.Count > 0 || explicitLocationIds.Count > 0) { availabilityType = "SPECIFIED"; } - else if (hasScopeArrays && string.Equals(availabilityType, "ALL", StringComparison.OrdinalIgnoreCase)) + else if (hasScopeArrays && AllScopeBindingHelper.IsDeclaredAll(availabilityType)) { - // 显式传了空数组 [] 表示清空指定范围,仍视为 SPECIFIED(0 门店)或改回 ALL availabilityType = "ALL"; } @@ -343,8 +353,9 @@ public class ProductCategoryAppService : ApplicationService, IProductCategoryApp return query.Where(_ => false); } - // 非平台管理员:仅返回绑定门店与可见范围有交集的分类(不再因 AvailabilityType=ALL 暴露其它公司数据) + // 非平台管理员:绑定门店与可见范围有交集,或 AvailabilityType=ALL(动态包含后续新增门店) return query.Where(c => + c.AvailabilityType == "ALL" || SqlFunc.Subqueryable() .Where(cl => cl.CategoryId == c.Id && scopedLocationIds.Contains(cl.LocationId)) .Any()); @@ -372,6 +383,11 @@ public class ProductCategoryAppService : ApplicationService, IProductCategoryApp throw new UserFriendlyException("无权访问该类别"); } + if (string.Equals(entity.AvailabilityType, "ALL", StringComparison.OrdinalIgnoreCase)) + { + return; + } + var visible = await _dbContext.SqlSugarClient.Queryable() .AnyAsync(cl => cl.CategoryId == entity.Id && scopedLocationIds.Contains(cl.LocationId)); if (!visible) diff --git a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/UsAppLabelingAppService.cs b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/UsAppLabelingAppService.cs index 8606243..d5e3cc7 100644 --- a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/UsAppLabelingAppService.cs +++ b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/UsAppLabelingAppService.cs @@ -78,6 +78,18 @@ public class UsAppLabelingAppService : ApplicationService, IUsAppLabelingAppServ .Select(x => x.ProductId) .ToListAsync(); + if (await ProductScopeSchemaHelper.HasAvailabilityTypeColumnAsync(_dbContext.SqlSugarClient)) + { + var allScopeProductIds = await _dbContext.SqlSugarClient.Queryable() + .Where(x => !x.IsDeleted && x.State && x.AvailabilityType == AllScopeBindingHelper.ScopeAll) + .Select(x => x.Id) + .ToListAsync(); + productIds = productIds + .Concat(allScopeProductIds) + .Distinct(StringComparer.Ordinal) + .ToList(); + } + if (productIds.Count == 0) { return new List(); diff --git a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/scripts/fl_product_availability.sql b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/scripts/fl_product_availability.sql new file mode 100644 index 0000000..53eb50b --- /dev/null +++ b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/scripts/fl_product_availability.sql @@ -0,0 +1,17 @@ +-- 产品适用门店:ALL / SPECIFIED(ALL 时动态包含后续新增门店,不写 fl_location_product 快照) +-- 可重复执行 + +SET @db := DATABASE(); + +SET @col_product_availability := ( + SELECT COUNT(*) FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 'fl_product' AND COLUMN_NAME = 'AvailabilityType' +); +SET @ddl_product_availability := IF( + @col_product_availability = 0, + 'ALTER TABLE `fl_product` ADD COLUMN `AvailabilityType` varchar(20) NOT NULL DEFAULT ''SPECIFIED'' COMMENT ''适用门店:ALL/SPECIFIED'' AFTER `State`', + 'SELECT 1' +); +PREPARE stmt_product_availability FROM @ddl_product_availability; +EXECUTE stmt_product_availability; +DEALLOCATE PREPARE stmt_product_availability; diff --git a/项目相关文档/2026-07-09代码修改.md b/项目相关文档/2026-07-09代码修改.md new file mode 100644 index 0000000..c63fb8f --- /dev/null +++ b/项目相关文档/2026-07-09代码修改.md @@ -0,0 +1,286 @@ +# 2026-07-09 代码修改 + +本文档说明 **2026-07-09** 对美国版标签(Label)模块的接口补充:**标签列表**与**批量导入**(Bulk Add Labels)。 + +--- + +## 一、背景与目标 + +| 项目 | 说明 | +|------|------| +| 业务场景 | Web 管理端 **Bulk Add Labels** 页面:同一模板下多行录入标签基本字段 + 模板数据字段后一次性保存 | +| 原行为 | 前端 `LabelsList.tsx` 对每行循环调用 `POST /api/app/label` 单条创建,模板数据再单独 `updateLabelTemplate` | +| 新行为 | 新增 `POST /api/app/label/batch-create`,一次提交多行;可选合并写入 `fl_label_template_product_default` | +| 列表接口 | `GET /api/app/label?SkipCount=1&MaxResultCount=10` 为标签分页列表(按标签维度分页,非 label-product 笛卡尔行) | + +--- + +## 二、标签列表 + +### 基本信息 + +| 项目 | 内容 | +|------|------| +| 方法 | `GET` | +| 路径 | `/api/app/label` | +| 鉴权 | Bearer Token | +| 示例 | `/api/app/label?SkipCount=1&MaxResultCount=10` | + +### 分页参数 + +| 参数 | 类型 | 说明 | +|------|------|------| +| `SkipCount` | `int` | 页码,**从 1 起**(非 0) | +| `MaxResultCount` | `int` | 每页条数 | + +### 筛选参数(Query) + +| 参数 | 说明 | +|------|------| +| `PartnerId` | 按 Company(`fl_partner.Id`)下门店集合筛选 | +| `GroupId` | 按 Region(`fl_group.Id`)筛选:命中 `fl_label_region`、`fl_label_location` 或 `AppliedRegionType=ALL` | +| `LocationId` | 按门店(`location.Id`)筛选;传则优先于 `GroupId` | +| `ProductId` | 按产品筛选(一个产品可对应多个标签) | +| `Keyword` | 关键词 | +| `LabelCategoryId` | 标签分类 | +| `LabelTypeId` | 标签类型(可选) | +| `TemplateCode` | 模板编码 | +| `State` | 启用状态 | + +### 出参结构 + +```json +{ + "pageIndex": 1, + "pageSize": 10, + "totalCount": 100, + "totalPages": 10, + "items": [ + { + "id": "LBL_xxx", + "labelName": "Turkey Breast", + "locationName": "Store A, Store B", + "locationIds": ["loc-id-1", "loc-id-2"], + "region": "Region A", + "regionIds": ["group-id-1"], + "groupIds": ["group-id-1"], + "appliedRegionType": "SPECIFIED", + "labelCategoryName": "Prep", + "productCategoryName": "Meat", + "products": "Turkey Breast", + "templateName": "3\"x6\" Nutrition Details", + "templateCode": "tpl_229mx5_mr05n3cq", + "labelTypeName": "Use By", + "state": true, + "lastEdited": "2026-07-09T10:00:00", + "hasError": false + } + ] +} +``` + +### 列表 curl 示例 + +```bash +# 登录(管理端) +curl -X POST "http://192.168.31.88:19001/api/app/account/login" \ + -H "Content-Type: application/json" \ + -d '{"userName":"sandi@123.com","password":"123456"}' + +# 标签列表第一页(10 条) +curl -G "http://192.168.31.88:19001/api/app/label" \ + -H "Authorization: Bearer {token}" \ + --data-urlencode "SkipCount=1" \ + --data-urlencode "MaxResultCount=10" +``` + +--- + +## 三、标签批量导入 + +### 基本信息 + +| 项目 | 内容 | +|------|------| +| 方法 | `POST` | +| 路径 | `/api/app/label/batch-create` | +| 鉴权 | Bearer Token | +| 对应页面 | Web 端 **Bulk Add Labels**(`LabelsList.tsx` → `LabelBulkAddPage`) | +| 单次上限 | 500 行 | + +### Body 顶层字段 + +| 字段 | 类型 | 必填 | 说明 | +|------|------|------|------| +| `templateCode` | `string` | 是 | 所有行共用的模板编码 | +| `items` | `array` | 是 | 导入行列表 | +| `saveTemplateProductDefaults` | `bool` | 否 | 是否合并写入模板 ProductDefaults,默认 `true` | + +### `items[]` 每行字段 + +#### 标签基本字段(与单条 `POST /api/app/label` 一致) + +| 字段 | 类型 | 必填 | 说明 | +|------|------|------|------| +| `labelName` | `string` | 是 | 标签名称 | +| `labelCategoryId` | `string` | 是 | 标签分类 Id | +| `labelTypeId` | `string` | 建议 | 标签类型 Id | +| `productIds` | `string[]` | 是 | 至少 1 个产品 | +| `locationIds` | `string[]` | 建议 | 适用门店(主字段) | +| `locationId` | `string` | 否 | 兼容单门店,与 `locationIds` 合并 | +| `appliedRegionType` | `string` | 否 | `ALL` / `SPECIFIED` | +| `regionIds` / `groupIds` | `string[]` | 条件 | `SPECIFIED` 时传 Region | +| `partnerId` / `partnerIds` | `string` / `string[]` | 否 | Company 范围 | +| `labelCode` | `string` | 否 | 不传则自动生成 `LBL_{guid}` | +| `labelInfoJson` | `object` | 否 | 标签级模板 JSON(通常走 ProductDefaults) | +| `state` | `bool` | 否 | 默认 `true` | + +#### 模板数据字段(对应 Bulk Add 表格列) + +| 字段 | 类型 | 说明 | +|------|------|------| +| `templateDefaultValues` | `object` | 已组装的 elementId → 值;**优先使用**,不再从下方字段推导 | +| `templateDataValues` | `object` | 文本类录入(如 Text、Barcode 手填值) | +| `templateDateOffsets` | `object` | 日期/时间/时长:`{ "el-id": { "unit": "Days", "value": "3" } }` | +| `nutritionByElementId` | `object` | 营养成分:`{ "el-nutrition": { "calories": "120" } }` | + +**模板数据落库规则** + +- `saveTemplateProductDefaults=true` 时:按 `productId + labelTypeId` 合并写入 `fl_label_template_product_default`(与前端 `saveTemplateDefaultsAfterLabels` 一致) +- 日期偏移存为 JSON 字符串:`{"unit":"Days","value":"3"}` +- Template 面板条码/二维码自动填充产品 `codeValue`;Label Name / Label Type 自动绑定行内 `labelName`、类型名 + +### 请求示例 + +```json +{ + "templateCode": "tpl_229mx5_mr05n3cq", + "saveTemplateProductDefaults": true, + "items": [ + { + "labelName": "Chicken Salad", + "labelCategoryId": "3a2228ca-42fa-5273-1105-3d8252ffdd99", + "labelTypeId": "3a2228e5-33c5-278e-a09f-47fd6e2ddbc7", + "locationIds": ["3a222878-b4c1-d27b-d437-93da14886350"], + "productIds": ["3a2228a8-6a51-6cc4-fee2-b77769766b33"], + "appliedRegionType": "SPECIFIED", + "regionIds": [], + "templateDataValues": { + "el-1782794752668-0gixa9y": "Fresh batch text", + "el-1782794771519-4360c0p": "123456789" + }, + "templateDateOffsets": { + "el-1782794481721-sdf7mvy": { "unit": "Days", "value": "3" } + }, + "state": true + }, + { + "labelName": "Turkey Wrap", + "labelCategoryId": "3a2228ca-42fa-5273-1105-3d8252ffdd99", + "labelTypeId": "3a2228e6-3ed0-b056-a08b-ea8b1eea46a0", + "locationIds": ["3a222878-b4c1-d27b-d437-93da14886350"], + "productIds": ["3a2228a8-6a51-6cc4-fee2-b77769766b33"], + "templateDataValues": { + "el-1782794752668-0gixa9y": "Ready to serve" + }, + "templateDateOffsets": { + "el-1782794481721-sdf7mvy": { "unit": "Days", "value": "5" } + } + } + ] +} +``` + +### 响应示例 + +```json +{ + "successCount": 2, + "failCount": 0, + "successItems": [ + { "rowNumber": 1, "labelCode": "LBL_abc...", "labelName": "Chicken Salad" }, + { "rowNumber": 2, "labelCode": "LBL_def...", "labelName": "Turkey Wrap" } + ], + "errors": [] +} +``` + +**部分成功示例**(第 2 行校验失败、第 1 行仍创建): + +```json +{ + "successCount": 1, + "failCount": 1, + "successItems": [ + { "rowNumber": 1, "labelCode": "LBL_abc...", "labelName": "Chicken Salad" } + ], + "errors": [ + { "rowNumber": 2, "labelName": "", "message": "标签名称不能为空" } + ] +} +``` + +### 批量导入 curl 示例 + +```bash +curl -X POST "http://192.168.31.88:19001/api/app/label/batch-create" \ + -H "Authorization: Bearer {token}" \ + -H "Content-Type: application/json" \ + -d '{ + "templateCode": "tpl_229mx5_mr05n3cq", + "saveTemplateProductDefaults": true, + "items": [ + { + "labelName": "Batch Test", + "labelCategoryId": "3a2228ca-42fa-5273-1105-3d8252ffdd99", + "labelTypeId": "3a2228e5-33c5-278e-a09f-47fd6e2ddbc7", + "locationIds": ["3a222878-b4c1-d27b-d437-93da14886350"], + "productIds": ["3a2228a8-6a51-6cc4-fee2-b77769766b33"], + "templateDataValues": { "el-1782794752668-0gixa9y": "Fresh" }, + "templateDateOffsets": { "el-1782794481721-sdf7mvy": { "unit": "Days", "value": "3" } } + } + ] + }' +``` + +--- + +## 四、与单条创建对比 + +| 能力 | `POST /api/app/label` | `POST /api/app/label/batch-create` | +|------|----------------------|-----------------------------------| +| 行数 | 1 条 | 最多 500 条 | +| 模板编码 | 每 Body 自带 | 顶层 `templateCode` 共用 | +| 模板数据 | 仅 `labelInfoJson` | 支持结构化模板字段 + ProductDefaults 合并 | +| 失败处理 | 整请求失败 | 行级错误收集,支持部分成功 | +| 返回值 | 标签详情 DTO | `successCount` / `failCount` / `errors` / `successItems` | + +--- + +## 五、代码改动摘要 + +| 文件 | 改动 | +|------|------| +| `ILabelAppService.cs` | 新增 `BatchCreateAsync` | +| `LabelAppService.cs` | 实现批量导入;逐行复用 `CreateAsync`;可选合并模板 ProductDefaults | +| `LabelBatchCreateInputVo.cs` | 批量入参 DTO | +| `LabelBatchCreateItemInputVo.cs` | 单行(基本字段 + 模板数据字段) | +| `LabelBatchDateOffsetInputVo.cs` | 日期偏移单位+数值 | +| `LabelBatchCreateResultDto.cs` | 批量结果 DTO | +| `LabelBatchTemplateDefaultsHelper.cs` | 组装/合并模板 ProductDefaults | + +--- + +## 六、部署与联调注意 + +1. `dotnet build` 编译 `FoodLabeling.Application` 与 `Yi.Abp.Web` 后**重启 API 进程**(未重启时 `batch-create` 会返回 405) +2. 管理端登录:`POST /api/app/account/login`(非 `/api/oauth/Login`) +3. 本地 Base URL 以 `appsettings.json` 中 `App:SelfUrl` 为准(当前示例为 `http://192.168.31.88:19001`) +4. 前端 `LabelsList.tsx` 的 `submit()` 仍循环调单条 `createLabel`;对接批量接口时需改为调用 `batch-create` + +--- + +## 七、相关文档 + +- 标签多门店 `locationIds`:`项目相关文档/6-23代码优化.md` +- 模板三维 scope:`项目相关文档/6-4代码优化.md`