LabelRegionScopeHelper.cs 24.4 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 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740
using FoodLabeling.Application.Services.DbModels;
using FoodLabeling.Domain.Entities;
using SqlSugar;
using Volo.Abp;
using Volo.Abp.Guids;

namespace FoodLabeling.Application.Helpers;

/// <summary>
/// ?? Region?<c>fl_group.Id</c>????? <c>fl_label_location</c> ???????????????
/// </summary>
public static class LabelRegionScopeHelper
{
    public const string AppliedRegionAll = "ALL";

    public const string AppliedRegionSpecified = "SPECIFIED";

    public const string AllRegionsDisplay = "All Regions";

    public const string AllLocationsDisplay = "All Locations";

    public sealed class LabelRegionScopeSaveResult
    {
        public string AppliedRegionType { get; init; } = AppliedRegionSpecified;

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

        /// <summary>???? Id ???<c>location.Id</c>???? <c>fl_label_location</c>?</summary>
        public List<string> LocationIds { get; init; } = new();

        /// <summary>?? <c>fl_label.LocationId</c>?? <see cref="LocationIds"/> ???</summary>
        public string? PrimaryLocationId => LocationIds.Count > 0 ? LocationIds[0] : null;
    }

    public sealed class LabelRegionScopeDisplay
    {
        public string Region { get; init; } = string.Empty;

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

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

    public sealed class LabelLocationScopeDisplay
    {
        public string Location { get; init; } = string.Empty;

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

    /// <summary>
    /// ??/????? Region ??? Id ???
    /// </summary>
    public static async Task<LabelRegionScopeSaveResult> ResolveScopeForSaveAsync(
        ISqlSugarClient db,
        string? appliedRegionType,
        IReadOnlyList<string>? regionIds,
        IReadOnlyList<string>? groupIds,
        string? locationId,
        IReadOnlyList<string>? locationIds)
    {
        var mergedRegionIds = NormalizeRegionIds(regionIds, groupIds);
        var type = (appliedRegionType ?? AppliedRegionAll).Trim().ToUpperInvariant();
        var hasScopeArrays = regionIds is not null || groupIds is not null || locationIds is not null;

        if (mergedRegionIds.Count > 0)
        {
            type = AppliedRegionSpecified;
        }
        else if (hasScopeArrays && string.Equals(type, AppliedRegionAll, StringComparison.OrdinalIgnoreCase))
        {
            type = AppliedRegionAll;
        }

        if (type != AppliedRegionAll && type != AppliedRegionSpecified)
        {
            throw new UserFriendlyException("?? Region ??????ALL/SPECIFIED?");
        }

        var explicitLocationIds = MergeExplicitLocationIds(locationId, locationIds);

        if (string.Equals(type, AppliedRegionAll, StringComparison.OrdinalIgnoreCase))
        {
            if (explicitLocationIds.Count > 0)
            {
                await LocationScopeBindingHelper.ValidateLocationIdsExistAsync(db, explicitLocationIds);
            }

            return new LabelRegionScopeSaveResult
            {
                AppliedRegionType = AppliedRegionAll,
                RegionIds = new List<string>(),
                LocationIds = explicitLocationIds
            };
        }

        if (mergedRegionIds.Count == 0 && explicitLocationIds.Count == 0)
        {
            throw new UserFriendlyException("??? Region?regionIds??/????locationIds?");
        }

        if (mergedRegionIds.Count > 0)
        {
            await ValidateRegionIdsExistAsync(db, mergedRegionIds);
        }

        var mergedLocations = await LocationScopeBindingHelper.MergeToLocationIdsAsync(
            db, (IReadOnlyList<string>?)null, mergedRegionIds, explicitLocationIds);

        if (mergedLocations.Count == 0)
        {
            throw new UserFriendlyException("? Region ???????????? Region ? locationIds");
        }

        if (explicitLocationIds.Count > 0)
        {
            var invalid = explicitLocationIds
                .Where(id => !mergedLocations.Contains(id, StringComparer.Ordinal))
                .ToList();
            if (invalid.Count > 0)
            {
                throw new UserFriendlyException("???????? Region ???");
            }
        }

        await LocationScopeBindingHelper.ValidateLocationIdsExistAsync(db, mergedLocations);

        return new LabelRegionScopeSaveResult
        {
            AppliedRegionType = AppliedRegionSpecified,
            RegionIds = mergedRegionIds,
            LocationIds = mergedLocations
        };
    }

