LabelRegionScopeHelper.cs 13.5 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
using FoodLabeling.Application.Services.DbModels;
using SqlSugar;
using Volo.Abp;

namespace FoodLabeling.Application.Helpers;

/// <summary>
/// 标签适用 Region(<c>fl_group.Id</c>)范围:保存、展示、列表筛选与 App 门店校验。
/// </summary>
public static class LabelRegionScopeHelper
{
    public const string AppliedTypeAll = "ALL";
    public const string AppliedTypeSpecified = "SPECIFIED";
    public const string AllRegionsDisplay = "All Regions";
    private const string EmptyDisplay = "无";

    public sealed class LabelRegionScopeData
    {
        public string AppliedRegionType { get; init; } = AppliedTypeSpecified;

        public string Region { get; init; } = string.Empty;

        public List<string> RegionIds { get; init; } = new();
    }

    /// <summary>
    /// 读取标签绑定的 Region Id 列表。
    /// </summary>
    public static async Task<List<string>> LoadRegionIdsAsync(ISqlSugarClient db, string labelId)
    {
        var lid = labelId?.Trim();
        if (string.IsNullOrWhiteSpace(lid))
        {
            return new List<string>();
        }

        return await db.Queryable<FlLabelRegionDbEntity>()
            .Where(x => x.LabelId == lid)
            .Select(x => x.GroupId)
            .ToListAsync();
    }

    /// <summary>
    /// 批量读取标签 Region Id(按 LabelId 分组)。
    /// </summary>
    public static async Task<Dictionary<string, List<string>>> LoadRegionIdsMapAsync(
        ISqlSugarClient db,
        IReadOnlyList<string> labelIds)
    {
        var ids = LocationScopeBindingHelper.NormalizeIds(labelIds);
        var result = ids.ToDictionary(x => x, _ => new List<string>(), StringComparer.Ordinal);
        if (ids.Count == 0)
        {
            return result;
        }

        var rows = await db.Queryable<FlLabelRegionDbEntity>()
            .Where(x => ids.Contains(x.LabelId))
            .ToListAsync();

        foreach (var row in rows)
        {
            if (string.IsNullOrWhiteSpace(row.LabelId) || string.IsNullOrWhiteSpace(row.GroupId))
            {
                continue;
            }

            if (!result.TryGetValue(row.LabelId, out var list))
            {
                list = new List<string>();
                result[row.LabelId] = list;
            }

            if (!list.Contains(row.GroupId, StringComparer.Ordinal))
            {
                list.Add(row.GroupId.Trim());
            }
        }

        foreach (var key in result.Keys.ToList())
        {
            result[key] = result[key].OrderBy(x => x, StringComparer.Ordinal).ToList();
        }

        return result;
    }

    /// <summary>
    /// 先删后插保存标签 Region 绑定;<c>ALL</c> 时仅删除关联行。
    /// </summary>
    public static async Task SaveRegionIdsAsync(
        ISqlSugarClient db,
        string labelId,
        string appliedRegionType,
        IReadOnlyList<string> regionIds,
        string? creatorId,
        DateTime now,
        Func<string> idGenerator)
    {
        var lid = labelId?.Trim();
        if (string.IsNullOrWhiteSpace(lid))
        {
            return;
        }

        await db.Deleteable<FlLabelRegionDbEntity>()
            .Where(x => x.LabelId == lid)
            .ExecuteCommandAsync();

        if (!string.Equals(appliedRegionType, AppliedTypeSpecified, StringComparison.OrdinalIgnoreCase))
        {
            return;
        }

        var groupIds = LocationScopeBindingHelper.NormalizeIds(regionIds);
        if (groupIds.Count == 0)
        {
            return;
        }

        var rows = groupIds.Select(gid => new FlLabelRegionDbEntity
        {
            Id = idGenerator(),
            LabelId = lid,
            GroupId = gid,
            CreationTime = now,
            CreatorId = creatorId
        }).ToList();

        await db.Insertable(rows).ExecuteCommandAsync();
    }