    public static async Task SaveLabelRegionsAsync(
        ISqlSugarClient db,
        IGuidGenerator guidGenerator,
        string labelId,
        string appliedRegionType,
        IReadOnlyList<string> regionIds,
        string? currentUserId,
        DateTime now)
    {
        var schema = await LabelRegionSchemaHelper.GetStatusAsync(db);
        if (!schema.HasLabelRegionTable)
        {
            return;
        }

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

        if (!string.Equals(appliedRegionType, AppliedRegionSpecified, StringComparison.OrdinalIgnoreCase)
            || regionIds.Count == 0)
        {
            return;
        }

        var rows = regionIds.Select(gid => new FlLabelRegionDbEntity
        {
            Id = guidGenerator.Create().ToString(),
            LabelId = labelId,
            GroupId = gid,
            CreationTime = now,
            CreatorId = currentUserId
        }).ToList();

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

    /// <summary>????????? <c>fl_label_location</c>?</summary>
    public static async Task SaveLabelLocationsAsync(
        ISqlSugarClient db,
        IGuidGenerator guidGenerator,
        string labelId,
        IReadOnlyList<string> locationIds,
        string? currentUserId,
        DateTime now)
    {
        var schema = await LabelRegionSchemaHelper.GetStatusAsync(db);
        if (!schema.HasLabelLocationTable)
        {
            return;
        }

        await db.Deleteable<FlLabelLocationDbEntity>()
            .Where(x => x.LabelId == labelId)
            .ExecuteCommandAsync();

        if (locationIds.Count == 0)
        {
            return;
        }

        var rows = locationIds.Select(locId => new FlLabelLocationDbEntity
        {
            Id = guidGenerator.Create().ToString(),
            LabelId = labelId,
            LocationId = locId,
            CreationTime = now,
            CreatorId = currentUserId
        }).ToList();

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

    public static async Task<List<string>> GetRegionIdsForLabelAsync(ISqlSugarClient db, string labelId)
    {
        var schema = await LabelRegionSchemaHelper.GetStatusAsync(db);
        if (!schema.HasLabelRegionTable)
        {
            return new List<string>();
        }

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

    public static async Task<List<string>> GetLocationIdsForLabelAsync(
        ISqlSugarClient db,
        string labelId,
        string? fallbackLocationId)
    {
        var schema = await LabelRegionSchemaHelper.GetStatusAsync(db);
        if (schema.HasLabelLocationTable)
        {
            var ids = LocationScopeBindingHelper.NormalizeIds(
                await db.Queryable<FlLabelLocationDbEntity>()
                    .Where(x => x.LabelId == labelId)
                    .Select(x => x.LocationId)
                    .ToListAsync());
            if (ids.Count > 0)
            {
                return ids;
            }
        }

        var fallback = fallbackLocationId?.Trim();
        return string.IsNullOrWhiteSpace(fallback)
            ? new List<string>()
            : new List<string> { fallback };
    }

    public static async Task<Dictionary<string, List<string>>> BuildLocationIdsMapAsync(
        ISqlSugarClient db,
        IReadOnlyList<string> labelIds,
        IReadOnlyDictionary<string, string?> fallbackLocationIdByLabelId)
    {
        var result = new Dictionary<string, List<string>>(StringComparer.Ordinal);
        if (labelIds.Count == 0)
        {
            return result;
        }

        foreach (var labelId in labelIds)
        {
            fallbackLocationIdByLabelId.TryGetValue(labelId, out var fallback);
            result[labelId] = new List<string>();
            if (!string.IsNullOrWhiteSpace(fallback))
            {
                result[labelId].Add(fallback.Trim());
            }
        }

        var schema = await LabelRegionSchemaHelper.GetStatusAsync(db);
        if (!schema.HasLabelLocationTable)
        {
            return result;
        }

        var links = await db.Queryable<FlLabelLocationDbEntity>()
            .Where(x => labelIds.Contains(x.LabelId))
            .ToListAsync();

        foreach (var g in links.GroupBy(x => x.LabelId, StringComparer.Ordinal))
        {
            var ids = LocationScopeBindingHelper.NormalizeIds(g.Select(x => x.LocationId).ToList());
            if (ids.Count > 0)
            {
                result[g.Key] = ids;
            }
        }

        return result;
    }

    public static async Task<LabelRegionScopeDisplay> BuildScopeDisplayAsync(
        ISqlSugarClient db,
        string labelId,
        string? appliedRegionType,
        IReadOnlyList<string> locationIds)
    {
        if (string.Equals(appliedRegionType, AppliedRegionAll, StringComparison.OrdinalIgnoreCase))
        {
            return new LabelRegionScopeDisplay
            {
                Region = AllRegionsDisplay,
                RegionIds = new List<string>(),
                GroupIds = new List<string>()
            };
        }

        var regionIds = await GetRegionIdsForLabelAsync(db, labelId);
        if (regionIds.Count == 0 && locationIds.Count > 0)
        {
            regionIds = await LocationScopeBindingHelper.ResolveGroupIdsFromLocationIdsAsync(db, locationIds.ToList());
        }

        if (regionIds.Count == 0)
        {
            return new LabelRegionScopeDisplay
            {
                Region = "?",
                RegionIds = new List<string>(),
                GroupIds = new List<string>()
            };
        }

        var names = await db.Queryable<FlGroupDbEntity>()
            .Where(g => !g.IsDeleted && regionIds.Contains(g.Id))
            .OrderBy(g => g.GroupName)
            .Select(g => g.GroupName)
            .ToListAsync();
        var regionText = names.Count > 0
            ? string.Join(", ", names.Where(n => !string.IsNullOrWhiteSpace(n)).Select(n => n!.Trim()).Distinct())
            : "?";

        return new LabelRegionScopeDisplay
        {
            Region = regionText,
            RegionIds = regionIds,
            GroupIds = regionIds
        };
    }

    public static async Task<LabelLocationScopeDisplay> BuildLocationDisplayAsync(
        ISqlSugarClient db,
        string? appliedRegionType,
        IReadOnlyList<string> locationIds)
    {
        if (string.Equals(appliedRegionType, AppliedRegionAll, StringComparison.OrdinalIgnoreCase)
            && locationIds.Count == 0)
        {
            return new LabelLocationScopeDisplay
            {
                Location = AllLocationsDisplay,
                LocationIds = new List<string>()
            };
        }

        if (locationIds.Count == 0)
        {
            return new LabelLocationScopeDisplay
            {
                Location = "?",
                LocationIds = new List<string>()
            };
        }

        var guidList = locationIds.Where(x => Guid.TryParse(x, out _)).Select(Guid.Parse).ToList();
        var names = new List<string>();
        if (guidList.Count > 0)
        {
            names = await db.Queryable<LocationAggregateRoot>()
                .Where(x => !x.IsDeleted && guidList.Contains(x.Id))
                .OrderBy(x => x.LocationName)
                .Select(x => x.LocationName ?? x.LocationCode)
                .ToListAsync();
        }

        var locationText = names.Count > 0
            ? string.Join(", ", names.Where(n => !string.IsNullOrWhiteSpace(n)).Select(n => n!.Trim()).Distinct())
            : "?";

        return new LabelLocationScopeDisplay
        {
            Location = locationText,
            LocationIds = locationIds.ToList()
        };
    }

    /// <summary>
    /// ??? Region?<c>fl_group.Id</c>?? scoped ?????
    /// </summary>
    public static ISugarQueryable<FlLabelDbEntity> ApplyLabelRegionListFilter(
        ISqlSugarClient db,
        ISugarQueryable<FlLabelDbEntity> query,
        string groupId,
        List<string>? scopedLocationIds,
        LabelRegionSchemaHelper.LabelRegionSchemaStatus schema)
    {
        var gid = groupId.Trim();
        if (scopedLocationIds is not { Count: > 0 })
        {
            return query.Where(_ => false);
        }

        if (!schema.HasLabelRegionTable && !schema.HasAppliedRegionTypeColumn)
        {
            return ApplyLabelLocationMatchFilter(query, scopedLocationIds, schema);
        }

        if (!schema.HasLabelRegionTable)
        {
            return query.Where(
                "(AppliedRegionType = @all OR LocationId IN (@locs))",
                new { all = AppliedRegionAll, locs = scopedLocationIds });
        }

        if (!schema.HasAppliedRegionTypeColumn)
        {
            if (schema.HasLabelLocationTable)
            {
                return query.Where(
                    """
                    (EXISTS (SELECT 1 FROM fl_label_region lr WHERE lr.LabelId = fl_label.Id AND lr.GroupId = @gid)
                     OR LocationId IN (@locs)
                     OR EXISTS (SELECT 1 FROM fl_label_location ll WHERE ll.LabelId = fl_label.Id AND ll.LocationId IN (@locs)))
                    """,
                    new { gid, locs = scopedLocationIds });
            }

            return query.Where(
                """
                (EXISTS (SELECT 1 FROM fl_label_region lr WHERE lr.LabelId = fl_label.Id AND lr.GroupId = @gid)
                 OR LocationId IN (@locs))
                """,
                new { gid, locs = scopedLocationIds });
        }

        if (schema.HasLabelLocationTable)
        {
            return query.Where(
                """
                (AppliedRegionType = @all
                 OR EXISTS (SELECT 1 FROM fl_label_region lr WHERE lr.LabelId = fl_label.Id AND lr.GroupId = @gid)
                 OR LocationId IN (@locs)
                 OR EXISTS (SELECT 1 FROM fl_label_location ll WHERE ll.LabelId = fl_label.Id AND ll.LocationId IN (@locs)))
                """,
                new { all = AppliedRegionAll, gid, locs = scopedLocationIds });
        }

        return query.Where(
            """
            (AppliedRegionType = @all
             OR EXISTS (SELECT 1 FROM fl_label_region lr WHERE lr.LabelId = fl_label.Id AND lr.GroupId = @gid)
             OR LocationId IN (@locs))
            """,
            new { all = AppliedRegionAll, gid, locs = scopedLocationIds });
    }

    /// <summary>? Region Id ???? scoped ????</summary>
    public static ISugarQueryable<FlLabelDbEntity> ApplyGroupIdListFilter(
        ISqlSugarClient db,
        ISugarQueryable<FlLabelDbEntity> query,
        string groupId,
        LabelRegionSchemaHelper.LabelRegionSchemaStatus schema)
    {
        var gid = groupId.Trim();
        if (!schema.HasLabelRegionTable && !schema.HasAppliedRegionTypeColumn)
        {
            return query.Where(_ => false);
        }

        if (!schema.HasLabelRegionTable)
        {
            return query.Where("AppliedRegionType = @all", new { all = AppliedRegionAll });
        }

        if (!schema.HasAppliedRegionTypeColumn)
        {
            return query.Where(l =>
                SqlFunc.Subqueryable<FlLabelRegionDbEntity>()
                    .Where(lr => lr.LabelId == l.Id && lr.GroupId == gid)
                    .Any());
        }

        return query.Where(
            """
            (AppliedRegionType = @all
             OR EXISTS (SELECT 1 FROM fl_label_region lr WHERE lr.LabelId = fl_label.Id AND lr.GroupId = @gid))
            """,
            new { all = AppliedRegionAll, gid });
    }

    /// <summary>? scoped ?????<c>fl_label_location</c> ???? <c>LocationId</c>??</summary>
    public static ISugarQueryable<FlLabelDbEntity> ApplyLabelLocationListFilter(
        ISqlSugarClient db,
        ISugarQueryable<FlLabelDbEntity> query,
        List<string> scopedLocationIds,
        LabelRegionSchemaHelper.LabelRegionSchemaStatus schema)
    {
        if (scopedLocationIds.Count == 0)
        {
            return query.Where(_ => false);
        }

        return ApplyLabelLocationMatchFilter(query, scopedLocationIds, schema);
    }

    /// <summary>
    /// ?????? Region Id?? App ??/?????
    /// </summary>
    public static async Task<List<string>> ResolveGroupIdsForLocationAsync(ISqlSugarClient db, string locationId)
    {
        return await LocationScopeBindingHelper.ResolveGroupIdsFromLocationIdsAsync(
            db, new List<string> { locationId.Trim() });
    }

    /// <summary>
    /// ??????????????????????
    /// </summary>
    public static async Task EnsureLabelAppliesToLocationAsync(
        ISqlSugarClient db,
        string labelId,
        string locationId)
    {
        var label = await LabelQueryHelper.QueryProjected(db)
            .FirstAsync(x => !x.IsDeleted && x.Id == labelId);
        var groupIds = await ResolveGroupIdsForLocationAsync(db, locationId);
        if (!await LabelAppliesToLocationAsync(db, label, locationId, groupIds))
        {
            throw new UserFriendlyException("??????????????? Region");
        }
    }

    public static async Task<bool> LabelAppliesToLocationAsync(
        ISqlSugarClient db,
        FlLabelDbEntity label,
        string locationId,
        List<string> groupIdsForLocation)
    {
        var appliedType = await LabelRegionSchemaHelper.GetAppliedRegionTypeForLabelAsync(
            db, label.Id, label.AppliedRegionType);

        if (string.Equals(appliedType, AppliedRegionAll, StringComparison.OrdinalIgnoreCase))
        {
            var locationIds = await GetLocationIdsForLabelAsync(db, label.Id, label.LocationId);
            if (locationIds.Count == 0)
            {
                return true;
            }

            return locationIds.Contains(locationId.Trim(), StringComparer.OrdinalIgnoreCase);
        }

        var schema = await LabelRegionSchemaHelper.GetStatusAsync(db);
        if (schema.HasLabelLocationTable)
        {
            var hitLocation = await db.Queryable<FlLabelLocationDbEntity>()
                .AnyAsync(x => x.LabelId == label.Id && x.LocationId == locationId);
            if (hitLocation)
            {
                return true;
            }
        }

        if (!string.IsNullOrWhiteSpace(label.LocationId) &&
            string.Equals(label.LocationId.Trim(), locationId, StringComparison.OrdinalIgnoreCase))
        {
            return true;
        }

        if (groupIdsForLocation.Count == 0)
        {
            return false;
        }

        if (!schema.HasLabelRegionTable)
        {
            return false;
        }

        return await db.Queryable<FlLabelRegionDbEntity>()
            .AnyAsync(lr => lr.LabelId == label.Id && groupIdsForLocation.Contains(lr.GroupId));
    }

    /// <summary>
    /// App labeling-tree 单门店可见性过滤 SQL(多表 join 时 fl_label 别名为 <c>l</c>)。
    /// </summary>
    public static (string Sql, object Parameters) BuildAppLabelingTreeStoreFilterSql(
        LabelRegionSchemaHelper.LabelRegionSchemaStatus schema,
        string locationId,
        IReadOnlyList<string> storeGroupIds)
    {
        var loc = locationId.Trim();
        var groupIds = LocationScopeBindingHelper.NormalizeIds(storeGroupIds);
        var hasLocTable = schema.HasLabelLocationTable;
        var hasRegTable = schema.HasLabelRegionTable;
        var hasAppliedCol = schema.HasAppliedRegionTypeColumn;

        if (!hasAppliedCol)
        {
            return (BuildAppLabelingTreeSpecifiedOnlySql(hasLocTable, hasRegTable, groupIds), new { loc, groupIds });
        }

        var allGlobalSql = hasLocTable
            ? """
              (NOT EXISTS (SELECT 1 FROM fl_label_location ll WHERE ll.LabelId = l.Id)
               AND (l.LocationId IS NULL OR l.LocationId = ''))
              """
            : "(l.LocationId IS NULL OR l.LocationId = '')";

        var locMatchParts = new List<string> { allGlobalSql, "l.LocationId = @loc" };
        if (hasLocTable)
        {
            locMatchParts.Insert(1,
                """
                EXISTS (SELECT 1 FROM fl_label_location ll
                        WHERE ll.LabelId = l.Id AND ll.LocationId = @loc)
                """);
        }

        var allBranchSql = string.Join(" OR ", locMatchParts);

        var specifiedParts = new List<string> { "l.LocationId = @loc" };
        if (hasLocTable)
        {
            specifiedParts.Insert(0,
                """
                EXISTS (SELECT 1 FROM fl_label_location ll
                        WHERE ll.LabelId = l.Id AND ll.LocationId = @loc)
                """);
        }

        if (hasRegTable && groupIds.Count > 0)
        {
            specifiedParts.Add(
                """
                EXISTS (SELECT 1 FROM fl_label_region lr
                        WHERE lr.LabelId = l.Id AND lr.GroupId IN (@groupIds))
                """);
        }

        var specifiedBranchSql = string.Join(" OR ", specifiedParts);

        var sql = $"""
                   ((l.AppliedRegionType = @all AND ({allBranchSql}))
                    OR (l.AppliedRegionType <> @all AND ({specifiedBranchSql})))
                   """;

        return (sql, new { all = AppliedRegionAll, loc, groupIds });
    }

    private static string BuildAppLabelingTreeSpecifiedOnlySql(
        bool hasLocTable,
        bool hasRegTable,
        IReadOnlyList<string> groupIds)
    {
        var parts = new List<string> { "l.LocationId = @loc" };
        if (hasLocTable)
        {
            parts.Insert(0,
                """
                EXISTS (SELECT 1 FROM fl_label_location ll
                        WHERE ll.LabelId = l.Id AND ll.LocationId = @loc)
                """);
        }

        if (hasRegTable && groupIds.Count > 0)
        {
            parts.Add(
                """
                EXISTS (SELECT 1 FROM fl_label_region lr
                        WHERE lr.LabelId = l.Id AND lr.GroupId IN (@groupIds))
                """);
        }

        return $"({string.Join(" OR ", parts)})";
    }

    private static ISugarQueryable<FlLabelDbEntity> ApplyLabelLocationMatchFilter(
        ISugarQueryable<FlLabelDbEntity> query,
        List<string> scopedLocationIds,
        LabelRegionSchemaHelper.LabelRegionSchemaStatus schema)
    {
        if (schema.HasLabelLocationTable)
        {
            return query.Where(
                """
                (LocationId IN (@locs)
                 OR EXISTS (SELECT 1 FROM fl_label_location ll WHERE ll.LabelId = fl_label.Id AND ll.LocationId IN (@locs)))
                """,
                new { locs = scopedLocationIds });
        }

        return query.Where(l => scopedLocationIds.Contains(l.LocationId));
    }

    private static List<string> MergeExplicitLocationIds(string? locationId, IReadOnlyList<string>? locationIds)
    {
        var merged = LocationScopeBindingHelper.NormalizeIds(locationIds);
        var single = locationId?.Trim();
        if (!string.IsNullOrWhiteSpace(single) && !merged.Contains(single, StringComparer.Ordinal))
        {
            merged.Insert(0, single);
        }

        return merged;
    }

    private static List<string> NormalizeRegionIds(
        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 ValidateRegionIdsExistAsync(ISqlSugarClient db, List<string> regionIds)
    {
        if (regionIds.Count == 0)
        {
            return;
        }

        var count = await db.Queryable<FlGroupDbEntity>()
            .Where(g => !g.IsDeleted && regionIds.Contains(g.Id))
            .CountAsync();
        if (count != regionIds.Count)
        {
            throw new UserFriendlyException("????? Region Id???????");
        }
    }
}