    /// <summary>
    /// 解析保存入参:ALL/SPECIFIED、Region Id 列表与唯一 <c>location.Id</c>。
    /// </summary>
    public static async Task<(string AppliedRegionType, List<string> RegionIds, string LocationId)> ResolveScopeForSaveAsync(
        ISqlSugarClient db,
        string? appliedRegionType,
        IReadOnlyList<string>? regionIds,
        IReadOnlyList<string>? groupIds,
        string? locationId,
        IReadOnlyList<string>? locationIds,
        IReadOnlyList<string>? partnerIds)
    {
        var normalizedRegionIds = MergeRegionIds(regionIds, groupIds);
        var explicitLocationId = locationId?.Trim();
        var explicitLocationIds = LocationScopeBindingHelper.NormalizeIds(locationIds);
        var type = (appliedRegionType ?? AppliedTypeSpecified).Trim().ToUpperInvariant();

        if (normalizedRegionIds.Count > 0)
        {
            type = AppliedTypeSpecified;
        }

        if (normalizedRegionIds.Count == 0 &&
            (!string.IsNullOrWhiteSpace(explicitLocationId) || explicitLocationIds.Count > 0))
        {
            var locIdsForRegion = new List<string>();
            if (!string.IsNullOrWhiteSpace(explicitLocationId))
            {
                locIdsForRegion.Add(explicitLocationId);
            }

            locIdsForRegion.AddRange(explicitLocationIds);
            normalizedRegionIds = await LocationScopeBindingHelper.ResolveGroupIdsFromLocationIdsAsync(
                db, locIdsForRegion);
            if (normalizedRegionIds.Count > 0)
            {
                type = AppliedTypeSpecified;
            }
        }

        if (type != AppliedTypeAll && type != AppliedTypeSpecified)
        {
            throw new UserFriendlyException("适用Region范围不合法(ALL/SPECIFIED)");
        }

        if (type == AppliedTypeAll)
        {
            var resolvedLoc = explicitLocationId;
            if (string.IsNullOrWhiteSpace(resolvedLoc) && explicitLocationIds.Count == 1)
            {
                resolvedLoc = explicitLocationIds[0];
            }
            else if (string.IsNullOrWhiteSpace(resolvedLoc) && explicitLocationIds.Count > 1)
            {
                throw new UserFriendlyException("全选 Region 时请显式指定 locationId,或仅选择一个门店");
            }

            if (!string.IsNullOrWhiteSpace(resolvedLoc))
            {
                await LocationScopeBindingHelper.ValidateLocationIdsExistAsync(
                    db, new List<string> { resolvedLoc });
            }

            return (AppliedTypeAll, new List<string>(), resolvedLoc ?? string.Empty);
        }

        if (normalizedRegionIds.Count == 0 &&
            string.IsNullOrWhiteSpace(explicitLocationId) &&
            explicitLocationIds.Count == 0)
        {
            throw new UserFriendlyException("请选择适用 Region");
        }

        await ValidateGroupIdsExistAsync(db, normalizedRegionIds);

        var mergedLocations = await LocationScopeBindingHelper.MergeToLocationIdsAsync(
            db, partnerIds, normalizedRegionIds, explicitLocationIds);

        if (!string.IsNullOrWhiteSpace(explicitLocationId))
        {
            if (mergedLocations.Count > 0 &&
                !mergedLocations.Contains(explicitLocationId, StringComparer.Ordinal))
            {
                throw new UserFriendlyException("所选门店不在指定 Region 范围内");
            }

            await LocationScopeBindingHelper.ValidateLocationIdsExistAsync(
                db, new List<string> { explicitLocationId });
            return (AppliedTypeSpecified, normalizedRegionIds, explicitLocationId);
        }

        if (mergedLocations.Count == 0)
        {
            throw new UserFriendlyException("指定适用 Region 时,至少需要匹配到一个有效门店");
        }

        return (AppliedTypeSpecified, normalizedRegionIds, mergedLocations[0]);
    }

    /// <summary>
    /// 列表筛选:按 Region Id 过滤,命中 <c>fl_label_region</c> 或 <c>AppliedRegionType=ALL</c>。
    /// </summary>
    public static ISugarQueryable<FlLabelDbEntity> ApplyGroupIdListFilter(
        ISugarQueryable<FlLabelDbEntity> query,
        string groupId)
    {
        var gid = groupId?.Trim();
        if (string.IsNullOrWhiteSpace(gid))
        {
            return query;
        }

        return query.Where(l =>
            l.AppliedRegionType == AppliedTypeAll ||
            SqlFunc.Subqueryable<FlLabelRegionDbEntity>()
                .Where(lr => lr.LabelId == l.Id && lr.GroupId == gid)
                .Any());
    }

    /// <summary>
    /// App 树/预览:判断标签是否适用于指定门店(ALL 或 Region 命中当前门店所属 Region)。
    /// </summary>
    public static async Task<bool> LabelAppliesToLocationAsync(
        ISqlSugarClient db,
        FlLabelDbEntity label,
        string locationId)
    {
        if (label is null)
        {
            return false;
        }

        if (string.Equals(label.AppliedRegionType, AppliedTypeAll, StringComparison.OrdinalIgnoreCase))
        {
            return true;
        }

        var locId = locationId?.Trim();
        if (string.IsNullOrWhiteSpace(locId))
        {
            return false;
        }

        var groupIds = await LocationScopeBindingHelper.ResolveGroupIdsFromLocationIdsAsync(
            db, new List<string> { locId });
        if (groupIds.Count == 0)
        {
            return false;
        }

        var regionLinks = await db.Queryable<FlLabelRegionDbEntity>()
            .Where(x => x.LabelId == label.Id)
            .Select(x => x.GroupId)
            .ToListAsync();

        return regionLinks.Any(gid => groupIds.Contains(gid, StringComparer.Ordinal));
    }

    /// <summary>
    /// 构建列表/详情 Region 展示字段。
    /// </summary>
    public static async Task<Dictionary<string, LabelRegionScopeData>> BuildRegionScopeMapAsync(
        ISqlSugarClient db,
        IReadOnlyList<(string Id, string AppliedRegionType)> labels)
    {
        var result = new Dictionary<string, LabelRegionScopeData>(StringComparer.Ordinal);
        if (labels.Count == 0)
        {
            return result;
        }

        foreach (var item in labels.Where(x =>
                     string.Equals(x.AppliedRegionType, AppliedTypeAll, StringComparison.OrdinalIgnoreCase)))
        {
            result[item.Id] = new LabelRegionScopeData
            {
                AppliedRegionType = AppliedTypeAll,
                Region = AllRegionsDisplay,
                RegionIds = new List<string>()
            };
        }

        var specifiedIds = labels
            .Where(x => string.Equals(x.AppliedRegionType, AppliedTypeSpecified, StringComparison.OrdinalIgnoreCase))
            .Select(x => x.Id)
            .ToList();
        if (specifiedIds.Count == 0)
        {
            return result;
        }

        var regionMap = await LoadRegionIdsMapAsync(db, specifiedIds);
        var allGroupIds = regionMap.Values.SelectMany(x => x).Distinct(StringComparer.Ordinal).ToList();
        var groupNameMap = new Dictionary<string, string>(StringComparer.Ordinal);
        if (allGroupIds.Count > 0)
        {
            var groups = await db.Queryable<FlGroupDbEntity>()
                .Where(x => !x.IsDeleted && allGroupIds.Contains(x.Id))
                .ToListAsync();
            foreach (var g in groups)
            {
                if (!string.IsNullOrWhiteSpace(g.Id))
                {
                    groupNameMap[g.Id] = g.GroupName?.Trim() ?? EmptyDisplay;
                }
            }
        }

        foreach (var labelId in specifiedIds)
        {
            var regionIds = regionMap.TryGetValue(labelId, out var ids)
                ? ids
                : new List<string>();

            if (regionIds.Count == 0)
            {
                result[labelId] = new LabelRegionScopeData
                {
                    AppliedRegionType = AppliedTypeSpecified,
                    Region = EmptyDisplay,
                    RegionIds = new List<string>()
                };
                continue;
            }

            var names = regionIds
                .Select(id => groupNameMap.TryGetValue(id, out var name) ? name : id)
                .Where(x => !string.IsNullOrWhiteSpace(x))
                .Distinct(StringComparer.OrdinalIgnoreCase)
                .OrderBy(x => x, StringComparer.OrdinalIgnoreCase)
                .ToList();

            result[labelId] = new LabelRegionScopeData
            {
                AppliedRegionType = AppliedTypeSpecified,
                Region = names.Count > 0 ? string.Join(", ", names) : EmptyDisplay,
                RegionIds = regionIds
            };
        }

        return result;
    }

    private static List<string> MergeRegionIds(
        IReadOnlyList<string>? regionIds,
        IReadOnlyList<string>? groupIds)
    {
        var merged = new HashSet<string>(StringComparer.Ordinal);
        foreach (var id in LocationScopeBindingHelper.NormalizeIds(regionIds))
        {
            merged.Add(id);
        }

        foreach (var id in LocationScopeBindingHelper.NormalizeIds(groupIds))
        {
            merged.Add(id);
        }

        return merged.OrderBy(x => x, StringComparer.Ordinal).ToList();
    }

    private static async Task ValidateGroupIdsExistAsync(ISqlSugarClient db, IReadOnlyList<string> groupIds)
    {
        var ids = LocationScopeBindingHelper.NormalizeIds(groupIds);
        if (ids.Count == 0)
        {
            return;
        }

        var existCount = await db.Queryable<FlGroupDbEntity>()
            .Where(x => !x.IsDeleted && ids.Contains(x.Id))
            .CountAsync();
        if (existCount != ids.Count)
        {
            throw new UserFriendlyException("Region 不存在");
        }
    }
}